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.ContentResolver;
35 import android.content.Context;
36 import android.content.Intent;
37 import android.content.IntentFilter;
38 import android.content.SharedPreferences;
39 import android.content.pm.PackageManager;
40 import android.content.res.Configuration;
41 import android.database.Cursor;
42 import android.graphics.Bitmap;
43 import android.graphics.BitmapFactory;
44 import android.graphics.Typeface;
45 import android.graphics.drawable.BitmapDrawable;
46 import android.graphics.drawable.Drawable;
47 import android.net.Uri;
48 import android.net.http.SslCertificate;
49 import android.net.http.SslError;
50 import android.os.AsyncTask;
51 import android.os.Build;
52 import android.os.Bundle;
53 import android.os.Handler;
54 import android.os.Message;
55 import android.preference.PreferenceManager;
56 import android.print.PrintDocumentAdapter;
57 import android.print.PrintManager;
58 import android.text.Editable;
59 import android.text.Spanned;
60 import android.text.TextWatcher;
61 import android.text.style.ForegroundColorSpan;
62 import android.util.Patterns;
63 import android.util.TypedValue;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.ViewGroup;
72 import android.view.WindowManager;
73 import android.view.inputmethod.InputMethodManager;
74 import android.webkit.CookieManager;
75 import android.webkit.HttpAuthHandler;
76 import android.webkit.SslErrorHandler;
77 import android.webkit.ValueCallback;
78 import android.webkit.WebBackForwardList;
79 import android.webkit.WebChromeClient;
80 import android.webkit.WebResourceResponse;
81 import android.webkit.WebSettings;
82 import android.webkit.WebStorage;
83 import android.webkit.WebView;
84 import android.webkit.WebViewClient;
85 import android.webkit.WebViewDatabase;
86 import android.widget.ArrayAdapter;
87 import android.widget.CursorAdapter;
88 import android.widget.EditText;
89 import android.widget.FrameLayout;
90 import android.widget.ImageView;
91 import android.widget.LinearLayout;
92 import android.widget.ListView;
93 import android.widget.ProgressBar;
94 import android.widget.RadioButton;
95 import android.widget.RelativeLayout;
96 import android.widget.TextView;
98 import androidx.annotation.NonNull;
99 import androidx.appcompat.app.ActionBar;
100 import androidx.appcompat.app.ActionBarDrawerToggle;
101 import androidx.appcompat.app.AppCompatActivity;
102 import androidx.appcompat.app.AppCompatDelegate;
103 import androidx.appcompat.widget.Toolbar;
104 import androidx.coordinatorlayout.widget.CoordinatorLayout;
105 import androidx.core.app.ActivityCompat;
106 import androidx.core.content.ContextCompat;
107 import androidx.core.content.FileProvider;
108 import androidx.core.content.res.ResourcesCompat;
109 import androidx.core.view.GravityCompat;
110 import androidx.drawerlayout.widget.DrawerLayout;
111 import androidx.fragment.app.DialogFragment;
112 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
113 import androidx.viewpager.widget.ViewPager;
114 import androidx.webkit.WebSettingsCompat;
115 import androidx.webkit.WebViewFeature;
117 import com.google.android.material.appbar.AppBarLayout;
118 import com.google.android.material.floatingactionbutton.FloatingActionButton;
119 import com.google.android.material.navigation.NavigationView;
120 import com.google.android.material.snackbar.Snackbar;
121 import com.google.android.material.tabs.TabLayout;
123 import com.stoutner.privacybrowser.BuildConfig;
124 import com.stoutner.privacybrowser.R;
125 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
126 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
127 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
128 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
129 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
130 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
131 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
132 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
133 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
134 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
135 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
136 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
137 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
138 import com.stoutner.privacybrowser.dialogs.OpenDialog;
139 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
140 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
141 import com.stoutner.privacybrowser.dialogs.SaveWebpageDialog;
142 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
143 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
144 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
145 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
146 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
147 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
148 import com.stoutner.privacybrowser.helpers.AdHelper;
149 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
150 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
151 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
152 import com.stoutner.privacybrowser.helpers.FileNameHelper;
153 import com.stoutner.privacybrowser.helpers.ProxyHelper;
154 import com.stoutner.privacybrowser.views.NestedScrollWebView;
156 import java.io.ByteArrayInputStream;
157 import java.io.ByteArrayOutputStream;
159 import java.io.IOException;
160 import java.io.UnsupportedEncodingException;
161 import java.net.MalformedURLException;
163 import java.net.URLDecoder;
164 import java.net.URLEncoder;
165 import java.text.NumberFormat;
166 import java.util.ArrayList;
167 import java.util.Date;
168 import java.util.HashMap;
169 import java.util.HashSet;
170 import java.util.List;
171 import java.util.Map;
172 import java.util.Objects;
173 import java.util.Set;
174 import java.util.concurrent.ExecutorService;
175 import java.util.concurrent.Executors;
177 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
178 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
179 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageDialog.SaveWebpageListener, StoragePermissionDialog.StoragePermissionDialogListener,
180 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
182 // The executor service handles background tasks. It is accessed from `ViewSourceActivity`.
183 public static ExecutorService executorService = Executors.newFixedThreadPool(4);
185 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
186 public static String orbotStatus = "unknown";
188 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
189 public static WebViewPagerAdapter webViewPagerAdapter;
191 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
192 public static boolean restartFromBookmarksActivity;
194 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
195 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
196 public static String currentBookmarksFolder;
198 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
199 public final static int UNRECOGNIZED_USER_AGENT = -1;
200 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
201 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
202 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
203 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
204 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
206 // Start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
207 public final static int BROWSE_OPEN_REQUEST_CODE = 0;
208 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 1;
209 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 2;
211 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
212 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
213 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
214 public static String proxyMode = ProxyHelper.NONE;
216 // Define the saved instance state constants.
217 private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
218 private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
219 private final String SAVED_TAB_POSITION = "saved_tab_position";
220 private final String PROXY_MODE = "proxy_mode";
222 // Define the saved instance state variables.
223 private ArrayList<Bundle> savedStateArrayList;
224 private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
225 private int savedTabPosition;
226 private String savedProxyMode;
228 // Define the class variables.
229 @SuppressWarnings("rawtypes")
230 AsyncTask populateBlocklists;
232 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
233 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
234 private NestedScrollWebView currentWebView;
236 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
237 private final Map<String, String> customHeaders = new HashMap<>();
239 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
240 private String searchURL;
242 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
243 private ArrayList<List<String[]>> easyList;
244 private ArrayList<List<String[]>> easyPrivacy;
245 private ArrayList<List<String[]>> fanboysAnnoyanceList;
246 private ArrayList<List<String[]>> fanboysSocialList;
247 private ArrayList<List<String[]>> ultraList;
248 private ArrayList<List<String[]>> ultraPrivacy;
250 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
251 private String webViewDefaultUserAgent;
253 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
254 private boolean incognitoModeEnabled;
256 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
257 private boolean fullScreenBrowsingModeEnabled;
259 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
260 private boolean inFullScreenBrowsingMode;
262 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
263 private boolean hideAppBar;
264 private boolean scrollAppBar;
266 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
267 private boolean loadingNewIntent;
269 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
270 private boolean reapplyDomainSettingsOnRestart;
272 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
273 private boolean reapplyAppSettingsOnRestart;
275 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
276 private boolean displayingFullScreenVideo;
278 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
279 private BroadcastReceiver orbotStatusBroadcastReceiver;
281 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
282 private boolean waitingForProxy = false;
284 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
285 private ActionBarDrawerToggle actionBarDrawerToggle;
287 // The color spans are used in `onCreate()` and `highlightUrlText()`.
288 private ForegroundColorSpan redColorSpan;
289 private ForegroundColorSpan initialGrayColorSpan;
290 private ForegroundColorSpan finalGrayColorSpan;
292 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
293 // and `loadBookmarksFolder()`.
294 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
296 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
297 private Cursor bookmarksCursor;
299 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
300 private CursorAdapter bookmarksCursorAdapter;
302 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
303 private String oldFolderNameString;
305 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
306 private ValueCallback<Uri[]> fileChooserCallback;
308 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
309 private int appBarHeight;
310 private int defaultProgressViewStartOffset;
311 private int defaultProgressViewEndOffset;
313 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
314 private boolean sanitizeGoogleAnalytics;
315 private boolean sanitizeFacebookClickIds;
316 private boolean sanitizeTwitterAmpRedirects;
318 // The file path strings are used in `onSaveWebpage()` and `onRequestPermissionResult()`
319 private String openFilePath;
320 private String saveWebpageUrl;
321 private String saveWebpageFilePath;
323 // Declare the class views.
324 private DrawerLayout drawerLayout;
325 private AppBarLayout appBarLayout;
326 private Toolbar toolbar;
327 private LinearLayout findOnPageLinearLayout;
328 private LinearLayout tabsLinearLayout;
329 private TabLayout tabLayout;
330 private SwipeRefreshLayout swipeRefreshLayout;
331 private ViewPager webViewPager;
333 // Declare the class menus.
334 private Menu optionsMenu;
336 // Declare the class menu items.
337 private MenuItem navigationBackMenuItem;
338 private MenuItem navigationForwardMenuItem;
339 private MenuItem navigationHistoryMenuItem;
340 private MenuItem navigationRequestsMenuItem;
341 private MenuItem optionsPrivacyMenuItem;
342 private MenuItem optionsRefreshMenuItem;
343 private MenuItem optionsFirstPartyCookiesMenuItem;
344 private MenuItem optionsThirdPartyCookiesMenuItem;
345 private MenuItem optionsDomStorageMenuItem;
346 private MenuItem optionsSaveFormDataMenuItem;
347 private MenuItem optionsClearDataMenuItem;
348 private MenuItem optionsClearCookiesMenuItem;
349 private MenuItem optionsClearDomStorageMenuItem;
350 private MenuItem optionsClearFormDataMenuItem;
351 private MenuItem optionsBlocklistsMenuItem;
352 private MenuItem optionsEasyListMenuItem;
353 private MenuItem optionsEasyPrivacyMenuItem;
354 private MenuItem optionsFanboysAnnoyanceListMenuItem;
355 private MenuItem optionsFanboysSocialBlockingListMenuItem;
356 private MenuItem optionsUltraListMenuItem;
357 private MenuItem optionsUltraPrivacyMenuItem;
358 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
359 private MenuItem optionsProxyMenuItem;
360 private MenuItem optionsProxyNoneMenuItem;
361 private MenuItem optionsProxyTorMenuItem;
362 private MenuItem optionsProxyI2pMenuItem;
363 private MenuItem optionsProxyCustomMenuItem;
364 private MenuItem optionsUserAgentMenuItem;
365 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
366 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
367 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
368 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
369 private MenuItem optionsUserAgentSafariOnIosMenuItem;
370 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
371 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
372 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
373 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
374 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
375 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
376 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
377 private MenuItem optionsUserAgentCustomMenuItem;
378 private MenuItem optionsSwipeToRefreshMenuItem;
379 private MenuItem optionsWideViewportMenuItem;
380 private MenuItem optionsDisplayImagesMenuItem;
381 private MenuItem optionsDarkWebViewMenuItem;
382 private MenuItem optionsFontSizeMenuItem;
383 private MenuItem optionsAddOrEditDomainMenuItem;
386 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
387 @SuppressLint("ClickableViewAccessibility")
388 protected void onCreate(Bundle savedInstanceState) {
389 // Run the default commands.
390 super.onCreate(savedInstanceState);
392 // Check to see if the activity has been restarted.
393 if (savedInstanceState != null) {
394 // Store the saved instance state variables.
395 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
396 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
397 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
398 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
401 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
402 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
404 // Get a handle for the shared preferences.
405 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
407 // Get the screenshot preference.
408 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
409 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
411 // Get the theme entry values string array.
412 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
414 // 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.
415 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
416 // Apply the light theme.
417 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
418 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
419 // Apply the dark theme.
420 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
421 } else { // The system default theme is selected.
422 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
423 // Follow the system default theme.
424 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
425 } else { // The system default theme is not supported.
426 // Follow the battery saver mode.
427 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
431 // Disable screenshots if not allowed.
432 if (!allowScreenshots) {
433 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
436 // 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.
437 if (Build.VERSION.SDK_INT >= 21) {
438 WebView.enableSlowWholeDocumentDraw();
442 setTheme(R.style.PrivacyBrowser);
444 // Set the content view.
445 setContentView(R.layout.main_framelayout);
447 // Get handles for the views.
448 drawerLayout = findViewById(R.id.drawerlayout);
449 appBarLayout = findViewById(R.id.appbar_layout);
450 toolbar = findViewById(R.id.toolbar);
451 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
452 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
453 tabLayout = findViewById(R.id.tablayout);
454 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
455 webViewPager = findViewById(R.id.webviewpager);
457 // Get a handle for the navigation view.
458 NavigationView navigationView = findViewById(R.id.navigationview);
460 // Get a handle for the navigation menu.
461 Menu navigationMenu = navigationView.getMenu();
463 // Get handles for the navigation menu items.
464 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
465 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
466 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
467 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
469 // Listen for touches on the navigation menu.
470 navigationView.setNavigationItemSelectedListener(this);
472 // Get a handle for the app compat delegate.
473 AppCompatDelegate appCompatDelegate = getDelegate();
475 // Set the support action bar.
476 appCompatDelegate.setSupportActionBar(toolbar);
478 // Get a handle for the action bar.
479 ActionBar actionBar = appCompatDelegate.getSupportActionBar();
481 // This is needed to get rid of the Android Studio warning that the action bar might be null.
482 assert actionBar != null;
484 // Add the custom layout, which shows the URL text bar.
485 actionBar.setCustomView(R.layout.url_app_bar);
486 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
488 // Create the hamburger icon at the start of the AppBar.
489 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
491 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
492 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
494 // Initialize the web view pager adapter.
495 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
497 // Set the pager adapter on the web view pager.
498 webViewPager.setAdapter(webViewPagerAdapter);
500 // Store up to 100 tabs in memory.
501 webViewPager.setOffscreenPageLimit(100);
503 // Initialize the app.
506 // Apply the app settings from the shared preferences.
509 // Populate the blocklists.
510 populateBlocklists = new PopulateBlocklists(this, this).execute();
514 protected void onNewIntent(Intent intent) {
515 // Run the default commands.
516 super.onNewIntent(intent);
518 // Replace the intent that started the app with this one.
521 // Check to see if the app is being restarted from a saved state.
522 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
523 // Get the information from the intent.
524 String intentAction = intent.getAction();
525 Uri intentUriData = intent.getData();
526 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
528 // Determine if this is a web search.
529 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
531 // 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.
532 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
533 // Get the shared preferences.
534 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
536 // Create a URL string.
539 // If the intent action is a web search, perform the search.
540 if (isWebSearch) { // The intent is a web search.
541 // Create an encoded URL string.
542 String encodedUrlString;
544 // Sanitize the search input and convert it to a search.
546 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
547 } catch (UnsupportedEncodingException exception) {
548 encodedUrlString = "";
551 // Add the base search URL.
552 url = searchURL + encodedUrlString;
553 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
554 // Set the intent data as the URL.
555 url = intentUriData.toString();
556 } else { // The intent contains a string, which might be a URL.
557 // Set the intent string as the URL.
558 url = intentStringExtra;
561 // Add a new tab if specified in the preferences.
562 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
563 // Set the loading new intent flag.
564 loadingNewIntent = true;
567 addNewTab(url, true);
568 } else { // Load the URL in the current tab.
570 loadUrl(currentWebView, url);
573 // Close the navigation drawer if it is open.
574 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
575 drawerLayout.closeDrawer(GravityCompat.START);
578 // Close the bookmarks drawer if it is open.
579 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
580 drawerLayout.closeDrawer(GravityCompat.END);
587 public void onRestart() {
588 // Run the default commands.
591 // Apply the app settings if returning from the Settings activity.
592 if (reapplyAppSettingsOnRestart) {
593 // Reset the reapply app settings on restart tracker.
594 reapplyAppSettingsOnRestart = false;
596 // Apply the app settings.
600 // Apply the domain settings if returning from the settings or domains activity.
601 if (reapplyDomainSettingsOnRestart) {
602 // Reset the reapply domain settings on restart tracker.
603 reapplyDomainSettingsOnRestart = false;
605 // Reapply the domain settings for each tab.
606 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
607 // Get the WebView tab fragment.
608 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
610 // Get the fragment view.
611 View fragmentView = webViewTabFragment.getView();
613 // Only reload the WebViews if they exist.
614 if (fragmentView != null) {
615 // Get the nested scroll WebView from the tab fragment.
616 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
618 // Reset the current domain name so the domain settings will be reapplied.
619 nestedScrollWebView.resetCurrentDomainName();
621 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
622 if (nestedScrollWebView.getUrl() != null) {
623 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
629 // Update the bookmarks drawer if returning from the Bookmarks activity.
630 if (restartFromBookmarksActivity) {
631 // Close the bookmarks drawer.
632 drawerLayout.closeDrawer(GravityCompat.END);
634 // Reload the bookmarks drawer.
635 loadBookmarksFolder();
637 // Reset `restartFromBookmarksActivity`.
638 restartFromBookmarksActivity = false;
641 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
642 updatePrivacyIcons(true);
645 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
647 public void onResume() {
648 // Run the default commands.
651 // Resume any WebViews.
652 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
653 // Get the WebView tab fragment.
654 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
656 // Get the fragment view.
657 View fragmentView = webViewTabFragment.getView();
659 // Only resume the WebViews if they exist (they won't when the app is first created).
660 if (fragmentView != null) {
661 // Get the nested scroll WebView from the tab fragment.
662 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
664 // Resume the nested scroll WebView.
665 nestedScrollWebView.onResume();
669 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
670 if (currentWebView != null) {
671 currentWebView.resumeTimers();
674 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
675 if (!proxyMode.equals(ProxyHelper.NONE)) {
679 // Reapply any system UI flags and the ad in the free flavor.
680 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
681 // Get a handle for the root frame layouts.
682 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
684 /* Hide the system bars.
685 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
686 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
687 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
688 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
690 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
691 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
692 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
694 AdHelper.resumeAd(findViewById(R.id.adview));
699 public void onPause() {
700 // Run the default commands.
703 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
704 // Get the WebView tab fragment.
705 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
707 // Get the fragment view.
708 View fragmentView = webViewTabFragment.getView();
710 // Only pause the WebViews if they exist (they won't when the app is first created).
711 if (fragmentView != null) {
712 // Get the nested scroll WebView from the tab fragment.
713 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
715 // Pause the nested scroll WebView.
716 nestedScrollWebView.onPause();
720 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
721 if (currentWebView != null) {
722 currentWebView.pauseTimers();
725 // Pause the ad or it will continue to consume resources in the background on the free flavor.
726 if (BuildConfig.FLAVOR.contentEquals("free")) {
728 AdHelper.pauseAd(findViewById(R.id.adview));
733 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
734 // Run the default commands.
735 super.onSaveInstanceState(savedInstanceState);
737 // Create the saved state array lists.
738 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
739 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
741 // Get the URLs from each tab.
742 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
743 // Get the WebView tab fragment.
744 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
746 // Get the fragment view.
747 View fragmentView = webViewTabFragment.getView();
749 if (fragmentView != null) {
750 // Get the nested scroll WebView from the tab fragment.
751 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
753 // Create saved state bundle.
754 Bundle savedStateBundle = new Bundle();
756 // Get the current states.
757 nestedScrollWebView.saveState(savedStateBundle);
758 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
760 // Store the saved states in the array lists.
761 savedStateArrayList.add(savedStateBundle);
762 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
766 // Get the current tab position.
767 int currentTabPosition = tabLayout.getSelectedTabPosition();
769 // Store the saved states in the bundle.
770 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
771 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
772 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
773 savedInstanceState.putString(PROXY_MODE, proxyMode);
777 public void onDestroy() {
778 // Unregister the orbot status broadcast receiver if it exists.
779 if (orbotStatusBroadcastReceiver != null) {
780 this.unregisterReceiver(orbotStatusBroadcastReceiver);
783 // Close the bookmarks cursor if it exists.
784 if (bookmarksCursor != null) {
785 bookmarksCursor.close();
788 // Close the bookmarks database if it exists.
789 if (bookmarksDatabaseHelper != null) {
790 bookmarksDatabaseHelper.close();
793 // Stop populating the blocklists if the AsyncTask is running in the background.
794 if (populateBlocklists != null) {
795 populateBlocklists.cancel(true);
798 // Run the default commands.
803 public boolean onCreateOptionsMenu(Menu menu) {
804 // Inflate the menu. This adds items to the action bar if it is present.
805 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
807 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
810 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
811 updatePrivacyIcons(false);
813 // Get handles for the class menu items.
814 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
815 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
816 optionsFirstPartyCookiesMenuItem = menu.findItem(R.id.first_party_cookies);
817 optionsThirdPartyCookiesMenuItem = menu.findItem(R.id.third_party_cookies);
818 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
819 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
820 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
821 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
822 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
823 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
824 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
825 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
826 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
827 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
828 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
829 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
830 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
831 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
832 optionsProxyMenuItem = menu.findItem(R.id.proxy);
833 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
834 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
835 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
836 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
837 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
838 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
839 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
840 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
841 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
842 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
843 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
844 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
845 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
846 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
847 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
848 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
849 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
850 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
851 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
852 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
853 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
854 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
855 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
856 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
858 // Get handles for the method menu items.
859 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
860 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
862 // Only display third-party cookies if API >= 21
863 optionsThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
865 // Only display the form data menu items if the API < 26.
866 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
867 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
869 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
870 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
872 // Only display the dark WebView menu item if API >= 21.
873 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
875 // Only show Ad Consent if this is the free flavor.
876 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
878 // Get the shared preferences.
879 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
881 // Get the dark theme and app bar preferences.
882 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
884 // 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.
885 if (displayAdditionalAppBarIcons) {
886 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
887 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
888 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
889 } else { //Do not display the additional icons.
890 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
891 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
892 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
895 // Replace Refresh with Stop if a URL is already loading.
896 if (currentWebView != null && currentWebView.getProgress() != 100) {
898 optionsRefreshMenuItem.setTitle(R.string.stop);
900 // Set the icon if it is displayed in the app bar.
901 if (displayAdditionalAppBarIcons) {
902 // Get the current theme status.
903 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
905 // Set the icon according to the current theme status.
906 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
907 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
909 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
919 public boolean onPrepareOptionsMenu(Menu menu) {
920 // Get a handle for the cookie manager.
921 CookieManager cookieManager = CookieManager.getInstance();
923 // Initialize the current user agent string and the font size.
924 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
927 // 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.
928 if (currentWebView != null) {
929 // Set the add or edit domain text.
930 if (currentWebView.getDomainSettingsApplied()) {
931 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
933 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
936 // Get the current user agent from the WebView.
937 currentUserAgent = currentWebView.getSettings().getUserAgentString();
939 // Get the current font size from the
940 fontSize = currentWebView.getSettings().getTextZoom();
942 // Set the status of the menu item checkboxes.
943 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
944 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
945 optionsEasyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
946 optionsEasyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
947 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
948 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
949 optionsUltraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
950 optionsUltraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
951 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
952 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
953 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
954 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
956 // Initialize the display names for the blocklists with the number of blocked requests.
957 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
958 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
959 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
960 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
961 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
962 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
963 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
964 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
966 // Only modify third-party cookies if the API >= 21.
967 if (Build.VERSION.SDK_INT >= 21) {
968 // Set the status of the third-party cookies checkbox.
969 optionsThirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
971 // Enable third-party cookies if first-party cookies are enabled.
972 optionsThirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
975 // Enable DOM Storage if JavaScript is enabled.
976 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
978 // Set the checkbox status for dark WebView if the WebView supports it.
979 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
980 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
984 // Set the checked status of the first party cookies menu item.
985 optionsFirstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
987 // Enable Clear Cookies if there are any.
988 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
990 // 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`.
991 String privateDataDirectoryString = getApplicationInfo().dataDir;
993 // Get a count of the number of files in the Local Storage directory.
994 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
995 int localStorageDirectoryNumberOfFiles = 0;
996 if (localStorageDirectory.exists()) {
997 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
998 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1001 // Get a count of the number of files in the IndexedDB directory.
1002 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1003 int indexedDBDirectoryNumberOfFiles = 0;
1004 if (indexedDBDirectory.exists()) {
1005 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1006 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1009 // Enable Clear DOM Storage if there is any.
1010 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1012 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1013 if (Build.VERSION.SDK_INT < 26) {
1014 // Get the WebView database.
1015 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1017 // Enable the clear form data menu item if there is anything to clear.
1018 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1021 // Enable Clear Data if any of the submenu items are enabled.
1022 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1024 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1025 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1027 // Set the proxy title and check the applied proxy.
1028 switch (proxyMode) {
1029 case ProxyHelper.NONE:
1030 // Set the proxy title.
1031 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1033 // Check the proxy None radio button.
1034 optionsProxyNoneMenuItem.setChecked(true);
1037 case ProxyHelper.TOR:
1038 // Set the proxy title.
1039 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1041 // Check the proxy Tor radio button.
1042 optionsProxyTorMenuItem.setChecked(true);
1045 case ProxyHelper.I2P:
1046 // Set the proxy title.
1047 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1049 // Check the proxy I2P radio button.
1050 optionsProxyI2pMenuItem.setChecked(true);
1053 case ProxyHelper.CUSTOM:
1054 // Set the proxy title.
1055 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1057 // Check the proxy Custom radio button.
1058 optionsProxyCustomMenuItem.setChecked(true);
1062 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1063 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1064 // Update the user agent menu item title.
1065 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1067 // Select the Privacy Browser radio box.
1068 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1069 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1070 // Update the user agent menu item title.
1071 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1073 // Select the WebView Default radio box.
1074 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1075 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1076 // Update the user agent menu item title.
1077 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1079 // Select the Firefox on Android radio box.
1080 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1081 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1082 // Update the user agent menu item title.
1083 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1085 // Select the Chrome on Android radio box.
1086 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1087 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1088 // Update the user agent menu item title.
1089 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1091 // Select the Safari on iOS radio box.
1092 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1093 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1094 // Update the user agent menu item title.
1095 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1097 // Select the Firefox on Linux radio box.
1098 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1099 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1100 // Update the user agent menu item title.
1101 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1103 // Select the Chromium on Linux radio box.
1104 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1105 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1106 // Update the user agent menu item title.
1107 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1109 // Select the Firefox on Windows radio box.
1110 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1111 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1112 // Update the user agent menu item title.
1113 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1115 // Select the Chrome on Windows radio box.
1116 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1117 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1118 // Update the user agent menu item title.
1119 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1121 // Select the Edge on Windows radio box.
1122 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1123 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1124 // Update the user agent menu item title.
1125 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1127 // Select the Internet on Windows radio box.
1128 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1129 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1130 // Update the user agent menu item title.
1131 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1133 // Select the Safari on macOS radio box.
1134 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1135 } else { // Custom user agent.
1136 // Update the user agent menu item title.
1137 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1139 // Select the Custom radio box.
1140 optionsUserAgentCustomMenuItem.setChecked(true);
1143 // Set the font size title.
1144 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1146 // Run all the other default commands.
1147 super.onPrepareOptionsMenu(menu);
1149 // Display the menu.
1154 public boolean onOptionsItemSelected(MenuItem menuItem) {
1155 // Get a handle for the shared preferences.
1156 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1158 // Get a handle for the cookie manager.
1159 CookieManager cookieManager = CookieManager.getInstance();
1161 // Get the selected menu item ID.
1162 int menuItemId = menuItem.getItemId();
1164 // Run the commands that correlate to the selected menu item.
1165 if (menuItemId == R.id.javascript) { // JavaScript.
1166 // Toggle the JavaScript status.
1167 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1169 // Update the privacy icon.
1170 updatePrivacyIcons(true);
1172 // Display a `Snackbar`.
1173 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1174 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1175 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1176 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1177 } else { // Privacy mode.
1178 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1181 // Reload the current WebView.
1182 currentWebView.reload();
1184 // Consume the event.
1186 } else if (menuItemId == R.id.refresh) { // Refresh.
1187 // Run the command that correlates to the current status of the menu item.
1188 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1189 // Reload the current WebView.
1190 currentWebView.reload();
1191 } else { // The stop button was pushed.
1192 // Stop the loading of the WebView.
1193 currentWebView.stopLoading();
1196 // Consume the event.
1198 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1199 // Open the bookmarks drawer.
1200 drawerLayout.openDrawer(GravityCompat.END);
1202 // Consume the event.
1204 } else if (menuItemId == R.id.first_party_cookies) { // First-party cookies.
1205 // Switch the first-party cookie status.
1206 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1208 // Store the first-party cookie status.
1209 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1211 // Update the menu checkbox.
1212 menuItem.setChecked(cookieManager.acceptCookie());
1214 // Update the privacy icon.
1215 updatePrivacyIcons(true);
1217 // Display a snackbar.
1218 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1219 Snackbar.make(webViewPager, R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1220 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1221 Snackbar.make(webViewPager, R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1222 } else { // Privacy mode.
1223 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1226 // Reload the current WebView.
1227 currentWebView.reload();
1229 // Consume the event.
1231 } else if (menuItemId == R.id.third_party_cookies) { // Third-party cookies.
1232 // Only act if the API >= 21. Otherwise, there are no third-party cookie controls.
1233 if (Build.VERSION.SDK_INT >= 21) {
1234 // Toggle the status of thirdPartyCookiesEnabled.
1235 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1237 // Update the menu checkbox.
1238 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1240 // Display a snackbar.
1241 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1242 Snackbar.make(webViewPager, R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1244 Snackbar.make(webViewPager, R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1247 // Reload the current WebView.
1248 currentWebView.reload();
1251 // Consume the event.
1253 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1254 // Toggle the status of domStorageEnabled.
1255 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1257 // Update the menu checkbox.
1258 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1260 // Update the privacy icon.
1261 updatePrivacyIcons(true);
1263 // Display a snackbar.
1264 if (currentWebView.getSettings().getDomStorageEnabled()) {
1265 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1267 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1270 // Reload the current WebView.
1271 currentWebView.reload();
1273 // Consume the event.
1275 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1276 // Switch the status of saveFormDataEnabled.
1277 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1279 // Update the menu checkbox.
1280 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1282 // Display a snackbar.
1283 if (currentWebView.getSettings().getSaveFormData()) {
1284 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1286 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1289 // Update the privacy icon.
1290 updatePrivacyIcons(true);
1292 // Reload the current WebView.
1293 currentWebView.reload();
1295 // Consume the event.
1297 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1298 // Create a snackbar.
1299 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1300 .setAction(R.string.undo, v -> {
1301 // Do nothing because everything will be handled by `onDismissed()` below.
1303 .addCallback(new Snackbar.Callback() {
1305 public void onDismissed(Snackbar snackbar, int event) {
1306 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1307 // Delete the cookies, which command varies by SDK.
1308 if (Build.VERSION.SDK_INT < 21) {
1309 cookieManager.removeAllCookie();
1311 cookieManager.removeAllCookies(null);
1318 // Consume the event.
1320 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1321 // Create a snackbar.
1322 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1323 .setAction(R.string.undo, v -> {
1324 // Do nothing because everything will be handled by `onDismissed()` below.
1326 .addCallback(new Snackbar.Callback() {
1328 public void onDismissed(Snackbar snackbar, int event) {
1329 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1330 // Delete the DOM Storage.
1331 WebStorage webStorage = WebStorage.getInstance();
1332 webStorage.deleteAllData();
1334 // Initialize a handler to manually delete the DOM storage files and directories.
1335 Handler deleteDomStorageHandler = new Handler();
1337 // Setup a runnable to manually delete the DOM storage files and directories.
1338 Runnable deleteDomStorageRunnable = () -> {
1340 // Get a handle for the runtime.
1341 Runtime runtime = Runtime.getRuntime();
1343 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1344 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1345 String privateDataDirectoryString = getApplicationInfo().dataDir;
1347 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1348 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1350 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1351 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1352 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1353 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1354 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1356 // Wait for the processes to finish.
1357 deleteLocalStorageProcess.waitFor();
1358 deleteIndexProcess.waitFor();
1359 deleteQuotaManagerProcess.waitFor();
1360 deleteQuotaManagerJournalProcess.waitFor();
1361 deleteDatabasesProcess.waitFor();
1362 } catch (Exception exception) {
1363 // Do nothing if an error is thrown.
1367 // Manually delete the DOM storage files after 200 milliseconds.
1368 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1374 // Consume the event.
1376 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1377 // Create a snackbar.
1378 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1379 .setAction(R.string.undo, v -> {
1380 // Do nothing because everything will be handled by `onDismissed()` below.
1382 .addCallback(new Snackbar.Callback() {
1384 public void onDismissed(Snackbar snackbar, int event) {
1385 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1386 // Get a handle for the webView database.
1387 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1389 // Delete the form data.
1390 webViewDatabase.clearFormData();
1396 // Consume the event.
1398 } else if (menuItemId == R.id.easylist) { // EasyList.
1399 // Toggle the EasyList status.
1400 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1402 // Update the menu checkbox.
1403 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1405 // Reload the current WebView.
1406 currentWebView.reload();
1408 // Consume the event.
1410 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1411 // Toggle the EasyPrivacy status.
1412 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1414 // Update the menu checkbox.
1415 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1417 // Reload the current WebView.
1418 currentWebView.reload();
1420 // Consume the event.
1422 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1423 // Toggle Fanboy's Annoyance List status.
1424 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1426 // Update the menu checkbox.
1427 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1429 // Update the staus of Fanboy's Social Blocking List.
1430 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1432 // Reload the current WebView.
1433 currentWebView.reload();
1435 // Consume the event.
1437 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1438 // Toggle Fanboy's Social Blocking List status.
1439 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1441 // Update the menu checkbox.
1442 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1444 // Reload the current WebView.
1445 currentWebView.reload();
1447 // Consume the event.
1449 } else if (menuItemId == R.id.ultralist) { // UltraList.
1450 // Toggle the UltraList status.
1451 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1453 // Update the menu checkbox.
1454 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1456 // Reload the current WebView.
1457 currentWebView.reload();
1459 // Consume the event.
1461 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1462 // Toggle the UltraPrivacy status.
1463 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1465 // Update the menu checkbox.
1466 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1468 // Reload the current WebView.
1469 currentWebView.reload();
1471 // Consume the event.
1473 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1474 //Toggle the third-party requests blocker status.
1475 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1477 // Update the menu checkbox.
1478 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1480 // Reload the current WebView.
1481 currentWebView.reload();
1483 // Consume the event.
1485 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1486 // Update the proxy mode.
1487 proxyMode = ProxyHelper.NONE;
1489 // Apply the proxy mode.
1492 // Consume the event.
1494 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1495 // Update the proxy mode.
1496 proxyMode = ProxyHelper.TOR;
1498 // Apply the proxy mode.
1501 // Consume the event.
1503 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1504 // Update the proxy mode.
1505 proxyMode = ProxyHelper.I2P;
1507 // Apply the proxy mode.
1510 // Consume the event.
1512 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1513 // Update the proxy mode.
1514 proxyMode = ProxyHelper.CUSTOM;
1516 // Apply the proxy mode.
1519 // Consume the event.
1521 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1522 // Update the user agent.
1523 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1525 // Reload the current WebView.
1526 currentWebView.reload();
1528 // Consume the event.
1530 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1531 // Update the user agent.
1532 currentWebView.getSettings().setUserAgentString("");
1534 // Reload the current WebView.
1535 currentWebView.reload();
1537 // Consume the event.
1539 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1540 // Update the user agent.
1541 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1543 // Reload the current WebView.
1544 currentWebView.reload();
1546 // Consume the event.
1548 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1549 // Update the user agent.
1550 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1552 // Reload the current WebView.
1553 currentWebView.reload();
1555 // Consume the event.
1557 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1558 // Update the user agent.
1559 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1561 // Reload the current WebView.
1562 currentWebView.reload();
1564 // Consume the event.
1566 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1567 // Update the user agent.
1568 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1570 // Reload the current WebView.
1571 currentWebView.reload();
1573 // Consume the event.
1575 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1576 // Update the user agent.
1577 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1579 // Reload the current WebView.
1580 currentWebView.reload();
1582 // Consume the event.
1584 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1585 // Update the user agent.
1586 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1588 // Reload the current WebView.
1589 currentWebView.reload();
1591 // Consume the event.
1593 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1594 // Update the user agent.
1595 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1597 // Reload the current WebView.
1598 currentWebView.reload();
1600 // Consume the event.
1602 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1603 // Update the user agent.
1604 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1606 // Reload the current WebView.
1607 currentWebView.reload();
1609 // Consume the event.
1611 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1612 // Update the user agent.
1613 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1615 // Reload the current WebView.
1616 currentWebView.reload();
1618 // Consume the event.
1620 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1621 // Update the user agent.
1622 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1624 // Reload the current WebView.
1625 currentWebView.reload();
1627 // Consume the event.
1629 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1630 // Update the user agent.
1631 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1633 // Reload the current WebView.
1634 currentWebView.reload();
1636 // Consume the event.
1638 } else if (menuItemId == R.id.font_size) { // Font size.
1639 // Instantiate the font size dialog.
1640 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1642 // Show the font size dialog.
1643 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1645 // Consume the event.
1647 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1648 // Toggle the stored status of swipe to refresh.
1649 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1651 // Get a handle for the swipe refresh layout.
1652 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1654 // Update the swipe refresh layout.
1655 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1656 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1657 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1658 } else { // Swipe to refresh is disabled.
1659 // Disable the swipe refresh layout.
1660 swipeRefreshLayout.setEnabled(false);
1663 // Consume the event.
1665 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1666 // Toggle the viewport.
1667 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1669 // Consume the event.
1671 } else if (menuItemId == R.id.display_images) { // Display images.
1672 // Toggle the displaying of images.
1673 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1674 // Disable loading of images.
1675 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1677 // Reload the website to remove existing images.
1678 currentWebView.reload();
1679 } else { // Images are not currently loaded automatically.
1680 // Enable loading of images. Missing images will be loaded without the need for a reload.
1681 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1684 // Consume the event.
1686 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1687 // Check to see if dark WebView is supported by this WebView.
1688 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1689 // Toggle the dark WebView setting.
1690 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1691 // Turn off dark WebView.
1692 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1693 } else { // Dark WebView is currently disabled.
1694 // Turn on dark WebView.
1695 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1699 // Consume the event.
1701 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1702 // Get a handle for the views.
1703 Toolbar toolbar = findViewById(R.id.toolbar);
1704 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1705 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1707 // Set the minimum height of the find on page linear layout to match the toolbar.
1708 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1710 // Hide the toolbar.
1711 toolbar.setVisibility(View.GONE);
1713 // Show the find on page linear layout.
1714 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1716 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1717 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1718 findOnPageEditText.postDelayed(() -> {
1719 // Set the focus on the find on page edit text.
1720 findOnPageEditText.requestFocus();
1722 // Get a handle for the input method manager.
1723 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1725 // Remove the lint warning below that the input method manager might be null.
1726 assert inputMethodManager != null;
1728 // Display the keyboard. `0` sets no input flags.
1729 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1732 // Consume the event.
1734 } else if (menuItemId == R.id.print) { // Print.
1735 // Get a print manager instance.
1736 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1738 // Remove the lint error below that print manager might be null.
1739 assert printManager != null;
1741 // Create a print document adapter from the current WebView.
1742 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1744 // Print the document.
1745 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1747 // Consume the event.
1749 } else if (menuItemId == R.id.save_url) { // Save URL.
1750 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1751 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1752 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1754 // Consume the event.
1756 } else if (menuItemId == R.id.save_archive) { // Save archive.
1757 // Instantiate the save dialog.
1758 DialogFragment saveArchiveFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_ARCHIVE, null, null, getString(R.string.webpage_mht), null,
1761 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1762 saveArchiveFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1764 // Consume the event.
1766 } else if (menuItemId == R.id.save_image) { // Save image.
1767 // Instantiate the save dialog.
1768 DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_IMAGE, null, null, getString(R.string.webpage_png), null,
1771 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1772 saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1774 // Consume the event.
1776 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1777 // Instantiate the create home screen shortcut dialog.
1778 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1779 currentWebView.getFavoriteOrDefaultIcon());
1781 // Show the create home screen shortcut dialog.
1782 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1784 // Consume the event.
1786 } else if (menuItemId == R.id.view_source) { // View source.
1787 // Create an intent to launch the view source activity.
1788 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1790 // Add the variables to the intent.
1791 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1792 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1795 startActivity(viewSourceIntent);
1797 // Consume the event.
1799 } else if (menuItemId == R.id.share_url) { // Share URL.
1800 // Setup the share string.
1801 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1803 // Create the share intent.
1804 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1806 // Add the share string to the intent.
1807 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1809 // Set the MIME type.
1810 shareIntent.setType("text/plain");
1812 // Set the intent to open in a new task.
1813 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1816 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1818 // Consume the event.
1820 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1821 // Open the URL with an outside app.
1822 openWithApp(currentWebView.getUrl());
1824 // Consume the event.
1826 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1827 // Open the URL with an outside browser.
1828 openWithBrowser(currentWebView.getUrl());
1830 // Consume the event.
1832 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1833 // Check if domain settings currently exist.
1834 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1835 // Reapply the domain settings on returning to `MainWebViewActivity`.
1836 reapplyDomainSettingsOnRestart = true;
1838 // Create an intent to launch the domains activity.
1839 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1841 // Add the extra information to the intent.
1842 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1843 domainsIntent.putExtra("close_on_back", true);
1844 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1846 // Get the current certificate.
1847 SslCertificate sslCertificate = currentWebView.getCertificate();
1849 // Check to see if the SSL certificate is populated.
1850 if (sslCertificate != null) {
1851 // Extract the certificate to strings.
1852 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1853 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1854 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1855 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1856 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1857 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1858 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1859 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1861 // Add the certificate to the intent.
1862 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1863 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1864 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1865 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1866 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1867 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1868 domainsIntent.putExtra("ssl_start_date", startDateLong);
1869 domainsIntent.putExtra("ssl_end_date", endDateLong);
1872 // Check to see if the current IP addresses have been received.
1873 if (currentWebView.hasCurrentIpAddresses()) {
1874 // Add the current IP addresses to the intent.
1875 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1879 startActivity(domainsIntent);
1880 } else { // Add a new domain.
1881 // Apply the new domain settings on returning to `MainWebViewActivity`.
1882 reapplyDomainSettingsOnRestart = true;
1884 // Get the current domain
1885 Uri currentUri = Uri.parse(currentWebView.getUrl());
1886 String currentDomain = currentUri.getHost();
1888 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1889 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1891 // Create the domain and store the database ID.
1892 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1894 // Create an intent to launch the domains activity.
1895 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1897 // Add the extra information to the intent.
1898 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1899 domainsIntent.putExtra("close_on_back", true);
1900 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1902 // Get the current certificate.
1903 SslCertificate sslCertificate = currentWebView.getCertificate();
1905 // Check to see if the SSL certificate is populated.
1906 if (sslCertificate != null) {
1907 // Extract the certificate to strings.
1908 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1909 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1910 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1911 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1912 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1913 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1914 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1915 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1917 // Add the certificate to the intent.
1918 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1919 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1920 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1921 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1922 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1923 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1924 domainsIntent.putExtra("ssl_start_date", startDateLong);
1925 domainsIntent.putExtra("ssl_end_date", endDateLong);
1928 // Check to see if the current IP addresses have been received.
1929 if (currentWebView.hasCurrentIpAddresses()) {
1930 // Add the current IP addresses to the intent.
1931 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1935 startActivity(domainsIntent);
1938 // Consume the event.
1940 } else if (menuItemId == R.id.ad_consent) { // Ad consent.
1941 // Instantiate the ad consent dialog.
1942 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1944 // Display the ad consent dialog.
1945 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1947 // Consume the event.
1949 } else { // There is no match with the options menu. Pass the event up to the parent method.
1950 // Don't consume the event.
1951 return super.onOptionsItemSelected(menuItem);
1955 // removeAllCookies is deprecated, but it is required for API < 21.
1957 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1958 // Get a handle for the shared preferences.
1959 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1961 // Get the menu item ID.
1962 int menuItemId = menuItem.getItemId();
1964 // Run the commands that correspond to the selected menu item.
1965 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
1966 // Clear and exit Privacy Browser.
1968 } else if (menuItemId == R.id.home) { // Home.
1969 // Load the homepage.
1970 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1971 } else if (menuItemId == R.id.back) { // Back.
1972 // Check if the WebView can go back.
1973 if (currentWebView.canGoBack()) {
1974 // Get the current web back forward list.
1975 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1977 // Get the previous entry URL.
1978 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1980 // Apply the domain settings.
1981 applyDomainSettings(currentWebView, previousUrl, false, false, false);
1983 // Load the previous website in the history.
1984 currentWebView.goBack();
1986 } else if (menuItemId == R.id.forward) { // Forward.
1987 // Check if the WebView can go forward.
1988 if (currentWebView.canGoForward()) {
1989 // Get the current web back forward list.
1990 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1992 // Get the next entry URL.
1993 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1995 // Apply the domain settings.
1996 applyDomainSettings(currentWebView, nextUrl, false, false, false);
1998 // Load the next website in the history.
1999 currentWebView.goForward();
2001 } else if (menuItemId == R.id.history) { // History.
2002 // Instantiate the URL history dialog.
2003 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2005 // Show the URL history dialog.
2006 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2007 } else if (menuItemId == R.id.open) { // Open.
2008 // Instantiate the open file dialog.
2009 DialogFragment openDialogFragment = new OpenDialog();
2011 // Show the open file dialog.
2012 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2013 } else if (menuItemId == R.id.requests) { // Requests.
2014 // Populate the resource requests.
2015 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2017 // Create an intent to launch the Requests activity.
2018 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2020 // Add the block third-party requests status to the intent.
2021 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2024 startActivity(requestsIntent);
2025 } else if (menuItemId == R.id.downloads) { // Downloads.
2026 // Launch the system Download Manager.
2027 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2029 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2030 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2033 startActivity(downloadManagerIntent);
2034 } else if (menuItemId == R.id.domains) { // Domains.
2035 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2036 reapplyDomainSettingsOnRestart = true;
2038 // Launch the domains activity.
2039 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2041 // Add the extra information to the intent.
2042 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2044 // Get the current certificate.
2045 SslCertificate sslCertificate = currentWebView.getCertificate();
2047 // Check to see if the SSL certificate is populated.
2048 if (sslCertificate != null) {
2049 // Extract the certificate to strings.
2050 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2051 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2052 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2053 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2054 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2055 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2056 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2057 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2059 // Add the certificate to the intent.
2060 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2061 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2062 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2063 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2064 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2065 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2066 domainsIntent.putExtra("ssl_start_date", startDateLong);
2067 domainsIntent.putExtra("ssl_end_date", endDateLong);
2070 // Check to see if the current IP addresses have been received.
2071 if (currentWebView.hasCurrentIpAddresses()) {
2072 // Add the current IP addresses to the intent.
2073 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2077 startActivity(domainsIntent);
2078 } else if (menuItemId == R.id.settings) { // Settings.
2079 // Set the flag to reapply app settings on restart when returning from Settings.
2080 reapplyAppSettingsOnRestart = true;
2082 // Set the flag to reapply the domain settings on restart when returning from Settings.
2083 reapplyDomainSettingsOnRestart = true;
2085 // Launch the settings activity.
2086 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2087 startActivity(settingsIntent);
2088 } else if (menuItemId == R.id.import_export) { // Import/Export.
2089 // Create an intent to launch the import/export activity.
2090 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2093 startActivity(importExportIntent);
2094 } else if (menuItemId == R.id.logcat) { // Logcat.
2095 // Create an intent to launch the logcat activity.
2096 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2099 startActivity(logcatIntent);
2100 } else if (menuItemId == R.id.guide) { // Guide.
2101 // Create an intent to launch the guide activity.
2102 Intent guideIntent = new Intent(this, GuideActivity.class);
2105 startActivity(guideIntent);
2106 } else if (menuItemId == R.id.about) { // About
2107 // Create an intent to launch the about activity.
2108 Intent aboutIntent = new Intent(this, AboutActivity.class);
2110 // Create a string array for the blocklist versions.
2111 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],
2112 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2114 // Add the blocklist versions to the intent.
2115 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2118 startActivity(aboutIntent);
2121 // Close the navigation drawer.
2122 drawerLayout.closeDrawer(GravityCompat.START);
2127 public void onPostCreate(Bundle savedInstanceState) {
2128 // Run the default commands.
2129 super.onPostCreate(savedInstanceState);
2131 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2132 actionBarDrawerToggle.syncState();
2136 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2137 // Run the default commands.
2138 super.onConfigurationChanged(newConfig);
2140 // Reload the ad for the free flavor if not in full screen mode.
2141 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2142 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2143 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2146 // `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:
2147 // https://code.google.com/p/android/issues/detail?id=20493#c8
2148 // ActivityCompat.invalidateOptionsMenu(this);
2152 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2153 // Get the hit test result.
2154 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2156 // Define the URL strings.
2157 final String imageUrl;
2158 final String linkUrl;
2160 // Get handles for the system managers.
2161 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2163 // Remove the lint errors below that the clipboard manager might be null.
2164 assert clipboardManager != null;
2166 // Process the link according to the type.
2167 switch (hitTestResult.getType()) {
2168 // `SRC_ANCHOR_TYPE` is a link.
2169 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2170 // Get the target URL.
2171 linkUrl = hitTestResult.getExtra();
2173 // Set the target URL as the title of the `ContextMenu`.
2174 menu.setHeaderTitle(linkUrl);
2176 // Add an Open in New Tab entry.
2177 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2178 // Load the link URL in a new tab and move to it.
2179 addNewTab(linkUrl, true);
2181 // Consume the event.
2185 // Add an Open in Background entry.
2186 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2187 // Load the link URL in a new tab but do not move to it.
2188 addNewTab(linkUrl, false);
2190 // Consume the event.
2194 // Add an Open with App entry.
2195 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2196 openWithApp(linkUrl);
2198 // Consume the event.
2202 // Add an Open with Browser entry.
2203 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2204 openWithBrowser(linkUrl);
2206 // Consume the event.
2210 // Add a Copy URL entry.
2211 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2212 // Save the link URL in a `ClipData`.
2213 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2215 // Set the `ClipData` as the clipboard's primary clip.
2216 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2218 // Consume the event.
2222 // Add a Save URL entry.
2223 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2224 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2225 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2226 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2228 // Consume the event.
2232 // Add an empty Cancel entry, which by default closes the context menu.
2233 menu.add(R.string.cancel);
2236 // `IMAGE_TYPE` is an image.
2237 case WebView.HitTestResult.IMAGE_TYPE:
2238 // Get the image URL.
2239 imageUrl = hitTestResult.getExtra();
2241 // Remove the incorrect lint warning below that the image URL might be null.
2242 assert imageUrl != null;
2244 // Set the context menu title.
2245 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2246 // Truncate the image URL before making it the title.
2247 menu.setHeaderTitle(imageUrl.substring(0, 100));
2248 } else { // The image URL does not contain the full image data.
2249 // Set the image URL as the title of the context menu.
2250 menu.setHeaderTitle(imageUrl);
2253 // Add an Open in New Tab entry.
2254 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2255 // Load the image in a new tab.
2256 addNewTab(imageUrl, true);
2258 // Consume the event.
2262 // Add an Open with App entry.
2263 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2264 // Open the image URL with an external app.
2265 openWithApp(imageUrl);
2267 // Consume the event.
2271 // Add an Open with Browser entry.
2272 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2273 // Open the image URL with an external browser.
2274 openWithBrowser(imageUrl);
2276 // Consume the event.
2280 // Add a View Image entry.
2281 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2282 // Load the image in the current tab.
2283 loadUrl(currentWebView, imageUrl);
2285 // Consume the event.
2289 // Add a Save Image entry.
2290 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2291 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2292 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2293 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2295 // Consume the event.
2299 // Add a Copy URL entry.
2300 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2301 // Save the image URL in a clip data.
2302 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2304 // Set the clip data as the clipboard's primary clip.
2305 clipboardManager.setPrimaryClip(imageTypeClipData);
2307 // Consume the event.
2311 // Add an empty Cancel entry, which by default closes the context menu.
2312 menu.add(R.string.cancel);
2315 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2316 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2317 // Get the image URL.
2318 imageUrl = hitTestResult.getExtra();
2320 // Instantiate a handler.
2321 Handler handler = new Handler();
2323 // Get a message from the handler.
2324 Message message = handler.obtainMessage();
2326 // Request the image details from the last touched node be returned in the message.
2327 currentWebView.requestFocusNodeHref(message);
2329 // Get the link URL from the message data.
2330 linkUrl = message.getData().getString("url");
2332 // Set the link URL as the title of the context menu.
2333 menu.setHeaderTitle(linkUrl);
2335 // Add an Open in New Tab entry.
2336 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2337 // Load the link URL in a new tab and move to it.
2338 addNewTab(linkUrl, true);
2340 // Consume the event.
2344 // Add an Open in Background entry.
2345 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2346 // Lod the link URL in a new tab but do not move to it.
2347 addNewTab(linkUrl, false);
2349 // Consume the event.
2353 // Add an Open Image in New Tab entry.
2354 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2355 // Load the image in a new tab and move to it.
2356 addNewTab(imageUrl, true);
2358 // Consume the event.
2362 // Add an Open with App entry.
2363 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2364 // Open the link URL with an external app.
2365 openWithApp(linkUrl);
2367 // Consume the event.
2371 // Add an Open with Browser entry.
2372 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2373 // Open the link URL with an external browser.
2374 openWithBrowser(linkUrl);
2376 // Consume the event.
2380 // Add a View Image entry.
2381 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2382 // View the image in the current tab.
2383 loadUrl(currentWebView, imageUrl);
2385 // Consume the event.
2389 // Add a Save Image entry.
2390 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2391 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2392 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2393 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2395 // Consume the event.
2399 // Add a Copy URL entry.
2400 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2401 // Save the link URL in a clip data.
2402 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2404 // Set the clip data as the clipboard's primary clip.
2405 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2407 // Consume the event.
2411 // Add a Save URL entry.
2412 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2413 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2414 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2415 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2417 // Consume the event.
2421 // Add an empty Cancel entry, which by default closes the context menu.
2422 menu.add(R.string.cancel);
2425 case WebView.HitTestResult.EMAIL_TYPE:
2426 // Get the target URL.
2427 linkUrl = hitTestResult.getExtra();
2429 // Set the target URL as the title of the `ContextMenu`.
2430 menu.setHeaderTitle(linkUrl);
2432 // Add a Write Email entry.
2433 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2434 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2435 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2437 // Parse the url and set it as the data for the `Intent`.
2438 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2440 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2441 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2445 startActivity(emailIntent);
2446 } catch (ActivityNotFoundException exception) {
2447 // Display a snackbar.
2448 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2451 // Consume the event.
2455 // Add a Copy Email Address entry.
2456 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2457 // Save the email address in a `ClipData`.
2458 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2460 // Set the `ClipData` as the clipboard's primary clip.
2461 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2463 // Consume the event.
2467 // Add an empty Cancel entry, which by default closes the context menu.
2468 menu.add(R.string.cancel);
2474 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2475 // Get a handle for the bookmarks list view.
2476 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2479 Dialog dialog = dialogFragment.getDialog();
2481 // Remove the incorrect lint warning below that the dialog might be null.
2482 assert dialog != null;
2484 // Get the views from the dialog fragment.
2485 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2486 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2488 // Extract the strings from the edit texts.
2489 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2490 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2492 // Create a favorite icon byte array output stream.
2493 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2495 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2496 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2498 // Convert the favorite icon byte array stream to a byte array.
2499 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2501 // Display the new bookmark below the current items in the (0 indexed) list.
2502 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2504 // Create the bookmark.
2505 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2507 // Update the bookmarks cursor with the current contents of this folder.
2508 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2510 // Update the list view.
2511 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2513 // Scroll to the new bookmark.
2514 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2518 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2519 // Get a handle for the bookmarks list view.
2520 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2523 Dialog dialog = dialogFragment.getDialog();
2525 // Remove the incorrect lint warning below that the dialog might be null.
2526 assert dialog != null;
2528 // Get handles for the views in the dialog fragment.
2529 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2530 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2531 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2533 // Get new folder name string.
2534 String folderNameString = createFolderNameEditText.getText().toString();
2536 // Create a folder icon bitmap.
2537 Bitmap folderIconBitmap;
2539 // Set the folder icon bitmap according to the dialog.
2540 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2541 // Get the default folder icon drawable.
2542 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2544 // Convert the folder icon drawable to a bitmap drawable.
2545 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2547 // Convert the folder icon bitmap drawable to a bitmap.
2548 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2549 } else { // Use the WebView favorite icon.
2550 // Copy the favorite icon bitmap to the folder icon bitmap.
2551 folderIconBitmap = favoriteIconBitmap;
2554 // Create a folder icon byte array output stream.
2555 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2557 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2558 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2560 // Convert the folder icon byte array stream to a byte array.
2561 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2563 // Move all the bookmarks down one in the display order.
2564 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2565 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2566 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2569 // Create the folder, which will be placed at the top of the `ListView`.
2570 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2572 // Update the bookmarks cursor with the current contents of this folder.
2573 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2575 // Update the `ListView`.
2576 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2578 // Scroll to the new folder.
2579 bookmarksListView.setSelection(0);
2583 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2584 // Remove the incorrect lint warning below that the dialog fragment might be null.
2585 assert dialogFragment != null;
2588 Dialog dialog = dialogFragment.getDialog();
2590 // Remove the incorrect lint warning below that the dialog might be null.
2591 assert dialog != null;
2593 // Get handles for the views from the dialog.
2594 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2595 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2596 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2597 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2599 // Get the new folder name.
2600 String newFolderNameString = editFolderNameEditText.getText().toString();
2602 // Check if the favorite icon has changed.
2603 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2604 // Update the name in the database.
2605 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2606 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2607 // Create the new folder icon Bitmap.
2608 Bitmap folderIconBitmap;
2610 // Populate the new folder icon bitmap.
2611 if (defaultFolderIconRadioButton.isChecked()) {
2612 // Get the default folder icon drawable.
2613 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2615 // Convert the folder icon drawable to a bitmap drawable.
2616 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2618 // Convert the folder icon bitmap drawable to a bitmap.
2619 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2620 } else { // Use the `WebView` favorite icon.
2621 // Copy the favorite icon bitmap to the folder icon bitmap.
2622 folderIconBitmap = favoriteIconBitmap;
2625 // Create a folder icon byte array output stream.
2626 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2628 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2629 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2631 // Convert the folder icon byte array stream to a byte array.
2632 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2634 // Update the folder icon in the database.
2635 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2636 } else { // The folder icon and the name have changed.
2637 // Get the new folder icon `Bitmap`.
2638 Bitmap folderIconBitmap;
2639 if (defaultFolderIconRadioButton.isChecked()) {
2640 // Get the default folder icon drawable.
2641 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2643 // Convert the folder icon drawable to a bitmap drawable.
2644 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2646 // Convert the folder icon bitmap drawable to a bitmap.
2647 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2648 } else { // Use the `WebView` favorite icon.
2649 // Copy the favorite icon bitmap to the folder icon bitmap.
2650 folderIconBitmap = favoriteIconBitmap;
2653 // Create a folder icon byte array output stream.
2654 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2656 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2657 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2659 // Convert the folder icon byte array stream to a byte array.
2660 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2662 // Update the folder name and icon in the database.
2663 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2666 // Update the bookmarks cursor with the current contents of this folder.
2667 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2669 // Update the `ListView`.
2670 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2673 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2675 public void onBackPressed() {
2676 // Check the different options for processing `back`.
2677 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2678 // Close the navigation drawer.
2679 drawerLayout.closeDrawer(GravityCompat.START);
2680 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2681 // close the bookmarks drawer.
2682 drawerLayout.closeDrawer(GravityCompat.END);
2683 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2684 // Get a handle for the layouts.
2685 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2686 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2687 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2689 // Re-enable the screen timeout.
2690 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2692 // Unset the full screen video flag.
2693 displayingFullScreenVideo = false;
2695 // Remove all the views from the full screen video frame layout.
2696 fullScreenVideoFrameLayout.removeAllViews();
2698 // Hide the full screen video frame layout.
2699 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2701 // Enable the sliding drawers.
2702 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2704 // Show the main content relative layout.
2705 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2707 // Apply the appropriate full screen mode flags.
2708 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2709 // Hide the banner ad in the free flavor.
2710 if (BuildConfig.FLAVOR.contentEquals("free")) {
2711 AdHelper.hideAd(findViewById(R.id.adview));
2714 /* Hide the system bars.
2715 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2716 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2717 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2718 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2720 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2721 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2723 // Reload the website if the app bar is hidden. Otherwise, there is some bug in Android that causes the WebView to be entirely black.
2725 // Reload the WebView.
2726 currentWebView.reload();
2728 } else { // Switch to normal viewing mode.
2729 // Remove the `SYSTEM_UI` flags from the root frame layout.
2730 rootFrameLayout.setSystemUiVisibility(0);
2733 // Reload the ad for the free flavor if not in full screen mode.
2734 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2736 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2738 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2739 // Get the current web back forward list.
2740 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2742 // Get the previous entry URL.
2743 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2745 // Apply the domain settings.
2746 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2749 currentWebView.goBack();
2750 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2751 // Close the current tab.
2753 } else { // There isn't anything to do in Privacy Browser.
2754 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2755 if (Build.VERSION.SDK_INT >= 21) {
2756 finishAndRemoveTask();
2761 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2766 // Process the results of a file browse.
2768 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2769 // Run the default commands.
2770 super.onActivityResult(requestCode, resultCode, returnedIntent);
2772 // Run the commands that correlate to the specified request code.
2773 switch (requestCode) {
2774 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2775 // File uploads only work on API >= 21.
2776 if (Build.VERSION.SDK_INT >= 21) {
2777 // Pass the file to the WebView.
2778 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2782 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2783 // Don't do anything if the user pressed back from the file picker.
2784 if (resultCode == Activity.RESULT_OK) {
2785 // Get a handle for the save dialog fragment.
2786 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2788 // Only update the file name if the dialog still exists.
2789 if (saveWebpageDialogFragment != null) {
2790 // Get a handle for the save webpage dialog.
2791 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2793 // Remove the incorrect lint warning below that the dialog might be null.
2794 assert saveWebpageDialog != null;
2796 // Get a handle for the file name edit text.
2797 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2798 TextView fileExistsWarningTextView = saveWebpageDialog.findViewById(R.id.file_exists_warning_textview);
2800 // Instantiate the file name helper.
2801 FileNameHelper fileNameHelper = new FileNameHelper();
2803 // Get the file path if it isn't null.
2804 if (returnedIntent.getData() != null) {
2805 // Convert the file name URI to a file name path.
2806 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2808 // Set the file name path as the text of the file name edit text.
2809 fileNameEditText.setText(fileNamePath);
2811 // Move the cursor to the end of the file name edit text.
2812 fileNameEditText.setSelection(fileNamePath.length());
2814 // Hide the file exists warning.
2815 fileExistsWarningTextView.setVisibility(View.GONE);
2821 case BROWSE_OPEN_REQUEST_CODE:
2822 // Don't do anything if the user pressed back from the file picker.
2823 if (resultCode == Activity.RESULT_OK) {
2824 // Get a handle for the open dialog fragment.
2825 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2827 // Only update the file name if the dialog still exists.
2828 if (openDialogFragment != null) {
2829 // Get a handle for the open dialog.
2830 Dialog openDialog = openDialogFragment.getDialog();
2832 // Remove the incorrect lint warning below that the dialog might be null.
2833 assert openDialog != null;
2835 // Get a handle for the file name edit text.
2836 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2838 // Instantiate the file name helper.
2839 FileNameHelper fileNameHelper = new FileNameHelper();
2841 // Get the file path if it isn't null.
2842 if (returnedIntent.getData() != null) {
2843 // Convert the file name URI to a file name path.
2844 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2846 // Set the file name path as the text of the file name edit text.
2847 fileNameEditText.setText(fileNamePath);
2849 // Move the cursor to the end of the file name edit text.
2850 fileNameEditText.setSelection(fileNamePath.length());
2858 private void loadUrlFromTextBox() {
2859 // Get a handle for the URL edit text.
2860 EditText urlEditText = findViewById(R.id.url_edittext);
2862 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2863 String unformattedUrlString = urlEditText.getText().toString().trim();
2865 // Initialize the formatted URL string.
2868 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2869 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2870 // Load the entire content URL.
2871 url = unformattedUrlString;
2872 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2873 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2874 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2875 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2876 unformattedUrlString = "https://" + unformattedUrlString;
2879 // Initialize `unformattedUrl`.
2880 URL unformattedUrl = null;
2882 // 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.
2884 unformattedUrl = new URL(unformattedUrlString);
2885 } catch (MalformedURLException e) {
2886 e.printStackTrace();
2889 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2890 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2891 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2892 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2893 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2894 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2897 Uri.Builder uri = new Uri.Builder();
2898 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2900 // Decode the URI as a UTF-8 string in.
2902 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2903 } catch (UnsupportedEncodingException exception) {
2904 // Do nothing. The formatted URL string will remain blank.
2906 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2907 // Create an encoded URL String.
2908 String encodedUrlString;
2910 // Sanitize the search input.
2912 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2913 } catch (UnsupportedEncodingException exception) {
2914 encodedUrlString = "";
2917 // Add the base search URL.
2918 url = searchURL + encodedUrlString;
2921 // 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.
2922 urlEditText.clearFocus();
2925 loadUrl(currentWebView, url);
2928 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2929 // Sanitize the URL.
2930 url = sanitizeUrl(url);
2932 // Apply the domain settings and load the URL.
2933 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2936 public void findPreviousOnPage(View view) {
2937 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2938 currentWebView.findNext(false);
2941 public void findNextOnPage(View view) {
2942 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2943 currentWebView.findNext(true);
2946 public void closeFindOnPage(View view) {
2947 // Get a handle for the views.
2948 Toolbar toolbar = findViewById(R.id.toolbar);
2949 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2950 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2952 // Delete the contents of `find_on_page_edittext`.
2953 findOnPageEditText.setText(null);
2955 // Clear the highlighted phrases if the WebView is not null.
2956 if (currentWebView != null) {
2957 currentWebView.clearMatches();
2960 // Hide the find on page linear layout.
2961 findOnPageLinearLayout.setVisibility(View.GONE);
2963 // Show the toolbar.
2964 toolbar.setVisibility(View.VISIBLE);
2966 // Get a handle for the input method manager.
2967 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2969 // Remove the lint warning below that the input method manager might be null.
2970 assert inputMethodManager != null;
2972 // Hide the keyboard.
2973 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2977 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2978 // Remove the incorrect lint warning below that the dialog fragment might be null.
2979 assert dialogFragment != null;
2982 Dialog dialog = dialogFragment.getDialog();
2984 // Remove the incorrect lint warning below tha the dialog might be null.
2985 assert dialog != null;
2987 // Get a handle for the font size edit text.
2988 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2990 // Initialize the new font size variable with the current font size.
2991 int newFontSize = currentWebView.getSettings().getTextZoom();
2993 // Get the font size from the edit text.
2995 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2996 } catch (Exception exception) {
2997 // If the edit text does not contain a valid font size do nothing.
3000 // Apply the new font size.
3001 currentWebView.getSettings().setTextZoom(newFontSize);
3005 public void onOpen(DialogFragment dialogFragment) {
3007 Dialog dialog = dialogFragment.getDialog();
3009 // Remove the incorrect lint warning below that the dialog might be null.
3010 assert dialog != null;
3012 // Get a handle for the file name edit text.
3013 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3015 // Get the file path string.
3016 openFilePath = fileNameEditText.getText().toString();
3018 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3019 applyDomainSettings(currentWebView, "file://" + openFilePath, true, false, false);
3021 // Check to see if the storage permission is needed.
3022 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
3024 currentWebView.loadUrl("file://" + openFilePath);
3025 } else { // The storage permission has not been granted.
3026 // Get the external private directory file.
3027 File externalPrivateDirectoryFile = getExternalFilesDir(null);
3029 // Remove the incorrect lint error below that the file might be null.
3030 assert externalPrivateDirectoryFile != null;
3032 // Get the external private directory string.
3033 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
3035 // Check to see if the file path is in the external private directory.
3036 if (openFilePath.startsWith(externalPrivateDirectory)) { // the file path is in the external private directory.
3038 currentWebView.loadUrl("file://" + openFilePath);
3039 } else { // The file path is in a public directory.
3040 // Check if the user has previously denied the storage permission.
3041 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3042 // Instantiate the storage permission alert dialog.
3043 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.OPEN);
3045 // Show the storage permission alert dialog. The permission will be requested the the dialog is closed.
3046 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
3047 } else { // Show the permission request directly.
3048 // Request the write external storage permission. The file will be opened when it finishes.
3049 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.OPEN);
3056 public void onSaveWebpage(int saveType, String originalUrlString, DialogFragment dialogFragment) {
3058 Dialog dialog = dialogFragment.getDialog();
3060 // Remove the incorrect lint warning below that the dialog might be null.
3061 assert dialog != null;
3063 // Get a handle for the edit texts.
3064 EditText urlEditText = dialog.findViewById(R.id.url_edittext);
3065 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3068 if ((originalUrlString != null) && originalUrlString.startsWith("data:")) {
3069 // Save the original URL.
3070 saveWebpageUrl = originalUrlString;
3072 // Get the URL from the edit text, which may have been modified.
3073 saveWebpageUrl = urlEditText.getText().toString();
3076 // Get the file path from the edit text.
3077 saveWebpageFilePath = fileNameEditText.getText().toString();
3079 // Check to see if the storage permission is needed.
3080 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
3081 //Save the webpage according to the save type.
3083 case StoragePermissionDialog.SAVE_URL:
3085 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3088 case StoragePermissionDialog.SAVE_ARCHIVE:
3089 // Save the webpage archive.
3090 saveWebpageArchive(saveWebpageFilePath);
3093 case StoragePermissionDialog.SAVE_IMAGE:
3094 // Save the webpage image.
3095 new SaveWebpageImage(this, this, saveWebpageFilePath, currentWebView).execute();
3099 // Reset the strings.
3100 saveWebpageUrl = "";
3101 saveWebpageFilePath = "";
3102 } else { // The storage permission has not been granted.
3103 // Get the external private directory file.
3104 File externalPrivateDirectoryFile = getExternalFilesDir(null);
3106 // Remove the incorrect lint error below that the file might be null.
3107 assert externalPrivateDirectoryFile != null;
3109 // Get the external private directory string.
3110 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
3112 // Check to see if the file path is in the external private directory.
3113 if (saveWebpageFilePath.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
3114 // Save the webpage according to the save type.
3116 case StoragePermissionDialog.SAVE_URL:
3118 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3121 case StoragePermissionDialog.SAVE_ARCHIVE:
3122 // Save the webpage archive.
3123 saveWebpageArchive(saveWebpageFilePath);
3126 case StoragePermissionDialog.SAVE_IMAGE:
3127 // Save the webpage image.
3128 new SaveWebpageImage(this, this, saveWebpageFilePath, currentWebView).execute();
3132 // Reset the strings.
3133 saveWebpageUrl = "";
3134 saveWebpageFilePath = "";
3135 } else { // The file path is in a public directory.
3136 // Check if the user has previously denied the storage permission.
3137 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3138 // Instantiate the storage permission alert dialog.
3139 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(saveType);
3141 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
3142 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
3143 } else { // Show the permission request directly.
3144 // Request the write external storage permission according to the save type. The URL will be saved when it finishes.
3145 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, saveType);
3152 public void onCloseStoragePermissionDialog(int requestType) {
3153 // Request the write external storage permission according to the request type. The file will be opened when it finishes.
3154 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestType);
3159 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3160 //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).
3161 if (grantResults.length > 0) {
3162 switch (requestCode) {
3163 case StoragePermissionDialog.OPEN:
3164 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3165 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3167 currentWebView.loadUrl("file://" + openFilePath);
3168 } else { // The storage permission was not granted.
3169 // Display an error snackbar.
3170 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3174 case StoragePermissionDialog.SAVE_URL:
3175 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3176 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3177 // Save the raw URL.
3178 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3179 } else { // The storage permission was not granted.
3180 // Display an error snackbar.
3181 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3185 case StoragePermissionDialog.SAVE_ARCHIVE:
3186 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3187 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3188 // Save the webpage archive.
3189 saveWebpageArchive(saveWebpageFilePath);
3190 } else { // The storage permission was not granted.
3191 // Display an error snackbar.
3192 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3196 case StoragePermissionDialog.SAVE_IMAGE:
3197 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3198 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3199 // Save the webpage image.
3200 new SaveWebpageImage(this, this, saveWebpageFilePath, currentWebView).execute();
3201 } else { // The storage permission was not granted.
3202 // Display an error snackbar.
3203 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3208 // Reset the strings.
3210 saveWebpageUrl = "";
3211 saveWebpageFilePath = "";
3215 private void initializeApp() {
3216 // Get a handle for the input method.
3217 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3219 // Remove the lint warning below that the input method manager might be null.
3220 assert inputMethodManager != null;
3222 // Initialize the gray foreground color spans for highlighting the URLs. The deprecated `getResources()` must be used until API >= 23.
3223 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3224 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3226 // Get the current theme status.
3227 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3229 // Set the red color span according to the theme.
3230 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3231 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3233 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
3236 // Get handles for the URL views.
3237 EditText urlEditText = findViewById(R.id.url_edittext);
3239 // Remove the formatting from the URL edit text when the user is editing the text.
3240 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3241 if (hasFocus) { // The user is editing the URL text box.
3242 // Remove the highlighting.
3243 urlEditText.getText().removeSpan(redColorSpan);
3244 urlEditText.getText().removeSpan(initialGrayColorSpan);
3245 urlEditText.getText().removeSpan(finalGrayColorSpan);
3246 } else { // The user has stopped editing the URL text box.
3247 // Move to the beginning of the string.
3248 urlEditText.setSelection(0);
3250 // Reapply the highlighting.
3255 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3256 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3257 // If the event is a key-down event on the `enter` button, load the URL.
3258 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3259 // Load the URL into the mainWebView and consume the event.
3260 loadUrlFromTextBox();
3262 // If the enter key was pressed, consume the event.
3265 // If any other key was pressed, do not consume the event.
3270 // Create an Orbot status broadcast receiver.
3271 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3273 public void onReceive(Context context, Intent intent) {
3274 // Store the content of the status message in `orbotStatus`.
3275 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3277 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3278 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3279 // Reset the waiting for proxy status.
3280 waitingForProxy = false;
3282 // Get a handle for the waiting for proxy dialog.
3283 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3285 // Dismiss the waiting for proxy dialog if it is displayed.
3286 if (waitingForProxyDialogFragment != null) {
3287 waitingForProxyDialogFragment.dismiss();
3290 // Reload existing URLs and load any URLs that are waiting for the proxy.
3291 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3292 // Get the WebView tab fragment.
3293 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3295 // Get the fragment view.
3296 View fragmentView = webViewTabFragment.getView();
3298 // Only process the WebViews if they exist.
3299 if (fragmentView != null) {
3300 // Get the nested scroll WebView from the tab fragment.
3301 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3303 // Get the waiting for proxy URL string.
3304 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3306 // Load the pending URL if it exists.
3307 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3309 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3311 // Reset the waiting for proxy URL string.
3312 nestedScrollWebView.resetWaitingForProxyUrlString();
3313 } else { // No URL is waiting to be loaded.
3314 // Reload the existing URL.
3315 nestedScrollWebView.reload();
3323 // Register the Orbot status broadcast receiver on `this` context.
3324 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3326 // Get handles for views that need to be modified.
3327 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3328 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3329 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3330 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3331 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3333 // Update the web view pager every time a tab is modified.
3334 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3336 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3341 public void onPageSelected(int position) {
3342 // Close the find on page bar if it is open.
3343 closeFindOnPage(null);
3345 // Set the current WebView.
3346 setCurrentWebView(position);
3348 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled by creating a new tab.
3349 if (tabLayout.getSelectedTabPosition() != position) {
3350 // Wait until the new tab has been created.
3351 tabLayout.post(() -> {
3352 // Get a handle for the tab.
3353 TabLayout.Tab tab = tabLayout.getTabAt(position);
3355 // Assert that the tab is not null.
3365 public void onPageScrollStateChanged(int state) {
3370 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3371 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3373 public void onTabSelected(TabLayout.Tab tab) {
3374 // Select the same page in the view pager.
3375 webViewPager.setCurrentItem(tab.getPosition());
3379 public void onTabUnselected(TabLayout.Tab tab) {
3384 public void onTabReselected(TabLayout.Tab tab) {
3385 // Instantiate the View SSL Certificate dialog.
3386 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3388 // Display the View SSL Certificate dialog.
3389 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3393 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3394 launchBookmarksActivityFab.setOnClickListener(v -> {
3395 // Get a copy of the favorite icon bitmap.
3396 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3398 // Create a favorite icon byte array output stream.
3399 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3401 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3402 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3404 // Convert the favorite icon byte array stream to a byte array.
3405 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3407 // Create an intent to launch the bookmarks activity.
3408 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3410 // Add the extra information to the intent.
3411 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3412 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3413 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3414 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3417 startActivity(bookmarksIntent);
3420 // Set the create new bookmark folder FAB to display an alert dialog.
3421 createBookmarkFolderFab.setOnClickListener(v -> {
3422 // Create a create bookmark folder dialog.
3423 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3425 // Show the create bookmark folder dialog.
3426 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3429 // Set the create new bookmark FAB to display an alert dialog.
3430 createBookmarkFab.setOnClickListener(view -> {
3431 // Instantiate the create bookmark dialog.
3432 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3434 // Display the create bookmark dialog.
3435 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3438 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3439 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3441 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3446 public void onTextChanged(CharSequence s, int start, int before, int count) {
3451 public void afterTextChanged(Editable s) {
3452 // 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.
3453 if (currentWebView != null) {
3454 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3459 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3460 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3461 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3462 // Hide the soft keyboard.
3463 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3465 // Consume the event.
3467 } else { // A different key was pressed.
3468 // Do not consume the event.
3473 // Implement swipe to refresh.
3474 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3476 // Store the default progress view offsets for use later in `initializeWebView()`.
3477 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3478 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3480 // Set the refresh color scheme according to the theme.
3481 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3482 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
3484 swipeRefreshLayout.setColorSchemeResources(R.color.violet_500);
3487 // Initialize a color background typed value.
3488 TypedValue colorBackgroundTypedValue = new TypedValue();
3490 // Get the color background from the theme.
3491 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3493 // Get the color background int from the typed value.
3494 int colorBackgroundInt = colorBackgroundTypedValue.data;
3496 // Set the swipe refresh background color.
3497 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3499 // The drawer titles identify the drawer layouts in accessibility mode.
3500 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3501 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3503 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3504 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3506 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3507 currentBookmarksFolder = "";
3509 // Load the home folder, which is `""` in the database.
3510 loadBookmarksFolder();
3512 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3513 // Convert the id from long to int to match the format of the bookmarks database.
3514 int databaseId = (int) id;
3516 // Get the bookmark cursor for this ID.
3517 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3519 // Move the bookmark cursor to the first row.
3520 bookmarkCursor.moveToFirst();
3522 // Act upon the bookmark according to the type.
3523 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3524 // Store the new folder name in `currentBookmarksFolder`.
3525 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3527 // Load the new folder.
3528 loadBookmarksFolder();
3529 } else { // The selected bookmark is not a folder.
3530 // Load the bookmark URL.
3531 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3533 // Close the bookmarks drawer.
3534 drawerLayout.closeDrawer(GravityCompat.END);
3537 // Close the `Cursor`.
3538 bookmarkCursor.close();
3541 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3542 // Convert the database ID from `long` to `int`.
3543 int databaseId = (int) id;
3545 // Find out if the selected bookmark is a folder.
3546 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3549 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3550 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3552 // Instantiate the edit folder bookmark dialog.
3553 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3555 // Show the edit folder bookmark dialog.
3556 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3558 // Get the bookmark cursor for this ID.
3559 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3561 // Move the bookmark cursor to the first row.
3562 bookmarkCursor.moveToFirst();
3564 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3565 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3568 // Consume the event.
3572 // The drawer listener is used to update the navigation menu.
3573 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3575 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3579 public void onDrawerOpened(@NonNull View drawerView) {
3583 public void onDrawerClosed(@NonNull View drawerView) {
3587 public void onDrawerStateChanged(int newState) {
3588 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3589 // Update the navigation menu items if the WebView is not null.
3590 if (currentWebView != null) {
3591 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3592 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3593 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3594 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3596 // Hide the keyboard (if displayed).
3597 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3600 // 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.
3601 urlEditText.clearFocus();
3602 currentWebView.clearFocus();
3607 // 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).
3608 customHeaders.put("X-Requested-With", "");
3610 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3611 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3613 // Get a handle for the WebView.
3614 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3616 // Store the default user agent.
3617 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3619 // Destroy the bare WebView.
3620 bareWebView.destroy();
3623 private void applyAppSettings() {
3624 // Get a handle for the shared preferences.
3625 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3627 // Store the values from the shared preferences in variables.
3628 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3629 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3630 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3631 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3632 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3633 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3634 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3635 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3636 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3638 // Apply the saved proxy mode if the app has been restarted.
3639 if (savedProxyMode != null) {
3640 // Apply the saved proxy mode.
3641 proxyMode = savedProxyMode;
3643 // Reset the saved proxy mode.
3644 savedProxyMode = null;
3647 // Get the search string.
3648 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3650 // Set the search string.
3651 if (searchString.equals("Custom URL")) { // A custom search string is used.
3652 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3653 } else { // A custom search string is not used.
3654 searchURL = searchString;
3657 // Get a handle for the app compat delegate.
3658 AppCompatDelegate appCompatDelegate = getDelegate();
3660 // Get handles for the views that need to be modified.
3661 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3662 ActionBar actionBar = appCompatDelegate.getSupportActionBar();
3664 // Remove the incorrect lint warning below that the action bar might be null.
3665 assert actionBar != null;
3670 // Set Do Not Track status.
3671 if (doNotTrackEnabled) {
3672 customHeaders.put("DNT", "1");
3674 customHeaders.remove("DNT");
3677 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3678 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3679 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3680 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3681 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3683 // Add the scrolling behavior to the layout parameters.
3685 // Enable scrolling of the app bar.
3686 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3687 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3688 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3689 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3691 // Disable scrolling of the app bar.
3692 swipeRefreshLayoutParams.setBehavior(null);
3693 toolbarLayoutParams.setScrollFlags(0);
3694 findOnPageLayoutParams.setScrollFlags(0);
3695 tabsLayoutParams.setScrollFlags(0);
3697 // Expand the app bar if it is currently collapsed.
3698 appBarLayout.setExpanded(true);
3701 // Apply the modified layout parameters.
3702 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3703 toolbar.setLayoutParams(toolbarLayoutParams);
3704 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3705 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3707 // Set the app bar scrolling for each WebView.
3708 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3709 // Get the WebView tab fragment.
3710 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3712 // Get the fragment view.
3713 View fragmentView = webViewTabFragment.getView();
3715 // Only modify the WebViews if they exist.
3716 if (fragmentView != null) {
3717 // Get the nested scroll WebView from the tab fragment.
3718 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3720 // Set the app bar scrolling.
3721 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3725 // Update the full screen browsing mode settings.
3726 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3727 // Update the visibility of the app bar, which might have changed in the settings.
3729 // Hide the tab linear layout.
3730 tabsLinearLayout.setVisibility(View.GONE);
3732 // Hide the action bar.
3735 // Show the tab linear layout.
3736 tabsLinearLayout.setVisibility(View.VISIBLE);
3738 // Show the action bar.
3742 // Hide the banner ad in the free flavor.
3743 if (BuildConfig.FLAVOR.contentEquals("free")) {
3744 AdHelper.hideAd(findViewById(R.id.adview));
3747 /* Hide the system bars.
3748 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3749 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3750 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3751 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3753 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3754 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3755 } else { // Privacy Browser is not in full screen browsing mode.
3756 // 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.
3757 inFullScreenBrowsingMode = false;
3759 // Show the tab linear layout.
3760 tabsLinearLayout.setVisibility(View.VISIBLE);
3762 // Show the action bar.
3765 // Show the banner ad in the free flavor.
3766 if (BuildConfig.FLAVOR.contentEquals("free")) {
3767 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3768 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3771 // Remove the `SYSTEM_UI` flags from the root frame layout.
3772 rootFrameLayout.setSystemUiVisibility(0);
3777 public void navigateHistory(String url, int steps) {
3778 // Apply the domain settings.
3779 applyDomainSettings(currentWebView, url, false, false, false);
3781 // Load the history entry.
3782 currentWebView.goBackOrForward(steps);
3786 public void pinnedErrorGoBack() {
3787 // Get the current web back forward list.
3788 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3790 // Get the previous entry URL.
3791 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3793 // Apply the domain settings.
3794 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3797 currentWebView.goBack();
3800 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3801 @SuppressLint("SetJavaScriptEnabled")
3802 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3803 // Store the current URL.
3804 nestedScrollWebView.setCurrentUrl(url);
3806 // Parse the URL into a URI.
3807 Uri uri = Uri.parse(url);
3809 // Extract the domain from `uri`.
3810 String newHostName = uri.getHost();
3812 // Strings don't like to be null.
3813 if (newHostName == null) {
3817 // 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.
3818 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3819 // Set the new host name as the current domain name.
3820 nestedScrollWebView.setCurrentDomainName(newHostName);
3822 // Reset the ignoring of pinned domain information.
3823 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3825 // Clear any pinned SSL certificate or IP addresses.
3826 nestedScrollWebView.clearPinnedSslCertificate();
3827 nestedScrollWebView.clearPinnedIpAddresses();
3829 // Reset the favorite icon if specified.
3831 // Initialize the favorite icon.
3832 nestedScrollWebView.initializeFavoriteIcon();
3834 // Get the current page position.
3835 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3837 // Get the corresponding tab.
3838 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3840 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3842 // Get the tab custom view.
3843 View tabCustomView = tab.getCustomView();
3845 // Remove the warning below that the tab custom view might be null.
3846 assert tabCustomView != null;
3848 // Get the tab views.
3849 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3850 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3852 // Set the default favorite icon as the favorite icon for this tab.
3853 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3855 // Set the loading title text.
3856 tabTitleTextView.setText(R.string.loading);
3860 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3861 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3863 // Get a full cursor from `domainsDatabaseHelper`.
3864 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3866 // Initialize `domainSettingsSet`.
3867 Set<String> domainSettingsSet = new HashSet<>();
3869 // Get the domain name column index.
3870 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3872 // Populate `domainSettingsSet`.
3873 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3874 // Move `domainsCursor` to the current row.
3875 domainNameCursor.moveToPosition(i);
3877 // Store the domain name in `domainSettingsSet`.
3878 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3881 // Close `domainNameCursor.
3882 domainNameCursor.close();
3884 // Initialize the domain name in database variable.
3885 String domainNameInDatabase = null;
3887 // Check the hostname against the domain settings set.
3888 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3889 // Record the domain name in the database.
3890 domainNameInDatabase = newHostName;
3892 // Set the domain settings applied tracker to true.
3893 nestedScrollWebView.setDomainSettingsApplied(true);
3894 } else { // The hostname is not contained in the domain settings set.
3895 // Set the domain settings applied tracker to false.
3896 nestedScrollWebView.setDomainSettingsApplied(false);
3899 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3900 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3901 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3902 // Set the domain settings applied tracker to true.
3903 nestedScrollWebView.setDomainSettingsApplied(true);
3905 // Store the applied domain names as it appears in the database.
3906 domainNameInDatabase = "*." + newHostName;
3909 // Strip out the lowest subdomain of of the host name.
3910 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3914 // Get a handle for the shared preferences.
3915 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3917 // Store the general preference information.
3918 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3919 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3920 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3921 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3922 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3923 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3925 // Get the WebView theme entry values string array.
3926 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3928 // Get a handle for the cookie manager.
3929 CookieManager cookieManager = CookieManager.getInstance();
3931 // Get handles for the views.
3932 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3933 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3935 // Initialize the user agent array adapter and string array.
3936 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3937 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3939 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3940 // Get a cursor for the current host and move it to the first position.
3941 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3942 currentDomainSettingsCursor.moveToFirst();
3944 // Get the settings from the cursor.
3945 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3946 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3947 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3948 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3949 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3950 // Form data can be removed once the minimum API >= 26.
3951 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3952 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3953 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3954 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3955 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3956 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3957 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3958 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3959 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3960 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3961 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3962 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3963 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3964 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3965 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3966 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3967 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3968 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WEBVIEW_THEME));
3969 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3970 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3971 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3972 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3973 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3974 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3975 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3976 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3977 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3978 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3979 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3981 // Get the pinned SSL date longs.
3982 long pinnedSslStartDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE));
3983 long pinnedSslEndDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE));
3985 // Define the pinned SSL date variables.
3986 Date pinnedSslStartDate;
3987 Date pinnedSslEndDate;
3989 // 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.
3990 if (pinnedSslStartDateLong == 0) {
3991 pinnedSslStartDate = null;
3993 pinnedSslStartDate = new Date(pinnedSslStartDateLong);
3996 // 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.
3997 if (pinnedSslEndDateLong == 0) {
3998 pinnedSslEndDate = null;
4000 pinnedSslEndDate = new Date(pinnedSslEndDateLong);
4003 // Close the current host domain settings cursor.
4004 currentDomainSettingsCursor.close();
4006 // If there is a pinned SSL certificate, store it in the WebView.
4007 if (pinnedSslCertificate) {
4008 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
4009 pinnedSslStartDate, pinnedSslEndDate);
4012 // If there is a pinned IP address, store it in the WebView.
4013 if (pinnedIpAddresses) {
4014 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
4017 // Apply the cookie domain settings.
4018 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4020 // Set third-party cookies status if API >= 21.
4021 if (Build.VERSION.SDK_INT >= 21) {
4022 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
4025 // Apply the form data setting if the API < 26.
4026 if (Build.VERSION.SDK_INT < 26) {
4027 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4030 // Apply the font size.
4031 try { // Try the specified font size to see if it is valid.
4032 if (fontSize == 0) { // Apply the default font size.
4033 // Try to set the font size from the value in the app settings.
4034 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4035 } else { // Apply the font size from domain settings.
4036 nestedScrollWebView.getSettings().setTextZoom(fontSize);
4038 } catch (Exception exception) { // The specified font size is invalid
4039 // Set the font size to be 100%
4040 nestedScrollWebView.getSettings().setTextZoom(100);
4043 // Set the user agent.
4044 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4045 // Get the array position of the default user agent name.
4046 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4048 // Set the user agent according to the system default.
4049 switch (defaultUserAgentArrayPosition) {
4050 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4051 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4052 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4055 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4056 // Set the user agent to `""`, which uses the default value.
4057 nestedScrollWebView.getSettings().setUserAgentString("");
4060 case SETTINGS_CUSTOM_USER_AGENT:
4061 // Set the default custom user agent.
4062 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4066 // Get the user agent string from the user agent data array
4067 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4069 } else { // Set the user agent according to the stored name.
4070 // Get the array position of the user agent name.
4071 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4073 switch (userAgentArrayPosition) {
4074 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4075 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
4078 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4079 // Set the user agent to `""`, which uses the default value.
4080 nestedScrollWebView.getSettings().setUserAgentString("");
4084 // Get the user agent string from the user agent data array.
4085 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4089 // Set swipe to refresh.
4090 switch (swipeToRefreshInt) {
4091 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4092 // Store the swipe to refresh status in the nested scroll WebView.
4093 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4095 // Update the swipe refresh layout.
4096 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4097 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4098 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4099 } else { // Swipe to refresh is disabled.
4100 // Disable the swipe refresh layout.
4101 swipeRefreshLayout.setEnabled(false);
4105 case DomainsDatabaseHelper.ENABLED:
4106 // Store the swipe to refresh status in the nested scroll WebView.
4107 nestedScrollWebView.setSwipeToRefresh(true);
4109 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4110 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4113 case DomainsDatabaseHelper.DISABLED:
4114 // Store the swipe to refresh status in the nested scroll WebView.
4115 nestedScrollWebView.setSwipeToRefresh(false);
4117 // Disable swipe to refresh.
4118 swipeRefreshLayout.setEnabled(false);
4121 // Check to see if WebView themes are supported.
4122 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4123 // Set the WebView theme.
4124 switch (webViewThemeInt) {
4125 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4126 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4127 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4128 // Turn off the WebView dark mode.
4129 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4130 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4131 // Turn on the WebView dark mode.
4132 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4133 } else { // The system default theme is selected.
4134 // Get the current system theme status.
4135 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4137 // Set the WebView theme according to the current system theme status.
4138 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4139 // Turn off the WebView dark mode.
4140 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4141 } else { // The system is in night mode.
4142 // Turn on the WebView dark mode.
4143 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4148 case DomainsDatabaseHelper.LIGHT_THEME:
4149 // Turn off the WebView dark mode.
4150 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4153 case DomainsDatabaseHelper.DARK_THEME:
4154 // Turn on the WebView dark mode.
4155 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4160 // Set the viewport.
4161 switch (wideViewportInt) {
4162 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4163 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4166 case DomainsDatabaseHelper.ENABLED:
4167 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4170 case DomainsDatabaseHelper.DISABLED:
4171 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4175 // Set the loading of webpage images.
4176 switch (displayWebpageImagesInt) {
4177 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4178 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4181 case DomainsDatabaseHelper.ENABLED:
4182 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4185 case DomainsDatabaseHelper.DISABLED:
4186 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4190 // Get the current theme status.
4191 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4193 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4194 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4195 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
4197 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
4199 } else { // The new URL does not have custom domain settings. Load the defaults.
4200 // Store the values from the shared preferences.
4201 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4202 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4203 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4204 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4205 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4206 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4207 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4208 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4209 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4210 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4211 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4212 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4214 // Apply the default first-party cookie setting.
4215 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4217 // Apply the default font size setting.
4219 // Try to set the font size from the value in the app settings.
4220 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4221 } catch (Exception exception) {
4222 // If the app settings value is invalid, set the font size to 100%.
4223 nestedScrollWebView.getSettings().setTextZoom(100);
4226 // Apply the form data setting if the API < 26.
4227 if (Build.VERSION.SDK_INT < 26) {
4228 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4231 // Store the swipe to refresh status in the nested scroll WebView.
4232 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4234 // Update the swipe refresh layout.
4235 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4236 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4237 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4238 } else { // Swipe to refresh is disabled.
4239 // Disable the swipe refresh layout.
4240 swipeRefreshLayout.setEnabled(false);
4243 // Reset the pinned variables.
4244 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4246 // Set third-party cookies status if API >= 21.
4247 if (Build.VERSION.SDK_INT >= 21) {
4248 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4251 // Get the array position of the user agent name.
4252 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4254 // Set the user agent.
4255 switch (userAgentArrayPosition) {
4256 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4257 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4258 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4261 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4262 // Set the user agent to `""`, which uses the default value.
4263 nestedScrollWebView.getSettings().setUserAgentString("");
4266 case SETTINGS_CUSTOM_USER_AGENT:
4267 // Set the default custom user agent.
4268 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4272 // Get the user agent string from the user agent data array
4273 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4276 // Apply the WebView theme if supported by the installed WebView.
4277 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4278 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4279 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4280 // Turn off the WebView dark mode.
4281 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4282 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4283 // Turn on the WebView dark mode.
4284 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4285 } else { // The system default theme is selected.
4286 // Get the current system theme status.
4287 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4289 // Set the WebView theme according to the current system theme status.
4290 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4291 // Turn off the WebView dark mode.
4292 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4293 } else { // The system is in night mode.
4294 // Turn on the WebView dark mode.
4295 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4300 // Set the viewport.
4301 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4303 // Set the loading of webpage images.
4304 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4306 // Set a transparent background on URL edit text.
4307 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4310 // Close the domains database helper.
4311 domainsDatabaseHelper.close();
4313 // Update the privacy icons.
4314 updatePrivacyIcons(true);
4317 // Reload the website if returning from the Domains activity.
4318 if (reloadWebsite) {
4319 nestedScrollWebView.reload();
4322 // Load the URL if directed. This makes sure that the domain settings are properly loaded before the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4324 nestedScrollWebView.loadUrl(url, customHeaders);
4328 private void applyProxy(boolean reloadWebViews) {
4329 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4330 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4332 // Reset the waiting for proxy tracker.
4333 waitingForProxy = false;
4335 // Get the current theme status.
4336 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4338 // Update the user interface and reload the WebViews if requested.
4339 switch (proxyMode) {
4340 case ProxyHelper.NONE:
4341 // Initialize a color background typed value.
4342 TypedValue colorBackgroundTypedValue = new TypedValue();
4344 // Get the color background from the theme.
4345 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4347 // Get the color background int from the typed value.
4348 int colorBackgroundInt = colorBackgroundTypedValue.data;
4350 // Set the default app bar layout background.
4351 appBarLayout.setBackgroundColor(colorBackgroundInt);
4354 case ProxyHelper.TOR:
4355 // Set the app bar background to indicate proxying through Orbot is enabled.
4356 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4357 appBarLayout.setBackgroundResource(R.color.blue_50);
4359 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4362 // Check to see if Orbot is installed.
4364 // Get the package manager.
4365 PackageManager packageManager = getPackageManager();
4367 // 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.
4368 packageManager.getPackageInfo("org.torproject.android", 0);
4370 // Check to see if the proxy is ready.
4371 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4372 // Set the waiting for proxy status.
4373 waitingForProxy = true;
4375 // Show the waiting for proxy dialog if it isn't already displayed.
4376 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4377 // Get a handle for the waiting for proxy alert dialog.
4378 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4380 // Display the waiting for proxy alert dialog.
4381 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4384 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4385 // Show the Orbot not installed dialog if it is not already displayed.
4386 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4387 // Get a handle for the Orbot not installed alert dialog.
4388 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4390 // Display the Orbot not installed alert dialog.
4391 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4396 case ProxyHelper.I2P:
4397 // Set the app bar background to indicate proxying through Orbot is enabled.
4398 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4399 appBarLayout.setBackgroundResource(R.color.blue_50);
4401 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4404 // Check to see if I2P is installed.
4406 // Get the package manager.
4407 PackageManager packageManager = getPackageManager();
4409 // 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.
4410 packageManager.getPackageInfo("org.torproject.android", 0);
4411 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4412 // Sow the I2P not installed dialog if it is not already displayed.
4413 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4414 // Get a handle for the waiting for proxy alert dialog.
4415 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4417 // Display the I2P not installed alert dialog.
4418 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4423 case ProxyHelper.CUSTOM:
4424 // Set the app bar background to indicate proxying through Orbot is enabled.
4425 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4426 appBarLayout.setBackgroundResource(R.color.blue_50);
4428 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4433 // Reload the WebViews if requested and not waiting for the proxy.
4434 if (reloadWebViews && !waitingForProxy) {
4435 // Reload the WebViews.
4436 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4437 // Get the WebView tab fragment.
4438 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4440 // Get the fragment view.
4441 View fragmentView = webViewTabFragment.getView();
4443 // Only reload the WebViews if they exist.
4444 if (fragmentView != null) {
4445 // Get the nested scroll WebView from the tab fragment.
4446 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4448 // Reload the WebView.
4449 nestedScrollWebView.reload();
4455 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4456 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4457 if ((optionsMenu != null) && (currentWebView != null)) {
4458 // Update the privacy icon.
4459 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4460 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4461 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4462 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4463 } else { // All the dangerous features are disabled.
4464 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4467 // Get the current theme status.
4468 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4470 // Update the first-party cookies icon.
4471 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4472 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4473 } else { // First-party cookies are disabled.
4474 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4475 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4477 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4481 // Update the refresh icon.
4482 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4483 // Set the icon according to the theme.
4484 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4485 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4487 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4489 } else { // The stop icon is displayed.
4490 // Set the icon according to the theme.
4491 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4492 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
4494 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
4498 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4499 if (runInvalidateOptionsMenu) {
4500 invalidateOptionsMenu();
4505 private void highlightUrlText() {
4506 // Get a handle for the URL edit text.
4507 EditText urlEditText = findViewById(R.id.url_edittext);
4509 // Only highlight the URL text if the box is not currently selected.
4510 if (!urlEditText.hasFocus()) {
4511 // Get the URL string.
4512 String urlString = urlEditText.getText().toString();
4514 // Highlight the URL according to the protocol.
4515 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4516 // De-emphasize everything before the file name.
4517 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4518 } else { // This is a web URL.
4519 // Get the index of the `/` immediately after the domain name.
4520 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4522 // Create a base URL string.
4525 // Get the base URL.
4526 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4527 // Get the base URL.
4528 baseUrl = urlString.substring(0, endOfDomainName);
4529 } else { // There are no characters after the base URL.
4530 // Set the base URL to be the entire URL string.
4531 baseUrl = urlString;
4534 // Get the index of the last `.` in the domain.
4535 int lastDotIndex = baseUrl.lastIndexOf(".");
4537 // Get the index of the penultimate `.` in the domain.
4538 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4540 // Markup the beginning of the URL.
4541 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4542 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4544 // De-emphasize subdomains.
4545 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4546 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4548 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4549 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4550 // De-emphasize the protocol and the additional subdomains.
4551 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4552 } else { // There is only one subdomain in the domain name.
4553 // De-emphasize only the protocol.
4554 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4558 // De-emphasize the text after the domain name.
4559 if (endOfDomainName > 0) {
4560 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4566 private void loadBookmarksFolder() {
4567 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4568 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4570 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4571 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4573 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4574 // Inflate the individual item layout. `false` does not attach it to the root.
4575 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4579 public void bindView(View view, Context context, Cursor cursor) {
4580 // Get handles for the views.
4581 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4582 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4584 // Get the favorite icon byte array from the cursor.
4585 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4587 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4588 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4590 // Display the bitmap in `bookmarkFavoriteIcon`.
4591 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4593 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4594 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4595 bookmarkNameTextView.setText(bookmarkNameString);
4597 // Make the font bold for folders.
4598 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4599 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4600 } else { // Reset the font to default for normal bookmarks.
4601 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4606 // Get a handle for the bookmarks list view.
4607 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4609 // Populate the list view with the adapter.
4610 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4612 // Get a handle for the bookmarks title text view.
4613 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4615 // Set the bookmarks drawer title.
4616 if (currentBookmarksFolder.isEmpty()) {
4617 bookmarksTitleTextView.setText(R.string.bookmarks);
4619 bookmarksTitleTextView.setText(currentBookmarksFolder);
4623 private void openWithApp(String url) {
4624 // Create an open with app intent with `ACTION_VIEW`.
4625 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4627 // Set the URI but not the MIME type. This should open all available apps.
4628 openWithAppIntent.setData(Uri.parse(url));
4630 // Flag the intent to open in a new task.
4631 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4635 // Show the chooser.
4636 startActivity(openWithAppIntent);
4637 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4638 // Show a snackbar with the error.
4639 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4643 private void openWithBrowser(String url) {
4644 // Create an open with browser intent with `ACTION_VIEW`.
4645 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4647 // Set the URI and the MIME type. `"text/html"` should load browser options.
4648 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4650 // Flag the intent to open in a new task.
4651 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4655 // Show the chooser.
4656 startActivity(openWithBrowserIntent);
4657 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4658 // Show a snackbar with the error.
4659 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4663 private String sanitizeUrl(String url) {
4664 // Sanitize Google Analytics.
4665 if (sanitizeGoogleAnalytics) {
4667 if (url.contains("?utm_")) {
4668 url = url.substring(0, url.indexOf("?utm_"));
4672 if (url.contains("&utm_")) {
4673 url = url.substring(0, url.indexOf("&utm_"));
4677 // Sanitize Facebook Click IDs.
4678 if (sanitizeFacebookClickIds) {
4679 // Remove `?fbclid=`.
4680 if (url.contains("?fbclid=")) {
4681 url = url.substring(0, url.indexOf("?fbclid="));
4684 // Remove `&fbclid=`.
4685 if (url.contains("&fbclid=")) {
4686 url = url.substring(0, url.indexOf("&fbclid="));
4689 // Remove `?fbadid=`.
4690 if (url.contains("?fbadid=")) {
4691 url = url.substring(0, url.indexOf("?fbadid="));
4694 // Remove `&fbadid=`.
4695 if (url.contains("&fbadid=")) {
4696 url = url.substring(0, url.indexOf("&fbadid="));
4700 // Sanitize Twitter AMP redirects.
4701 if (sanitizeTwitterAmpRedirects) {
4703 if (url.contains("?amp=1")) {
4704 url = url.substring(0, url.indexOf("?amp=1"));
4708 // Return the sanitized URL.
4712 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4713 // Store the blocklists.
4714 easyList = combinedBlocklists.get(0);
4715 easyPrivacy = combinedBlocklists.get(1);
4716 fanboysAnnoyanceList = combinedBlocklists.get(2);
4717 fanboysSocialList = combinedBlocklists.get(3);
4718 ultraList = combinedBlocklists.get(4);
4719 ultraPrivacy = combinedBlocklists.get(5);
4721 // Check to see if the activity has been restarted with a saved state.
4722 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4723 // Add the first tab.
4724 addNewTab("", true);
4725 } else { // The activity has been restarted.
4726 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4727 for (int i = 0; i < savedStateArrayList.size(); i++) {
4729 tabLayout.addTab(tabLayout.newTab());
4732 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4734 // Remove the lint warning below that the current tab might be null.
4735 assert newTab != null;
4737 // Set a custom view on the new tab.
4738 newTab.setCustomView(R.layout.tab_custom_view);
4740 // Add the new page.
4741 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4744 // Reset the saved state variables.
4745 savedStateArrayList = null;
4746 savedNestedScrollWebViewStateArrayList = null;
4748 // Restore the selected tab position.
4749 if (savedTabPosition == 0) { // The first tab is selected.
4750 // Set the first page as the current WebView.
4751 setCurrentWebView(0);
4752 } else { // the first tab is not selected.
4753 // Move to the selected tab.
4754 webViewPager.setCurrentItem(savedTabPosition);
4757 // Get the intent that started the app.
4758 Intent intent = getIntent();
4760 // Reset the intent. This prevents a duplicate tab from being created on restart.
4761 setIntent(new Intent());
4763 // Get the information from the intent.
4764 String intentAction = intent.getAction();
4765 Uri intentUriData = intent.getData();
4766 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4768 // Determine if this is a web search.
4769 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4771 // 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.
4772 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4773 // Get the shared preferences.
4774 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4776 // Create a URL string.
4779 // If the intent action is a web search, perform the search.
4780 if (isWebSearch) { // The intent is a web search.
4781 // Create an encoded URL string.
4782 String encodedUrlString;
4784 // Sanitize the search input and convert it to a search.
4786 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4787 } catch (UnsupportedEncodingException exception) {
4788 encodedUrlString = "";
4791 // Add the base search URL.
4792 url = searchURL + encodedUrlString;
4793 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4794 // Set the intent data as the URL.
4795 url = intentUriData.toString();
4796 } else { // The intent contains a string, which might be a URL.
4797 // Set the intent string as the URL.
4798 url = intentStringExtra;
4801 // Add a new tab if specified in the preferences.
4802 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4803 // Set the loading new intent flag.
4804 loadingNewIntent = true;
4807 addNewTab(url, true);
4808 } else { // Load the URL in the current tab.
4810 loadUrl(currentWebView, url);
4816 public void addTab(View view) {
4817 // Add a new tab with a blank URL.
4818 addNewTab("", true);
4821 private void addNewTab(String url, boolean moveToTab) {
4822 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4823 int newTabNumber = tabLayout.getTabCount();
4826 tabLayout.addTab(tabLayout.newTab());
4829 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4831 // Remove the lint warning below that the current tab might be null.
4832 assert newTab != null;
4834 // Set a custom view on the new tab.
4835 newTab.setCustomView(R.layout.tab_custom_view);
4837 // Add the new WebView page.
4838 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4841 public void closeTab(View view) {
4842 // Run the command according to the number of tabs.
4843 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4844 // Close the current tab.
4846 } else { // There is only one tab open.
4851 private void closeCurrentTab() {
4852 // Pause the current WebView. This prevents buffered audio from playing after the tab is closed.
4853 currentWebView.onPause();
4855 // Get the current tab number.
4856 int currentTabNumber = tabLayout.getSelectedTabPosition();
4858 // Delete the current tab.
4859 tabLayout.removeTabAt(currentTabNumber);
4861 // 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.
4862 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4863 setCurrentWebView(currentTabNumber);
4866 // Expand the app bar if it is currently collapsed.
4867 appBarLayout.setExpanded(true);
4870 private void saveWebpageArchive(String filePath) {
4871 // Save the webpage archive.
4872 currentWebView.saveWebArchive(filePath);
4874 // Display a snackbar.
4875 Snackbar saveWebpageArchiveSnackbar = Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + filePath, Snackbar.LENGTH_SHORT);
4877 // Add an open option to the snackbar.
4878 saveWebpageArchiveSnackbar.setAction(R.string.open, (View view) -> {
4879 // Get a file for the file name string.
4880 File file = new File(filePath);
4882 // Declare a file URI variable.
4885 // Get the URI for the file according to the Android version.
4886 if (Build.VERSION.SDK_INT >= 24) { // Use a file provider.
4887 fileUri = FileProvider.getUriForFile(this, getString(R.string.file_provider), file);
4888 } else { // Get the raw file path URI.
4889 fileUri = Uri.fromFile(file);
4892 // Get a handle for the content resolver.
4893 ContentResolver contentResolver = getContentResolver();
4895 // Create an open intent with `ACTION_VIEW`.
4896 Intent openIntent = new Intent(Intent.ACTION_VIEW);
4898 // Set the URI and the MIME type.
4899 openIntent.setDataAndType(fileUri, contentResolver.getType(fileUri));
4901 // Allow the app to read the file URI.
4902 openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
4904 // Show the chooser.
4905 startActivity(Intent.createChooser(openIntent, getString(R.string.open)));
4908 // Show the snackbar.
4909 saveWebpageArchiveSnackbar.show();
4912 private void clearAndExit() {
4913 // Get a handle for the shared preferences.
4914 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4916 // Close the bookmarks cursor and database.
4917 bookmarksCursor.close();
4918 bookmarksDatabaseHelper.close();
4920 // Get the status of the clear everything preference.
4921 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4923 // Get a handle for the runtime.
4924 Runtime runtime = Runtime.getRuntime();
4926 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4927 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4928 String privateDataDirectoryString = getApplicationInfo().dataDir;
4931 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4932 // The command to remove cookies changed slightly in API 21.
4933 if (Build.VERSION.SDK_INT >= 21) {
4934 CookieManager.getInstance().removeAllCookies(null);
4936 CookieManager.getInstance().removeAllCookie();
4939 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4941 // Two commands must be used because `Runtime.exec()` does not like `*`.
4942 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4943 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4945 // Wait until the processes have finished.
4946 deleteCookiesProcess.waitFor();
4947 deleteCookiesJournalProcess.waitFor();
4948 } catch (Exception exception) {
4949 // Do nothing if an error is thrown.
4953 // Clear DOM storage.
4954 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4955 // Ask `WebStorage` to clear the DOM storage.
4956 WebStorage webStorage = WebStorage.getInstance();
4957 webStorage.deleteAllData();
4959 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4961 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4962 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4964 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4965 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4966 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4967 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4968 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4970 // Wait until the processes have finished.
4971 deleteLocalStorageProcess.waitFor();
4972 deleteIndexProcess.waitFor();
4973 deleteQuotaManagerProcess.waitFor();
4974 deleteQuotaManagerJournalProcess.waitFor();
4975 deleteDatabaseProcess.waitFor();
4976 } catch (Exception exception) {
4977 // Do nothing if an error is thrown.
4981 // Clear form data if the API < 26.
4982 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4983 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4984 webViewDatabase.clearFormData();
4986 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4988 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4989 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4990 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4992 // Wait until the processes have finished.
4993 deleteWebDataProcess.waitFor();
4994 deleteWebDataJournalProcess.waitFor();
4995 } catch (Exception exception) {
4996 // Do nothing if an error is thrown.
5000 // Clear the logcat.
5001 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
5003 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5004 Process process = Runtime.getRuntime().exec("logcat -b all -c");
5006 // Wait for the process to finish.
5008 } catch (IOException|InterruptedException exception) {
5014 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
5015 // Clear the cache from each WebView.
5016 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
5017 // Get the WebView tab fragment.
5018 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
5020 // Get the fragment view.
5021 View fragmentView = webViewTabFragment.getView();
5023 // Only clear the cache if the WebView exists.
5024 if (fragmentView != null) {
5025 // Get the nested scroll WebView from the tab fragment.
5026 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
5028 // Clear the cache for this WebView.
5029 nestedScrollWebView.clearCache(true);
5033 // Manually delete the cache directories.
5035 // Delete the main cache directory.
5036 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
5038 // Delete the secondary `Service Worker` cache directory.
5039 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
5040 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5042 // Wait until the processes have finished.
5043 deleteCacheProcess.waitFor();
5044 deleteServiceWorkerProcess.waitFor();
5045 } catch (Exception exception) {
5046 // Do nothing if an error is thrown.
5050 // Wipe out each WebView.
5051 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
5052 // Get the WebView tab fragment.
5053 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
5055 // Get the fragment view.
5056 View fragmentView = webViewTabFragment.getView();
5058 // Only wipe out the WebView if it exists.
5059 if (fragmentView != null) {
5060 // Get the nested scroll WebView from the tab fragment.
5061 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
5063 // Clear SSL certificate preferences for this WebView.
5064 nestedScrollWebView.clearSslPreferences();
5066 // Clear the back/forward history for this WebView.
5067 nestedScrollWebView.clearHistory();
5069 // Destroy the internal state of the WebView.
5070 nestedScrollWebView.destroy();
5074 // Clear the custom headers.
5075 customHeaders.clear();
5077 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
5078 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
5079 if (clearEverything) {
5081 // Delete the folder.
5082 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
5084 // Wait until the process has finished.
5085 deleteAppWebviewProcess.waitFor();
5086 } catch (Exception exception) {
5087 // Do nothing if an error is thrown.
5091 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
5092 if (Build.VERSION.SDK_INT >= 21) {
5093 finishAndRemoveTask();
5098 // Remove the terminated program from RAM. The status code is `0`.
5102 public void bookmarksBack(View view) {
5103 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
5104 // close the bookmarks drawer.
5105 drawerLayout.closeDrawer(GravityCompat.END);
5106 } else { // A subfolder is displayed.
5107 // Place the former parent folder in `currentFolder`.
5108 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
5110 // Load the new folder.
5111 loadBookmarksFolder();
5115 private void setCurrentWebView(int pageNumber) {
5116 // Get handles for the URL views.
5117 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
5118 EditText urlEditText = findViewById(R.id.url_edittext);
5119 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
5121 // Stop the swipe to refresh indicator if it is running
5122 swipeRefreshLayout.setRefreshing(false);
5124 // Get the WebView tab fragment.
5125 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
5127 // Get the fragment view.
5128 View fragmentView = webViewTabFragment.getView();
5130 // Set the current WebView if the fragment view is not null.
5131 if (fragmentView != null) { // The fragment has been populated.
5132 // Store the current WebView.
5133 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
5135 // Update the status of swipe to refresh.
5136 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
5137 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5138 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
5139 } else { // Swipe to refresh is disabled.
5140 // Disable the swipe refresh layout.
5141 swipeRefreshLayout.setEnabled(false);
5144 // Get a handle for the cookie manager.
5145 CookieManager cookieManager = CookieManager.getInstance();
5147 // Set the first-party cookie status.
5148 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
5150 // Update the privacy icons. `true` redraws the icons in the app bar.
5151 updatePrivacyIcons(true);
5153 // Get a handle for the input method manager.
5154 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5156 // Remove the lint warning below that the input method manager might be null.
5157 assert inputMethodManager != null;
5159 // Get the current URL.
5160 String url = currentWebView.getUrl();
5162 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5163 if (!loadingNewIntent) { // A new intent is not being loaded.
5164 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5165 // Display the hint in the URL edit text.
5166 urlEditText.setText("");
5168 // Request focus for the URL text box.
5169 urlEditText.requestFocus();
5171 // Display the keyboard.
5172 inputMethodManager.showSoftInput(urlEditText, 0);
5173 } else { // The WebView has a loaded URL.
5174 // Clear the focus from the URL text box.
5175 urlEditText.clearFocus();
5177 // Hide the soft keyboard.
5178 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5180 // Display the current URL in the URL text box.
5181 urlEditText.setText(url);
5183 // Highlight the URL text.
5186 } else { // A new intent is being loaded.
5187 // Reset the loading new intent tracker.
5188 loadingNewIntent = false;
5191 // Set the background to indicate the domain settings status.
5192 if (currentWebView.getDomainSettingsApplied()) {
5193 // Get the current theme status.
5194 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5196 // Set a green background on the URL relative layout to indicate that custom domain settings are being used.
5197 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
5198 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
5200 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
5203 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5205 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5206 // Create a handler to set the current WebView.
5207 Handler setCurrentWebViewHandler = new Handler();
5209 // Create a runnable to set the current WebView.
5210 Runnable setCurrentWebWebRunnable = () -> {
5211 // Set the current WebView.
5212 setCurrentWebView(pageNumber);
5215 // Try setting the current WebView again after 100 milliseconds.
5216 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5221 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5222 // Get a handle for the shared preferences.
5223 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5225 // Get the WebView theme.
5226 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5228 // Get the WebView theme entry values string array.
5229 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5231 // Apply the WebView theme if supported by the installed WebView.
5232 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5233 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5234 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5235 // Turn off the WebView dark mode.
5236 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5238 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5239 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5240 nestedScrollWebView.setVisibility(View.VISIBLE);
5241 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5242 // Turn on the WebView dark mode.
5243 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5244 } else { // The system default theme is selected.
5245 // Get the current system theme status.
5246 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5248 // Set the WebView theme according to the current system theme status.
5249 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5250 // Turn off the WebView dark mode.
5251 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5253 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5254 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5255 nestedScrollWebView.setVisibility(View.VISIBLE);
5256 } else { // The system is in night mode.
5257 // Turn on the WebView dark mode.
5258 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5263 // Get a handle for the app compat delegate.
5264 AppCompatDelegate appCompatDelegate = getDelegate();
5266 // Get handles for the activity views.
5267 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
5268 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
5269 ActionBar actionBar = appCompatDelegate.getSupportActionBar();
5270 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
5271 EditText urlEditText = findViewById(R.id.url_edittext);
5272 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
5274 // Remove the incorrect lint warning below that the action bar might be null.
5275 assert actionBar != null;
5277 // Get a handle for the activity
5278 Activity activity = this;
5280 // Get a handle for the input method manager.
5281 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5283 // Instantiate the blocklist helper.
5284 BlocklistHelper blocklistHelper = new BlocklistHelper();
5286 // Remove the lint warning below that the input method manager might be null.
5287 assert inputMethodManager != null;
5289 // Initialize the favorite icon.
5290 nestedScrollWebView.initializeFavoriteIcon();
5292 // Set the app bar scrolling.
5293 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5295 // Allow pinch to zoom.
5296 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5298 // Hide zoom controls.
5299 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5301 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5302 if (Build.VERSION.SDK_INT >= 21) {
5303 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5306 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5307 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5309 // Explicitly disable geolocation.
5310 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5312 // Create a double-tap gesture detector to toggle full-screen mode.
5313 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5314 // Override `onDoubleTap()`. All other events are handled using the default settings.
5316 public boolean onDoubleTap(MotionEvent event) {
5317 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5318 // Toggle the full screen browsing mode tracker.
5319 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5321 // Toggle the full screen browsing mode.
5322 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5323 // Hide the app bar if specified.
5325 // Close the find on page bar if it is visible.
5326 closeFindOnPage(null);
5328 // Hide the tab linear layout.
5329 tabsLinearLayout.setVisibility(View.GONE);
5331 // Hide the action bar.
5334 // Check to see if the app bar is normally scrolled.
5335 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5336 // Get the swipe refresh layout parameters.
5337 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5339 // Remove the off-screen scrolling layout.
5340 swipeRefreshLayoutParams.setBehavior(null);
5341 } else { // The app bar is not scrolled when it is displayed.
5342 // Remove the padding from the top of the swipe refresh layout.
5343 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5345 // The swipe refresh circle must be moved above the now removed status bar location.
5346 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5350 // Hide the banner ad in the free flavor.
5351 if (BuildConfig.FLAVOR.contentEquals("free")) {
5352 AdHelper.hideAd(findViewById(R.id.adview));
5355 /* Hide the system bars.
5356 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5357 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5358 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5359 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5361 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5362 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5363 } else { // Switch to normal viewing mode.
5364 // Show the app bar if it was hidden.
5366 // Show the tab linear layout.
5367 tabsLinearLayout.setVisibility(View.VISIBLE);
5369 // Show the action bar.
5372 // Check to see if the app bar is normally scrolled.
5373 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5374 // Get the swipe refresh layout parameters.
5375 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5377 // Add the off-screen scrolling layout.
5378 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5379 } else { // The app bar is not scrolled when it is displayed.
5380 // The swipe refresh layout must be manually moved below the app bar layout.
5381 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5383 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5384 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5388 // Show the banner ad in the free flavor.
5389 if (BuildConfig.FLAVOR.contentEquals("free")) {
5391 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5394 // Remove the `SYSTEM_UI` flags from the root frame layout.
5395 rootFrameLayout.setSystemUiVisibility(0);
5398 // Consume the double-tap.
5400 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5406 // Pass all touch events on the WebView through the double-tap gesture detector.
5407 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5408 // Call `performClick()` on the view, which is required for accessibility.
5409 view.performClick();
5411 // Send the event to the gesture detector.
5412 return doubleTapGestureDetector.onTouchEvent(event);
5415 // Register the WebView for a context menu. This is used to see link targets and download images.
5416 registerForContextMenu(nestedScrollWebView);
5418 // Allow the downloading of files.
5419 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5420 // Define a formatted file size string.
5421 String formattedFileSizeString;
5423 // Process the content length if it contains data.
5424 if (contentLength > 0) { // The content length is greater than 0.
5425 // Format the content length as a string.
5426 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5427 } else { // The content length is not greater than 0.
5428 // Set the formatted file size string to be `unknown size`.
5429 formattedFileSizeString = getString(R.string.unknown_size);
5432 // Get the file name from the content disposition.
5433 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5435 // Instantiate the save dialog.
5436 DialogFragment saveDialogFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_URL, downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5437 nestedScrollWebView.getAcceptFirstPartyCookies());
5439 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5440 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5443 // Update the find on page count.
5444 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5445 // Get a handle for `findOnPageCountTextView`.
5446 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5449 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5450 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5451 // Set `findOnPageCountTextView` to `0/0`.
5452 findOnPageCountTextView.setText(R.string.zero_of_zero);
5453 } else if (isDoneCounting) { // There are matches.
5454 // `activeMatchOrdinal` is zero-based.
5455 int activeMatch = activeMatchOrdinal + 1;
5457 // Build the match string.
5458 String matchString = activeMatch + "/" + numberOfMatches;
5460 // Set `findOnPageCountTextView`.
5461 findOnPageCountTextView.setText(matchString);
5466 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5467 // 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.
5468 if (Build.VERSION.SDK_INT >= 23) {
5469 nestedScrollWebView.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
5470 if (nestedScrollWebView.getSwipeToRefresh()) {
5471 // Only enable swipe to refresh if the WebView is scrolled to the top.
5472 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5474 // Disable swipe to refresh.
5475 swipeRefreshLayout.setEnabled(false);
5478 // Reinforce the system UI visibility flags if in full screen browsing mode.
5479 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5480 if (inFullScreenBrowsingMode) {
5481 /* Hide the system bars.
5482 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5483 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5484 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5485 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5487 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5488 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5492 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5493 if (nestedScrollWebView.getSwipeToRefresh()) {
5494 // Only enable swipe to refresh if the WebView is scrolled to the top.
5495 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5497 // Disable swipe to refresh.
5498 swipeRefreshLayout.setEnabled(false);
5502 // Reinforce the system UI visibility flags if in full screen browsing mode.
5503 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5504 if (inFullScreenBrowsingMode) {
5505 /* Hide the system bars.
5506 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5507 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5508 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5509 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5511 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5512 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5517 // Set the web chrome client.
5518 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5519 // Update the progress bar when a page is loading.
5521 public void onProgressChanged(WebView view, int progress) {
5522 // Update the progress bar.
5523 progressBar.setProgress(progress);
5525 // Set the visibility of the progress bar.
5526 if (progress < 100) {
5527 // Show the progress bar.
5528 progressBar.setVisibility(View.VISIBLE);
5530 // Hide the progress bar.
5531 progressBar.setVisibility(View.GONE);
5533 //Stop the swipe to refresh indicator if it is running
5534 swipeRefreshLayout.setRefreshing(false);
5536 // Make the current WebView visible. If this is a new tab, the current WebView would have been created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5537 nestedScrollWebView.setVisibility(View.VISIBLE);
5541 // Set the favorite icon when it changes.
5543 public void onReceivedIcon(WebView view, Bitmap icon) {
5544 // Only update the favorite icon if the website has finished loading.
5545 if (progressBar.getVisibility() == View.GONE) {
5546 // Store the new favorite icon.
5547 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5549 // Get the current page position.
5550 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5552 // Get the current tab.
5553 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5555 // Check to see if the tab has been populated.
5557 // Get the custom view from the tab.
5558 View tabView = tab.getCustomView();
5560 // Check to see if the custom tab view has been populated.
5561 if (tabView != null) {
5562 // Get the favorite icon image view from the tab.
5563 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5565 // Display the favorite icon in the tab.
5566 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5572 // Save a copy of the title when it changes.
5574 public void onReceivedTitle(WebView view, String title) {
5575 // Get the current page position.
5576 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5578 // Get the current tab.
5579 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5581 // Only populate the title text view if the tab has been fully created.
5583 // Get the custom view from the tab.
5584 View tabView = tab.getCustomView();
5586 // Only populate the title text view if the tab view has been fully populated.
5587 if (tabView != null) {
5588 // Get the title text view from the tab.
5589 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5591 // Set the title according to the URL.
5592 if (title.equals("about:blank")) {
5593 // Set the title to indicate a new tab.
5594 tabTitleTextView.setText(R.string.new_tab);
5596 // Set the title as the tab text.
5597 tabTitleTextView.setText(title);
5603 // Enter full screen video.
5605 public void onShowCustomView(View video, CustomViewCallback callback) {
5606 // Get a handle for the full screen video frame layout.
5607 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5609 // Set the full screen video flag.
5610 displayingFullScreenVideo = true;
5612 // Pause the ad if this is the free flavor.
5613 if (BuildConfig.FLAVOR.contentEquals("free")) {
5614 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5615 AdHelper.pauseAd(findViewById(R.id.adview));
5618 // Hide the keyboard.
5619 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5621 // Hide the main content relative layout.
5622 mainContentRelativeLayout.setVisibility(View.GONE);
5624 /* Hide the system bars.
5625 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5626 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5627 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5628 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5630 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5631 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5633 // Disable the sliding drawers.
5634 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5636 // Add the video view to the full screen video frame layout.
5637 fullScreenVideoFrameLayout.addView(video);
5639 // Show the full screen video frame layout.
5640 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5642 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5643 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5646 // Exit full screen video.
5648 public void onHideCustomView() {
5649 // Get a handle for the full screen video frame layout.
5650 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5652 // Re-enable the screen timeout.
5653 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5655 // Unset the full screen video flag.
5656 displayingFullScreenVideo = false;
5658 // Remove all the views from the full screen video frame layout.
5659 fullScreenVideoFrameLayout.removeAllViews();
5661 // Hide the full screen video frame layout.
5662 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5664 // Enable the sliding drawers.
5665 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5667 // Show the main content relative layout.
5668 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5670 // Apply the appropriate full screen mode flags.
5671 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5672 // Hide the app bar if specified.
5674 // Hide the tab linear layout.
5675 tabsLinearLayout.setVisibility(View.GONE);
5677 // Hide the action bar.
5681 // Hide the banner ad in the free flavor.
5682 if (BuildConfig.FLAVOR.contentEquals("free")) {
5683 AdHelper.hideAd(findViewById(R.id.adview));
5686 /* Hide the system bars.
5687 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5688 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5689 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5690 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5692 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5693 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5694 } else { // Switch to normal viewing mode.
5695 // Remove the `SYSTEM_UI` flags from the root frame layout.
5696 rootFrameLayout.setSystemUiVisibility(0);
5699 // Reload the ad for the free flavor if not in full screen mode.
5700 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5702 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5708 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5709 // Show the file chooser if the device is running API >= 21.
5710 if (Build.VERSION.SDK_INT >= 21) {
5711 // Store the file path callback.
5712 fileChooserCallback = filePathCallback;
5714 // Create an intent to open a chooser based on the file chooser parameters.
5715 Intent fileChooserIntent = fileChooserParams.createIntent();
5717 // Get a handle for the package manager.
5718 PackageManager packageManager = getPackageManager();
5720 // Check to see if the file chooser intent resolves to an installed package.
5721 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5722 // Start the file chooser intent.
5723 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5724 } else { // The file chooser intent will cause a crash.
5725 // Create a generic intent to open a chooser.
5726 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5728 // Request an openable file.
5729 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5731 // Set the file type to everything.
5732 genericFileChooserIntent.setType("*/*");
5734 // Start the generic file chooser intent.
5735 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5742 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5743 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5744 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5746 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5747 // Sanitize the url.
5748 url = sanitizeUrl(url);
5750 // Handle the URL according to the type.
5751 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5752 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5753 loadUrl(nestedScrollWebView, url);
5755 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5756 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5758 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5759 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5760 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5762 // Parse the url and set it as the data for the intent.
5763 emailIntent.setData(Uri.parse(url));
5765 // Open the email program in a new task instead of as part of Privacy Browser.
5766 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5770 startActivity(emailIntent);
5771 } catch (ActivityNotFoundException exception) {
5772 // Display a snackbar.
5773 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5777 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5779 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5780 // Open the dialer and load the phone number, but wait for the user to place the call.
5781 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5783 // Add the phone number to the intent.
5784 dialIntent.setData(Uri.parse(url));
5786 // Open the dialer in a new task instead of as part of Privacy Browser.
5787 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5791 startActivity(dialIntent);
5792 } catch (ActivityNotFoundException exception) {
5793 // Display a snackbar.
5794 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5797 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5799 } else { // Load a system chooser to select an app that can handle the URL.
5800 // Open an app that can handle the URL.
5801 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5803 // Add the URL to the intent.
5804 genericIntent.setData(Uri.parse(url));
5806 // List all apps that can handle the URL instead of just opening the first one.
5807 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5809 // Open the app in a new task instead of as part of Privacy Browser.
5810 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5812 // Start the app or display a snackbar if no app is available to handle the URL.
5814 startActivity(genericIntent);
5815 } catch (ActivityNotFoundException exception) {
5816 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5819 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5824 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5826 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5827 // Check to see if the resource request is for the main URL.
5828 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5829 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5833 // 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.
5834 while (ultraPrivacy == null) {
5835 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5836 synchronized (this) {
5838 // Check to see if the blocklists have been populated after 100 ms.
5840 } catch (InterruptedException exception) {
5846 // Sanitize the URL.
5847 url = sanitizeUrl(url);
5849 // Create an empty web resource response to be used if the resource request is blocked.
5850 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5852 // Reset the whitelist results tracker.
5853 String[] whitelistResultStringArray = null;
5855 // Initialize the third party request tracker.
5856 boolean isThirdPartyRequest = false;
5858 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5859 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5861 // Store a copy of the current domain for use in later requests.
5862 String currentDomain = currentBaseDomain;
5864 // Nobody is happy when comparing null strings.
5865 if ((currentBaseDomain != null) && (url != null)) {
5866 // Convert the request URL to a URI.
5867 Uri requestUri = Uri.parse(url);
5869 // Get the request host name.
5870 String requestBaseDomain = requestUri.getHost();
5872 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5873 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5874 // Determine the current base domain.
5875 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5876 // Remove the first subdomain.
5877 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5880 // Determine the request base domain.
5881 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5882 // Remove the first subdomain.
5883 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5886 // Update the third party request tracker.
5887 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5891 // Get the current WebView page position.
5892 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5894 // Determine if the WebView is currently displayed.
5895 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5897 // Block third-party requests if enabled.
5898 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5899 // Add the result to the resource requests.
5900 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5902 // Increment the blocked requests counters.
5903 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5904 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5906 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5907 if (webViewDisplayed) {
5908 // Updating the UI must be run from the UI thread.
5909 activity.runOnUiThread(() -> {
5910 // Update the menu item titles.
5911 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5913 // Update the options menu if it has been populated.
5914 if (optionsMenu != null) {
5915 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5916 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5917 getString(R.string.block_all_third_party_requests));
5922 // Return an empty web resource response.
5923 return emptyWebResourceResponse;
5926 // Check UltraList if it is enabled.
5927 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5928 // Check the URL against UltraList.
5929 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5931 // Process the UltraList results.
5932 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5933 // Add the result to the resource requests.
5934 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5936 // Increment the blocked requests counters.
5937 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5938 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5940 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5941 if (webViewDisplayed) {
5942 // Updating the UI must be run from the UI thread.
5943 activity.runOnUiThread(() -> {
5944 // Update the menu item titles.
5945 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5947 // Update the options menu if it has been populated.
5948 if (optionsMenu != null) {
5949 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5950 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5955 // The resource request was blocked. Return an empty web resource response.
5956 return emptyWebResourceResponse;
5957 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5958 // Add a whitelist entry to the resource requests array.
5959 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5961 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5966 // Check UltraPrivacy if it is enabled.
5967 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5968 // Check the URL against UltraPrivacy.
5969 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5971 // Process the UltraPrivacy results.
5972 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5973 // Add the result to the resource requests.
5974 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5975 ultraPrivacyResults[5]});
5977 // Increment the blocked requests counters.
5978 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5979 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5981 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5982 if (webViewDisplayed) {
5983 // Updating the UI must be run from the UI thread.
5984 activity.runOnUiThread(() -> {
5985 // Update the menu item titles.
5986 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5988 // Update the options menu if it has been populated.
5989 if (optionsMenu != null) {
5990 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5991 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5996 // The resource request was blocked. Return an empty web resource response.
5997 return emptyWebResourceResponse;
5998 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5999 // Add a whitelist entry to the resource requests array.
6000 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
6001 ultraPrivacyResults[5]});
6003 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
6008 // Check EasyList if it is enabled.
6009 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
6010 // Check the URL against EasyList.
6011 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
6013 // Process the EasyList results.
6014 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
6015 // Add the result to the resource requests.
6016 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
6018 // Increment the blocked requests counters.
6019 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6020 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
6022 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6023 if (webViewDisplayed) {
6024 // Updating the UI must be run from the UI thread.
6025 activity.runOnUiThread(() -> {
6026 // Update the menu item titles.
6027 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6029 // Update the options menu if it has been populated.
6030 if (optionsMenu != null) {
6031 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6032 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
6037 // The resource request was blocked. Return an empty web resource response.
6038 return emptyWebResourceResponse;
6039 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
6040 // Update the whitelist result string array tracker.
6041 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
6045 // Check EasyPrivacy if it is enabled.
6046 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
6047 // Check the URL against EasyPrivacy.
6048 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
6050 // Process the EasyPrivacy results.
6051 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
6052 // Add the result to the resource requests.
6053 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
6054 easyPrivacyResults[5]});
6056 // Increment the blocked requests counters.
6057 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6058 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
6060 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6061 if (webViewDisplayed) {
6062 // Updating the UI must be run from the UI thread.
6063 activity.runOnUiThread(() -> {
6064 // Update the menu item titles.
6065 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6067 // Update the options menu if it has been populated.
6068 if (optionsMenu != null) {
6069 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6070 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
6075 // The resource request was blocked. Return an empty web resource response.
6076 return emptyWebResourceResponse;
6077 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
6078 // Update the whitelist result string array tracker.
6079 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
6083 // Check Fanboy’s Annoyance List if it is enabled.
6084 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
6085 // Check the URL against Fanboy's Annoyance List.
6086 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
6088 // Process the Fanboy's Annoyance List results.
6089 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
6090 // Add the result to the resource requests.
6091 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
6092 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
6094 // Increment the blocked requests counters.
6095 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6096 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
6098 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6099 if (webViewDisplayed) {
6100 // Updating the UI must be run from the UI thread.
6101 activity.runOnUiThread(() -> {
6102 // Update the menu item titles.
6103 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6105 // Update the options menu if it has been populated.
6106 if (optionsMenu != null) {
6107 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6108 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
6109 getString(R.string.fanboys_annoyance_list));
6114 // The resource request was blocked. Return an empty web resource response.
6115 return emptyWebResourceResponse;
6116 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
6117 // Update the whitelist result string array tracker.
6118 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
6119 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
6121 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
6122 // Check the URL against Fanboy's Annoyance List.
6123 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
6125 // Process the Fanboy's Social Blocking List results.
6126 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
6127 // Add the result to the resource requests.
6128 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6129 fanboysSocialListResults[4], fanboysSocialListResults[5]});
6131 // Increment the blocked requests counters.
6132 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6133 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
6135 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6136 if (webViewDisplayed) {
6137 // Updating the UI must be run from the UI thread.
6138 activity.runOnUiThread(() -> {
6139 // Update the menu item titles.
6140 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6142 // Update the options menu if it has been populated.
6143 if (optionsMenu != null) {
6144 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6145 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
6146 getString(R.string.fanboys_social_blocking_list));
6151 // The resource request was blocked. Return an empty web resource response.
6152 return emptyWebResourceResponse;
6153 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
6154 // Update the whitelist result string array tracker.
6155 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6156 fanboysSocialListResults[4], fanboysSocialListResults[5]};
6160 // Add the request to the log because it hasn't been processed by any of the previous checks.
6161 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
6162 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
6163 } else { // The request didn't match any blocklist entry. Log it as a default request.
6164 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
6167 // The resource request has not been blocked. `return null` loads the requested resource.
6171 // Handle HTTP authentication requests.
6173 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
6174 // Store the handler.
6175 nestedScrollWebView.setHttpAuthHandler(handler);
6177 // Instantiate an HTTP authentication dialog.
6178 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
6180 // Show the HTTP authentication dialog.
6181 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
6185 public void onPageStarted(WebView view, String url, Bitmap favicon) {
6186 // Get the preferences.
6187 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
6189 // 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.
6190 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6191 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6192 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6194 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6195 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6197 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6198 appBarHeight = appBarLayout.getHeight();
6200 // The swipe refresh layout must be manually moved below the app bar layout.
6201 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6203 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6204 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6207 // Reset the list of resource requests.
6208 nestedScrollWebView.clearResourceRequests();
6210 // Reset the requests counters.
6211 nestedScrollWebView.resetRequestsCounters();
6213 // Get the current page position.
6214 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6216 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6217 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6218 // Display the formatted URL text.
6219 urlEditText.setText(url);
6221 // Apply text highlighting to `urlTextBox`.
6224 // Hide the keyboard.
6225 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6228 // Reset the list of host IP addresses.
6229 nestedScrollWebView.clearCurrentIpAddresses();
6231 // Get a URI for the current URL.
6232 Uri currentUri = Uri.parse(url);
6234 // Get the IP addresses for the host.
6235 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6237 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6238 if (optionsMenu != null) {
6240 optionsRefreshMenuItem.setTitle(R.string.stop);
6242 // Get the app bar and theme preferences.
6243 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6245 // If the icon is displayed in the AppBar, set it according to the theme.
6246 if (displayAdditionalAppBarIcons) {
6247 // Get the current theme status.
6248 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6250 // Set the stop icon according to the theme.
6251 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6252 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
6254 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
6261 public void onPageFinished(WebView view, String url) {
6262 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6263 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6264 CookieManager.getInstance().flush();
6267 // Update the Refresh menu item if the options menu has been created.
6268 if (optionsMenu != null) {
6269 // Reset the Refresh title.
6270 optionsRefreshMenuItem.setTitle(R.string.refresh);
6272 // Get the app bar and theme preferences.
6273 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6275 // If the icon is displayed in the app bar, reset it according to the theme.
6276 if (displayAdditionalAppBarIcons) {
6277 // Get the current theme status.
6278 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6280 // Set the icon according to the theme.
6281 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6282 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6284 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6289 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6290 if (incognitoModeEnabled) {
6291 // Clear the cache. `true` includes disk files.
6292 nestedScrollWebView.clearCache(true);
6294 // Clear the back/forward history.
6295 nestedScrollWebView.clearHistory();
6297 // Manually delete cache folders.
6299 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6300 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6301 String privateDataDirectoryString = getApplicationInfo().dataDir;
6303 // Delete the main cache directory.
6304 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6306 // Delete the secondary `Service Worker` cache directory.
6307 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6308 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6309 } catch (IOException exception) {
6310 // Do nothing if an error is thrown.
6313 // Clear the logcat.
6315 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6316 Runtime.getRuntime().exec("logcat -b all -c");
6317 } catch (IOException exception) {
6322 // Get the current page position.
6323 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6325 // 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.
6326 String currentUrl = nestedScrollWebView.getUrl();
6328 // Get the current tab.
6329 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6331 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6332 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6333 // Probably some sort of race condition when Privacy Browser is being resumed.
6334 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6335 // Check to see if the URL is `about:blank`.
6336 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6337 // Display the hint in the URL edit text.
6338 urlEditText.setText("");
6340 // Request focus for the URL text box.
6341 urlEditText.requestFocus();
6343 // Display the keyboard.
6344 inputMethodManager.showSoftInput(urlEditText, 0);
6346 // Apply the domain settings. This clears any settings from the previous domain.
6347 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6349 // Only populate the title text view if the tab has been fully created.
6351 // Get the custom view from the tab.
6352 View tabView = tab.getCustomView();
6354 // Remove the incorrect warning below that the current tab view might be null.
6355 assert tabView != null;
6357 // Get the title text view from the tab.
6358 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6360 // Set the title as the tab text.
6361 tabTitleTextView.setText(R.string.new_tab);
6363 } else { // The WebView has loaded a webpage.
6364 // Update the URL edit text if it is not currently being edited.
6365 if (!urlEditText.hasFocus()) {
6366 // 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.
6367 String sanitizedUrl = sanitizeUrl(currentUrl);
6369 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6370 urlEditText.setText(sanitizedUrl);
6372 // Apply text highlighting to the URL.
6376 // Only populate the title text view if the tab has been fully created.
6378 // Get the custom view from the tab.
6379 View tabView = tab.getCustomView();
6381 // Remove the incorrect warning below that the current tab view might be null.
6382 assert tabView != null;
6384 // Get the title text view from the tab.
6385 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6387 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6388 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6394 // Handle SSL Certificate errors.
6396 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6397 // Get the current website SSL certificate.
6398 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6400 // Extract the individual pieces of information from the current website SSL certificate.
6401 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6402 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6403 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6404 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6405 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6406 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6407 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6408 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6410 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6411 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6412 // Get the pinned SSL certificate.
6413 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6415 // Extract the arrays from the array list.
6416 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6417 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6419 // Check if the current SSL certificate matches the pinned certificate.
6420 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6421 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6422 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6423 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6425 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6428 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6429 // Store the SSL error handler.
6430 nestedScrollWebView.setSslErrorHandler(handler);
6432 // Instantiate an SSL certificate error alert dialog.
6433 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6435 // Show the SSL certificate error dialog.
6436 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6441 // Check to see if the state is being restored.
6442 if (restoringState) { // The state is being restored.
6443 // Resume the nested scroll WebView JavaScript timers.
6444 nestedScrollWebView.resumeTimers();
6445 } else if (pageNumber == 0) { // The first page is being loaded.
6446 // Set this nested scroll WebView as the current WebView.
6447 currentWebView = nestedScrollWebView;
6449 // Initialize the URL to load string.
6450 String urlToLoadString;
6452 // Get the intent that started the app.
6453 Intent launchingIntent = getIntent();
6455 // Reset the intent. This prevents a duplicate tab from being created on restart.
6456 setIntent(new Intent());
6458 // Get the information from the intent.
6459 String launchingIntentAction = launchingIntent.getAction();
6460 Uri launchingIntentUriData = launchingIntent.getData();
6461 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6463 // Parse the launching intent URL.
6464 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6465 // Create an encoded URL string.
6466 String encodedUrlString;
6468 // Sanitize the search input and convert it to a search.
6470 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6471 } catch (UnsupportedEncodingException exception) {
6472 encodedUrlString = "";
6475 // Store the web search as the URL to load.
6476 urlToLoadString = searchURL + encodedUrlString;
6477 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6478 // Store the URI as a URL.
6479 urlToLoadString = launchingIntentUriData.toString();
6480 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6482 urlToLoadString = launchingIntentStringExtra;
6483 } else if (!url.equals("")) { // The activity has been restarted.
6484 // Load the saved URL.
6485 urlToLoadString = url;
6486 } else { // The is no URL in the intent.
6487 // Store the homepage to be loaded.
6488 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6491 // Load the website if not waiting for the proxy.
6492 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6493 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6494 } else { // Load the URL.
6495 loadUrl(nestedScrollWebView, urlToLoadString);
6498 // Reset the intent. This prevents a duplicate tab from being created on a subsequent restart if loading an link from a new intent on restart.
6499 // For example, this prevents a duplicate tab if a link is loaded from the Guide after changing the theme in the guide and then changing the theme again in the main activity.
6500 setIntent(new Intent());
6501 } else { // This is not the first tab.
6503 loadUrl(nestedScrollWebView, url);
6505 // Set the focus and display the keyboard if the URL is blank.
6506 if (url.equals("")) {
6507 // Request focus for the URL text box.
6508 urlEditText.requestFocus();
6510 // Create a display keyboard handler.
6511 Handler displayKeyboardHandler = new Handler();
6513 // Create a display keyboard runnable.
6514 Runnable displayKeyboardRunnable = () -> {
6515 // Display the keyboard.
6516 inputMethodManager.showSoftInput(urlEditText, 0);
6519 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6520 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);