2 * Copyright © 2015-2021 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 FrameLayout rootFrameLayout;
325 private DrawerLayout drawerLayout;
326 private RelativeLayout mainContentRelativeLayout;
327 private AppBarLayout appBarLayout;
328 private Toolbar toolbar;
329 private RelativeLayout urlRelativeLayout;
330 private EditText urlEditText;
331 private ActionBar actionBar;
332 private LinearLayout findOnPageLinearLayout;
333 private LinearLayout tabsLinearLayout;
334 private TabLayout tabLayout;
335 private SwipeRefreshLayout swipeRefreshLayout;
336 private ViewPager webViewPager;
337 private FrameLayout fullScreenVideoFrameLayout;
339 // Declare the class menus.
340 private Menu optionsMenu;
342 // Declare the class menu items.
343 private MenuItem navigationBackMenuItem;
344 private MenuItem navigationForwardMenuItem;
345 private MenuItem navigationHistoryMenuItem;
346 private MenuItem navigationRequestsMenuItem;
347 private MenuItem optionsPrivacyMenuItem;
348 private MenuItem optionsRefreshMenuItem;
349 private MenuItem optionsFirstPartyCookiesMenuItem;
350 private MenuItem optionsThirdPartyCookiesMenuItem;
351 private MenuItem optionsDomStorageMenuItem;
352 private MenuItem optionsSaveFormDataMenuItem;
353 private MenuItem optionsClearDataMenuItem;
354 private MenuItem optionsClearCookiesMenuItem;
355 private MenuItem optionsClearDomStorageMenuItem;
356 private MenuItem optionsClearFormDataMenuItem;
357 private MenuItem optionsBlocklistsMenuItem;
358 private MenuItem optionsEasyListMenuItem;
359 private MenuItem optionsEasyPrivacyMenuItem;
360 private MenuItem optionsFanboysAnnoyanceListMenuItem;
361 private MenuItem optionsFanboysSocialBlockingListMenuItem;
362 private MenuItem optionsUltraListMenuItem;
363 private MenuItem optionsUltraPrivacyMenuItem;
364 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
365 private MenuItem optionsProxyMenuItem;
366 private MenuItem optionsProxyNoneMenuItem;
367 private MenuItem optionsProxyTorMenuItem;
368 private MenuItem optionsProxyI2pMenuItem;
369 private MenuItem optionsProxyCustomMenuItem;
370 private MenuItem optionsUserAgentMenuItem;
371 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
372 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
373 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
374 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
375 private MenuItem optionsUserAgentSafariOnIosMenuItem;
376 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
377 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
378 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
379 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
380 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
381 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
382 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
383 private MenuItem optionsUserAgentCustomMenuItem;
384 private MenuItem optionsSwipeToRefreshMenuItem;
385 private MenuItem optionsWideViewportMenuItem;
386 private MenuItem optionsDisplayImagesMenuItem;
387 private MenuItem optionsDarkWebViewMenuItem;
388 private MenuItem optionsFontSizeMenuItem;
389 private MenuItem optionsAddOrEditDomainMenuItem;
392 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
393 @SuppressLint("ClickableViewAccessibility")
394 protected void onCreate(Bundle savedInstanceState) {
395 // Run the default commands.
396 super.onCreate(savedInstanceState);
398 // Check to see if the activity has been restarted.
399 if (savedInstanceState != null) {
400 // Store the saved instance state variables.
401 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
402 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
403 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
404 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
407 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
408 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
410 // Get a handle for the shared preferences.
411 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
413 // Get the screenshot preference.
414 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
415 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
417 // Get the theme entry values string array.
418 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
420 // 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.
421 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
422 // Apply the light theme.
423 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
424 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
425 // Apply the dark theme.
426 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
427 } else { // The system default theme is selected.
428 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
429 // Follow the system default theme.
430 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
431 } else { // The system default theme is not supported.
432 // Follow the battery saver mode.
433 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
437 // Disable screenshots if not allowed.
438 if (!allowScreenshots) {
439 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
442 // 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.
443 if (Build.VERSION.SDK_INT >= 21) {
444 WebView.enableSlowWholeDocumentDraw();
448 setTheme(R.style.PrivacyBrowser);
450 // Set the content view.
451 setContentView(R.layout.main_framelayout);
453 // Get handles for the views.
454 rootFrameLayout = findViewById(R.id.root_framelayout);
455 drawerLayout = findViewById(R.id.drawerlayout);
456 mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
457 appBarLayout = findViewById(R.id.appbar_layout);
458 toolbar = findViewById(R.id.toolbar);
459 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
460 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
461 tabLayout = findViewById(R.id.tablayout);
462 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
463 webViewPager = findViewById(R.id.webviewpager);
464 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
466 // Get a handle for the navigation view.
467 NavigationView navigationView = findViewById(R.id.navigationview);
469 // Get a handle for the navigation menu.
470 Menu navigationMenu = navigationView.getMenu();
472 // Get handles for the navigation menu items.
473 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
474 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
475 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
476 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
478 // Listen for touches on the navigation menu.
479 navigationView.setNavigationItemSelectedListener(this);
481 // Get a handle for the app compat delegate.
482 AppCompatDelegate appCompatDelegate = getDelegate();
484 // Set the support action bar.
485 appCompatDelegate.setSupportActionBar(toolbar);
487 // Get a handle for the action bar.
488 actionBar = appCompatDelegate.getSupportActionBar();
490 // Remove the incorrect lint warning below that the action bar might be null.
491 assert actionBar != null;
493 // Add the custom layout, which shows the URL text bar.
494 actionBar.setCustomView(R.layout.url_app_bar);
495 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
497 // Get handles for the views in the URL app bar.
498 urlRelativeLayout = findViewById(R.id.url_relativelayout);
499 urlEditText = findViewById(R.id.url_edittext);
501 // Create the hamburger icon at the start of the AppBar.
502 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
504 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
505 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
507 // Initialize the web view pager adapter.
508 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
510 // Set the pager adapter on the web view pager.
511 webViewPager.setAdapter(webViewPagerAdapter);
513 // Store up to 100 tabs in memory.
514 webViewPager.setOffscreenPageLimit(100);
516 // Initialize the app.
519 // Apply the app settings from the shared preferences.
522 // Populate the blocklists.
523 populateBlocklists = new PopulateBlocklists(this, this).execute();
527 protected void onNewIntent(Intent intent) {
528 // Run the default commands.
529 super.onNewIntent(intent);
531 // Replace the intent that started the app with this one.
534 // Check to see if the app is being restarted from a saved state.
535 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
536 // Get the information from the intent.
537 String intentAction = intent.getAction();
538 Uri intentUriData = intent.getData();
539 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
541 // Determine if this is a web search.
542 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
544 // 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.
545 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
546 // Get the shared preferences.
547 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
549 // Create a URL string.
552 // If the intent action is a web search, perform the search.
553 if (isWebSearch) { // The intent is a web search.
554 // Create an encoded URL string.
555 String encodedUrlString;
557 // Sanitize the search input and convert it to a search.
559 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
560 } catch (UnsupportedEncodingException exception) {
561 encodedUrlString = "";
564 // Add the base search URL.
565 url = searchURL + encodedUrlString;
566 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
567 // Set the intent data as the URL.
568 url = intentUriData.toString();
569 } else { // The intent contains a string, which might be a URL.
570 // Set the intent string as the URL.
571 url = intentStringExtra;
574 // Add a new tab if specified in the preferences.
575 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
576 // Set the loading new intent flag.
577 loadingNewIntent = true;
580 addNewTab(url, true);
581 } else { // Load the URL in the current tab.
583 loadUrl(currentWebView, url);
586 // Close the navigation drawer if it is open.
587 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
588 drawerLayout.closeDrawer(GravityCompat.START);
591 // Close the bookmarks drawer if it is open.
592 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
593 drawerLayout.closeDrawer(GravityCompat.END);
600 public void onRestart() {
601 // Run the default commands.
604 // Apply the app settings if returning from the Settings activity.
605 if (reapplyAppSettingsOnRestart) {
606 // Reset the reapply app settings on restart tracker.
607 reapplyAppSettingsOnRestart = false;
609 // Apply the app settings.
613 // Apply the domain settings if returning from the settings or domains activity.
614 if (reapplyDomainSettingsOnRestart) {
615 // Reset the reapply domain settings on restart tracker.
616 reapplyDomainSettingsOnRestart = false;
618 // Reapply the domain settings for each tab.
619 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
620 // Get the WebView tab fragment.
621 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
623 // Get the fragment view.
624 View fragmentView = webViewTabFragment.getView();
626 // Only reload the WebViews if they exist.
627 if (fragmentView != null) {
628 // Get the nested scroll WebView from the tab fragment.
629 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
631 // Reset the current domain name so the domain settings will be reapplied.
632 nestedScrollWebView.resetCurrentDomainName();
634 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
635 if (nestedScrollWebView.getUrl() != null) {
636 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
642 // Update the bookmarks drawer if returning from the Bookmarks activity.
643 if (restartFromBookmarksActivity) {
644 // Close the bookmarks drawer.
645 drawerLayout.closeDrawer(GravityCompat.END);
647 // Reload the bookmarks drawer.
648 loadBookmarksFolder();
650 // Reset `restartFromBookmarksActivity`.
651 restartFromBookmarksActivity = false;
654 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
655 updatePrivacyIcons(true);
658 // `onStart()` runs after `onCreate()` or `onRestart()`. This is used instead of `onResume()` so the commands aren't called every time the screen is partially hidden.
660 public void onStart() {
661 // Run the default commands.
664 // Resume any WebViews.
665 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
666 // Get the WebView tab fragment.
667 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
669 // Get the fragment view.
670 View fragmentView = webViewTabFragment.getView();
672 // Only resume the WebViews if they exist (they won't when the app is first created).
673 if (fragmentView != null) {
674 // Get the nested scroll WebView from the tab fragment.
675 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
677 // Resume the nested scroll WebView.
678 nestedScrollWebView.onResume();
682 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
683 if (currentWebView != null) {
684 currentWebView.resumeTimers();
687 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
688 if (!proxyMode.equals(ProxyHelper.NONE)) {
692 // Reapply any system UI flags and the ad in the free flavor.
693 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
694 /* Hide the system bars.
695 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
696 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
697 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
698 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
700 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
701 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
702 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
703 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
704 View adView = findViewById(R.id.adview);
707 AdHelper.resumeAd(adView);
711 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
713 public void onStop() {
714 // Run the default commands.
717 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
718 // Get the WebView tab fragment.
719 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
721 // Get the fragment view.
722 View fragmentView = webViewTabFragment.getView();
724 // Only pause the WebViews if they exist (they won't when the app is first created).
725 if (fragmentView != null) {
726 // Get the nested scroll WebView from the tab fragment.
727 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
729 // Pause the nested scroll WebView.
730 nestedScrollWebView.onPause();
734 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
735 if (currentWebView != null) {
736 currentWebView.pauseTimers();
739 // Pause the ad or it will continue to consume resources in the background on the free flavor.
740 if (BuildConfig.FLAVOR.contentEquals("free")) {
741 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
742 View adView = findViewById(R.id.adview);
745 AdHelper.pauseAd(adView);
750 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
751 // Run the default commands.
752 super.onSaveInstanceState(savedInstanceState);
754 // Create the saved state array lists.
755 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
756 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
758 // Get the URLs from each tab.
759 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
760 // Get the WebView tab fragment.
761 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
763 // Get the fragment view.
764 View fragmentView = webViewTabFragment.getView();
766 if (fragmentView != null) {
767 // Get the nested scroll WebView from the tab fragment.
768 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
770 // Create saved state bundle.
771 Bundle savedStateBundle = new Bundle();
773 // Get the current states.
774 nestedScrollWebView.saveState(savedStateBundle);
775 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
777 // Store the saved states in the array lists.
778 savedStateArrayList.add(savedStateBundle);
779 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
783 // Get the current tab position.
784 int currentTabPosition = tabLayout.getSelectedTabPosition();
786 // Store the saved states in the bundle.
787 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
788 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
789 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
790 savedInstanceState.putString(PROXY_MODE, proxyMode);
794 public void onDestroy() {
795 // Unregister the orbot status broadcast receiver if it exists.
796 if (orbotStatusBroadcastReceiver != null) {
797 this.unregisterReceiver(orbotStatusBroadcastReceiver);
800 // Close the bookmarks cursor if it exists.
801 if (bookmarksCursor != null) {
802 bookmarksCursor.close();
805 // Close the bookmarks database if it exists.
806 if (bookmarksDatabaseHelper != null) {
807 bookmarksDatabaseHelper.close();
810 // Stop populating the blocklists if the AsyncTask is running in the background.
811 if (populateBlocklists != null) {
812 populateBlocklists.cancel(true);
815 // Run the default commands.
820 public boolean onCreateOptionsMenu(Menu menu) {
821 // Inflate the menu. This adds items to the action bar if it is present.
822 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
824 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
827 // Get handles for the class menu items.
828 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
829 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
830 optionsFirstPartyCookiesMenuItem = menu.findItem(R.id.first_party_cookies);
831 optionsThirdPartyCookiesMenuItem = menu.findItem(R.id.third_party_cookies);
832 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
833 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
834 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
835 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
836 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
837 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
838 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
839 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
840 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
841 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
842 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
843 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
844 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
845 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
846 optionsProxyMenuItem = menu.findItem(R.id.proxy);
847 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
848 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
849 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
850 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
851 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
852 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
853 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
854 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
855 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
856 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
857 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
858 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
859 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
860 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
861 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
862 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
863 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
864 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
865 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
866 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
867 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
868 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
869 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
870 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
872 // Get handles for the method menu items.
873 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
874 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
876 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
877 updatePrivacyIcons(false);
879 // Only display third-party cookies if API >= 21
880 optionsThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
882 // Only display the form data menu items if the API < 26.
883 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
884 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
886 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
887 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
889 // Only display the dark WebView menu item if API >= 21.
890 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
892 // Only show Ad Consent if this is the free flavor.
893 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
895 // Get the shared preferences.
896 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
898 // Get the dark theme and app bar preferences.
899 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
901 // 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.
902 if (displayAdditionalAppBarIcons) {
903 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
904 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
905 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
906 } else { //Do not display the additional icons.
907 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
908 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
909 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
912 // Replace Refresh with Stop if a URL is already loading.
913 if (currentWebView != null && currentWebView.getProgress() != 100) {
915 optionsRefreshMenuItem.setTitle(R.string.stop);
917 // Set the icon if it is displayed in the app bar.
918 if (displayAdditionalAppBarIcons) {
919 // Get the current theme status.
920 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
922 // Set the icon according to the current theme status.
923 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
924 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
926 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
936 public boolean onPrepareOptionsMenu(Menu menu) {
937 // Get a handle for the cookie manager.
938 CookieManager cookieManager = CookieManager.getInstance();
940 // Initialize the current user agent string and the font size.
941 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
944 // 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.
945 if (currentWebView != null) {
946 // Set the add or edit domain text.
947 if (currentWebView.getDomainSettingsApplied()) {
948 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
950 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
953 // Get the current user agent from the WebView.
954 currentUserAgent = currentWebView.getSettings().getUserAgentString();
956 // Get the current font size from the
957 fontSize = currentWebView.getSettings().getTextZoom();
959 // Set the status of the menu item checkboxes.
960 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
961 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
962 optionsEasyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
963 optionsEasyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
964 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
965 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
966 optionsUltraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
967 optionsUltraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
968 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
969 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
970 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
971 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
973 // Initialize the display names for the blocklists with the number of blocked requests.
974 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
975 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
976 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
977 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
978 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
979 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
980 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
981 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
983 // Only modify third-party cookies if the API >= 21.
984 if (Build.VERSION.SDK_INT >= 21) {
985 // Set the status of the third-party cookies checkbox.
986 optionsThirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
988 // Enable third-party cookies if first-party cookies are enabled.
989 optionsThirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
992 // Enable DOM Storage if JavaScript is enabled.
993 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
995 // Set the checkbox status for dark WebView if the WebView supports it.
996 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
997 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1001 // Set the checked status of the first party cookies menu item.
1002 optionsFirstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1004 // Enable Clear Cookies if there are any.
1005 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1007 // 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`.
1008 String privateDataDirectoryString = getApplicationInfo().dataDir;
1010 // Get a count of the number of files in the Local Storage directory.
1011 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1012 int localStorageDirectoryNumberOfFiles = 0;
1013 if (localStorageDirectory.exists()) {
1014 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1015 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1018 // Get a count of the number of files in the IndexedDB directory.
1019 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1020 int indexedDBDirectoryNumberOfFiles = 0;
1021 if (indexedDBDirectory.exists()) {
1022 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1023 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1026 // Enable Clear DOM Storage if there is any.
1027 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1029 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1030 if (Build.VERSION.SDK_INT < 26) {
1031 // Get the WebView database.
1032 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1034 // Enable the clear form data menu item if there is anything to clear.
1035 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1038 // Enable Clear Data if any of the submenu items are enabled.
1039 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1041 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1042 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1044 // Set the proxy title and check the applied proxy.
1045 switch (proxyMode) {
1046 case ProxyHelper.NONE:
1047 // Set the proxy title.
1048 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1050 // Check the proxy None radio button.
1051 optionsProxyNoneMenuItem.setChecked(true);
1054 case ProxyHelper.TOR:
1055 // Set the proxy title.
1056 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1058 // Check the proxy Tor radio button.
1059 optionsProxyTorMenuItem.setChecked(true);
1062 case ProxyHelper.I2P:
1063 // Set the proxy title.
1064 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1066 // Check the proxy I2P radio button.
1067 optionsProxyI2pMenuItem.setChecked(true);
1070 case ProxyHelper.CUSTOM:
1071 // Set the proxy title.
1072 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1074 // Check the proxy Custom radio button.
1075 optionsProxyCustomMenuItem.setChecked(true);
1079 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1080 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1081 // Update the user agent menu item title.
1082 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1084 // Select the Privacy Browser radio box.
1085 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1086 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1087 // Update the user agent menu item title.
1088 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1090 // Select the WebView Default radio box.
1091 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1092 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1093 // Update the user agent menu item title.
1094 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1096 // Select the Firefox on Android radio box.
1097 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1098 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1099 // Update the user agent menu item title.
1100 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1102 // Select the Chrome on Android radio box.
1103 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1104 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1105 // Update the user agent menu item title.
1106 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1108 // Select the Safari on iOS radio box.
1109 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1110 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1111 // Update the user agent menu item title.
1112 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1114 // Select the Firefox on Linux radio box.
1115 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1116 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1117 // Update the user agent menu item title.
1118 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1120 // Select the Chromium on Linux radio box.
1121 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1122 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1123 // Update the user agent menu item title.
1124 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1126 // Select the Firefox on Windows radio box.
1127 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1128 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1129 // Update the user agent menu item title.
1130 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1132 // Select the Chrome on Windows radio box.
1133 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1134 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1135 // Update the user agent menu item title.
1136 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1138 // Select the Edge on Windows radio box.
1139 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1140 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1141 // Update the user agent menu item title.
1142 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1144 // Select the Internet on Windows radio box.
1145 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1146 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1147 // Update the user agent menu item title.
1148 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1150 // Select the Safari on macOS radio box.
1151 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1152 } else { // Custom user agent.
1153 // Update the user agent menu item title.
1154 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1156 // Select the Custom radio box.
1157 optionsUserAgentCustomMenuItem.setChecked(true);
1160 // Set the font size title.
1161 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1163 // Run all the other default commands.
1164 super.onPrepareOptionsMenu(menu);
1166 // Display the menu.
1171 public boolean onOptionsItemSelected(MenuItem menuItem) {
1172 // Get a handle for the shared preferences.
1173 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1175 // Get a handle for the cookie manager.
1176 CookieManager cookieManager = CookieManager.getInstance();
1178 // Get the selected menu item ID.
1179 int menuItemId = menuItem.getItemId();
1181 // Run the commands that correlate to the selected menu item.
1182 if (menuItemId == R.id.javascript) { // JavaScript.
1183 // Toggle the JavaScript status.
1184 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1186 // Update the privacy icon.
1187 updatePrivacyIcons(true);
1189 // Display a `Snackbar`.
1190 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1191 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1192 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1193 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1194 } else { // Privacy mode.
1195 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1198 // Reload the current WebView.
1199 currentWebView.reload();
1201 // Consume the event.
1203 } else if (menuItemId == R.id.refresh) { // Refresh.
1204 // Run the command that correlates to the current status of the menu item.
1205 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1206 // Reload the current WebView.
1207 currentWebView.reload();
1208 } else { // The stop button was pushed.
1209 // Stop the loading of the WebView.
1210 currentWebView.stopLoading();
1213 // Consume the event.
1215 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1216 // Open the bookmarks drawer.
1217 drawerLayout.openDrawer(GravityCompat.END);
1219 // Consume the event.
1221 } else if (menuItemId == R.id.first_party_cookies) { // First-party cookies.
1222 // Switch the first-party cookie status.
1223 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1225 // Store the first-party cookie status.
1226 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1228 // Update the menu checkbox.
1229 menuItem.setChecked(cookieManager.acceptCookie());
1231 // Update the privacy icon.
1232 updatePrivacyIcons(true);
1234 // Display a snackbar.
1235 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1236 Snackbar.make(webViewPager, R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1237 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1238 Snackbar.make(webViewPager, R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1239 } else { // Privacy mode.
1240 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1243 // Reload the current WebView.
1244 currentWebView.reload();
1246 // Consume the event.
1248 } else if (menuItemId == R.id.third_party_cookies) { // Third-party cookies.
1249 // Only act if the API >= 21. Otherwise, there are no third-party cookie controls.
1250 if (Build.VERSION.SDK_INT >= 21) {
1251 // Toggle the status of thirdPartyCookiesEnabled.
1252 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1254 // Update the menu checkbox.
1255 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1257 // Display a snackbar.
1258 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1259 Snackbar.make(webViewPager, R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1261 Snackbar.make(webViewPager, R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1264 // Reload the current WebView.
1265 currentWebView.reload();
1268 // Consume the event.
1270 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1271 // Toggle the status of domStorageEnabled.
1272 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1274 // Update the menu checkbox.
1275 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1277 // Update the privacy icon.
1278 updatePrivacyIcons(true);
1280 // Display a snackbar.
1281 if (currentWebView.getSettings().getDomStorageEnabled()) {
1282 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1284 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1287 // Reload the current WebView.
1288 currentWebView.reload();
1290 // Consume the event.
1292 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1293 // Switch the status of saveFormDataEnabled.
1294 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1296 // Update the menu checkbox.
1297 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1299 // Display a snackbar.
1300 if (currentWebView.getSettings().getSaveFormData()) {
1301 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1303 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1306 // Update the privacy icon.
1307 updatePrivacyIcons(true);
1309 // Reload the current WebView.
1310 currentWebView.reload();
1312 // Consume the event.
1314 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1315 // Create a snackbar.
1316 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1317 .setAction(R.string.undo, v -> {
1318 // Do nothing because everything will be handled by `onDismissed()` below.
1320 .addCallback(new Snackbar.Callback() {
1322 public void onDismissed(Snackbar snackbar, int event) {
1323 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1324 // Delete the cookies, which command varies by SDK.
1325 if (Build.VERSION.SDK_INT < 21) {
1326 cookieManager.removeAllCookie();
1328 cookieManager.removeAllCookies(null);
1335 // Consume the event.
1337 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1338 // Create a snackbar.
1339 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1340 .setAction(R.string.undo, v -> {
1341 // Do nothing because everything will be handled by `onDismissed()` below.
1343 .addCallback(new Snackbar.Callback() {
1345 public void onDismissed(Snackbar snackbar, int event) {
1346 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1347 // Delete the DOM Storage.
1348 WebStorage webStorage = WebStorage.getInstance();
1349 webStorage.deleteAllData();
1351 // Initialize a handler to manually delete the DOM storage files and directories.
1352 Handler deleteDomStorageHandler = new Handler();
1354 // Setup a runnable to manually delete the DOM storage files and directories.
1355 Runnable deleteDomStorageRunnable = () -> {
1357 // Get a handle for the runtime.
1358 Runtime runtime = Runtime.getRuntime();
1360 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1361 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1362 String privateDataDirectoryString = getApplicationInfo().dataDir;
1364 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1365 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1367 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1368 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1369 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1370 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1371 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1373 // Wait for the processes to finish.
1374 deleteLocalStorageProcess.waitFor();
1375 deleteIndexProcess.waitFor();
1376 deleteQuotaManagerProcess.waitFor();
1377 deleteQuotaManagerJournalProcess.waitFor();
1378 deleteDatabasesProcess.waitFor();
1379 } catch (Exception exception) {
1380 // Do nothing if an error is thrown.
1384 // Manually delete the DOM storage files after 200 milliseconds.
1385 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1391 // Consume the event.
1393 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1394 // Create a snackbar.
1395 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1396 .setAction(R.string.undo, v -> {
1397 // Do nothing because everything will be handled by `onDismissed()` below.
1399 .addCallback(new Snackbar.Callback() {
1401 public void onDismissed(Snackbar snackbar, int event) {
1402 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1403 // Get a handle for the webView database.
1404 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1406 // Delete the form data.
1407 webViewDatabase.clearFormData();
1413 // Consume the event.
1415 } else if (menuItemId == R.id.easylist) { // EasyList.
1416 // Toggle the EasyList status.
1417 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1419 // Update the menu checkbox.
1420 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1422 // Reload the current WebView.
1423 currentWebView.reload();
1425 // Consume the event.
1427 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1428 // Toggle the EasyPrivacy status.
1429 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1431 // Update the menu checkbox.
1432 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1434 // Reload the current WebView.
1435 currentWebView.reload();
1437 // Consume the event.
1439 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1440 // Toggle Fanboy's Annoyance List status.
1441 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1443 // Update the menu checkbox.
1444 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1446 // Update the staus of Fanboy's Social Blocking List.
1447 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1449 // Reload the current WebView.
1450 currentWebView.reload();
1452 // Consume the event.
1454 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1455 // Toggle Fanboy's Social Blocking List status.
1456 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1458 // Update the menu checkbox.
1459 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1461 // Reload the current WebView.
1462 currentWebView.reload();
1464 // Consume the event.
1466 } else if (menuItemId == R.id.ultralist) { // UltraList.
1467 // Toggle the UltraList status.
1468 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1470 // Update the menu checkbox.
1471 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1473 // Reload the current WebView.
1474 currentWebView.reload();
1476 // Consume the event.
1478 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1479 // Toggle the UltraPrivacy status.
1480 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1482 // Update the menu checkbox.
1483 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1485 // Reload the current WebView.
1486 currentWebView.reload();
1488 // Consume the event.
1490 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1491 //Toggle the third-party requests blocker status.
1492 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1494 // Update the menu checkbox.
1495 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1497 // Reload the current WebView.
1498 currentWebView.reload();
1500 // Consume the event.
1502 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1503 // Update the proxy mode.
1504 proxyMode = ProxyHelper.NONE;
1506 // Apply the proxy mode.
1509 // Consume the event.
1511 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1512 // Update the proxy mode.
1513 proxyMode = ProxyHelper.TOR;
1515 // Apply the proxy mode.
1518 // Consume the event.
1520 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1521 // Update the proxy mode.
1522 proxyMode = ProxyHelper.I2P;
1524 // Apply the proxy mode.
1527 // Consume the event.
1529 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1530 // Update the proxy mode.
1531 proxyMode = ProxyHelper.CUSTOM;
1533 // Apply the proxy mode.
1536 // Consume the event.
1538 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1539 // Update the user agent.
1540 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1542 // Reload the current WebView.
1543 currentWebView.reload();
1545 // Consume the event.
1547 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1548 // Update the user agent.
1549 currentWebView.getSettings().setUserAgentString("");
1551 // Reload the current WebView.
1552 currentWebView.reload();
1554 // Consume the event.
1556 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1557 // Update the user agent.
1558 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1560 // Reload the current WebView.
1561 currentWebView.reload();
1563 // Consume the event.
1565 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1566 // Update the user agent.
1567 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1569 // Reload the current WebView.
1570 currentWebView.reload();
1572 // Consume the event.
1574 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1575 // Update the user agent.
1576 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1578 // Reload the current WebView.
1579 currentWebView.reload();
1581 // Consume the event.
1583 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1584 // Update the user agent.
1585 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1587 // Reload the current WebView.
1588 currentWebView.reload();
1590 // Consume the event.
1592 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1593 // Update the user agent.
1594 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1596 // Reload the current WebView.
1597 currentWebView.reload();
1599 // Consume the event.
1601 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1602 // Update the user agent.
1603 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1605 // Reload the current WebView.
1606 currentWebView.reload();
1608 // Consume the event.
1610 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1611 // Update the user agent.
1612 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1614 // Reload the current WebView.
1615 currentWebView.reload();
1617 // Consume the event.
1619 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1620 // Update the user agent.
1621 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1623 // Reload the current WebView.
1624 currentWebView.reload();
1626 // Consume the event.
1628 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1629 // Update the user agent.
1630 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1632 // Reload the current WebView.
1633 currentWebView.reload();
1635 // Consume the event.
1637 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1638 // Update the user agent.
1639 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1641 // Reload the current WebView.
1642 currentWebView.reload();
1644 // Consume the event.
1646 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1647 // Update the user agent.
1648 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1650 // Reload the current WebView.
1651 currentWebView.reload();
1653 // Consume the event.
1655 } else if (menuItemId == R.id.font_size) { // Font size.
1656 // Instantiate the font size dialog.
1657 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1659 // Show the font size dialog.
1660 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1662 // Consume the event.
1664 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1665 // Toggle the stored status of swipe to refresh.
1666 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1668 // Update the swipe refresh layout.
1669 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1670 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1671 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1672 } else { // Swipe to refresh is disabled.
1673 // Disable the swipe refresh layout.
1674 swipeRefreshLayout.setEnabled(false);
1677 // Consume the event.
1679 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1680 // Toggle the viewport.
1681 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1683 // Consume the event.
1685 } else if (menuItemId == R.id.display_images) { // Display images.
1686 // Toggle the displaying of images.
1687 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1688 // Disable loading of images.
1689 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1691 // Reload the website to remove existing images.
1692 currentWebView.reload();
1693 } else { // Images are not currently loaded automatically.
1694 // Enable loading of images. Missing images will be loaded without the need for a reload.
1695 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1698 // Consume the event.
1700 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1701 // Check to see if dark WebView is supported by this WebView.
1702 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1703 // Toggle the dark WebView setting.
1704 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1705 // Turn off dark WebView.
1706 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1707 } else { // Dark WebView is currently disabled.
1708 // Turn on dark WebView.
1709 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1713 // Consume the event.
1715 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1716 // Get a handle for the views.
1717 Toolbar toolbar = findViewById(R.id.toolbar);
1718 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1719 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1721 // Set the minimum height of the find on page linear layout to match the toolbar.
1722 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1724 // Hide the toolbar.
1725 toolbar.setVisibility(View.GONE);
1727 // Show the find on page linear layout.
1728 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1730 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1731 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1732 findOnPageEditText.postDelayed(() -> {
1733 // Set the focus on the find on page edit text.
1734 findOnPageEditText.requestFocus();
1736 // Get a handle for the input method manager.
1737 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1739 // Remove the lint warning below that the input method manager might be null.
1740 assert inputMethodManager != null;
1742 // Display the keyboard. `0` sets no input flags.
1743 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1746 // Consume the event.
1748 } else if (menuItemId == R.id.print) { // Print.
1749 // Get a print manager instance.
1750 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1752 // Remove the lint error below that print manager might be null.
1753 assert printManager != null;
1755 // Create a print document adapter from the current WebView.
1756 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1758 // Print the document.
1759 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1761 // Consume the event.
1763 } else if (menuItemId == R.id.save_url) { // Save URL.
1764 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1765 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1766 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1768 // Consume the event.
1770 } else if (menuItemId == R.id.save_archive) { // Save archive.
1771 // Instantiate the save dialog.
1772 DialogFragment saveArchiveFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_ARCHIVE, null, null, getString(R.string.webpage_mht), null,
1775 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1776 saveArchiveFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1778 // Consume the event.
1780 } else if (menuItemId == R.id.save_image) { // Save image.
1781 // Instantiate the save dialog.
1782 DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_IMAGE, null, null, getString(R.string.webpage_png), null,
1785 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1786 saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1788 // Consume the event.
1790 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1791 // Instantiate the create home screen shortcut dialog.
1792 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1793 currentWebView.getFavoriteOrDefaultIcon());
1795 // Show the create home screen shortcut dialog.
1796 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1798 // Consume the event.
1800 } else if (menuItemId == R.id.view_source) { // View source.
1801 // Create an intent to launch the view source activity.
1802 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1804 // Add the variables to the intent.
1805 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1806 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1809 startActivity(viewSourceIntent);
1811 // Consume the event.
1813 } else if (menuItemId == R.id.share_url) { // Share URL.
1814 // Setup the share string.
1815 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1817 // Create the share intent.
1818 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1820 // Add the share string to the intent.
1821 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1823 // Set the MIME type.
1824 shareIntent.setType("text/plain");
1826 // Set the intent to open in a new task.
1827 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1830 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1832 // Consume the event.
1834 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1835 // Open the URL with an outside app.
1836 openWithApp(currentWebView.getUrl());
1838 // Consume the event.
1840 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1841 // Open the URL with an outside browser.
1842 openWithBrowser(currentWebView.getUrl());
1844 // Consume the event.
1846 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1847 // Check if domain settings currently exist.
1848 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1849 // Reapply the domain settings on returning to `MainWebViewActivity`.
1850 reapplyDomainSettingsOnRestart = true;
1852 // Create an intent to launch the domains activity.
1853 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1855 // Add the extra information to the intent.
1856 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1857 domainsIntent.putExtra("close_on_back", true);
1858 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1860 // Get the current certificate.
1861 SslCertificate sslCertificate = currentWebView.getCertificate();
1863 // Check to see if the SSL certificate is populated.
1864 if (sslCertificate != null) {
1865 // Extract the certificate to strings.
1866 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1867 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1868 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1869 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1870 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1871 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1872 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1873 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1875 // Add the certificate to the intent.
1876 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1877 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1878 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1879 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1880 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1881 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1882 domainsIntent.putExtra("ssl_start_date", startDateLong);
1883 domainsIntent.putExtra("ssl_end_date", endDateLong);
1886 // Check to see if the current IP addresses have been received.
1887 if (currentWebView.hasCurrentIpAddresses()) {
1888 // Add the current IP addresses to the intent.
1889 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1893 startActivity(domainsIntent);
1894 } else { // Add a new domain.
1895 // Apply the new domain settings on returning to `MainWebViewActivity`.
1896 reapplyDomainSettingsOnRestart = true;
1898 // Get the current domain
1899 Uri currentUri = Uri.parse(currentWebView.getUrl());
1900 String currentDomain = currentUri.getHost();
1902 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1903 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1905 // Create the domain and store the database ID.
1906 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1908 // Create an intent to launch the domains activity.
1909 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1911 // Add the extra information to the intent.
1912 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1913 domainsIntent.putExtra("close_on_back", true);
1914 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1916 // Get the current certificate.
1917 SslCertificate sslCertificate = currentWebView.getCertificate();
1919 // Check to see if the SSL certificate is populated.
1920 if (sslCertificate != null) {
1921 // Extract the certificate to strings.
1922 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1923 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1924 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1925 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1926 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1927 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1928 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1929 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1931 // Add the certificate to the intent.
1932 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1933 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1934 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1935 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1936 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1937 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1938 domainsIntent.putExtra("ssl_start_date", startDateLong);
1939 domainsIntent.putExtra("ssl_end_date", endDateLong);
1942 // Check to see if the current IP addresses have been received.
1943 if (currentWebView.hasCurrentIpAddresses()) {
1944 // Add the current IP addresses to the intent.
1945 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1949 startActivity(domainsIntent);
1952 // Consume the event.
1954 } else if (menuItemId == R.id.ad_consent) { // Ad consent.
1955 // Instantiate the ad consent dialog.
1956 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1958 // Display the ad consent dialog.
1959 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1961 // Consume the event.
1963 } else { // There is no match with the options menu. Pass the event up to the parent method.
1964 // Don't consume the event.
1965 return super.onOptionsItemSelected(menuItem);
1969 // removeAllCookies is deprecated, but it is required for API < 21.
1971 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1972 // Get a handle for the shared preferences.
1973 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1975 // Get the menu item ID.
1976 int menuItemId = menuItem.getItemId();
1978 // Run the commands that correspond to the selected menu item.
1979 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
1980 // Clear and exit Privacy Browser.
1982 } else if (menuItemId == R.id.home) { // Home.
1983 // Load the homepage.
1984 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1985 } else if (menuItemId == R.id.back) { // Back.
1986 // Check if the WebView can go back.
1987 if (currentWebView.canGoBack()) {
1988 // Get the current web back forward list.
1989 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1991 // Get the previous entry URL.
1992 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1994 // Apply the domain settings.
1995 applyDomainSettings(currentWebView, previousUrl, false, false, false);
1997 // Load the previous website in the history.
1998 currentWebView.goBack();
2000 } else if (menuItemId == R.id.forward) { // Forward.
2001 // Check if the WebView can go forward.
2002 if (currentWebView.canGoForward()) {
2003 // Get the current web back forward list.
2004 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2006 // Get the next entry URL.
2007 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2009 // Apply the domain settings.
2010 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2012 // Load the next website in the history.
2013 currentWebView.goForward();
2015 } else if (menuItemId == R.id.history) { // History.
2016 // Instantiate the URL history dialog.
2017 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2019 // Show the URL history dialog.
2020 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2021 } else if (menuItemId == R.id.open) { // Open.
2022 // Instantiate the open file dialog.
2023 DialogFragment openDialogFragment = new OpenDialog();
2025 // Show the open file dialog.
2026 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2027 } else if (menuItemId == R.id.requests) { // Requests.
2028 // Populate the resource requests.
2029 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2031 // Create an intent to launch the Requests activity.
2032 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2034 // Add the block third-party requests status to the intent.
2035 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2038 startActivity(requestsIntent);
2039 } else if (menuItemId == R.id.downloads) { // Downloads.
2040 // Launch the system Download Manager.
2041 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2043 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2044 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2047 startActivity(downloadManagerIntent);
2048 } else if (menuItemId == R.id.domains) { // Domains.
2049 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2050 reapplyDomainSettingsOnRestart = true;
2052 // Launch the domains activity.
2053 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2055 // Add the extra information to the intent.
2056 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2058 // Get the current certificate.
2059 SslCertificate sslCertificate = currentWebView.getCertificate();
2061 // Check to see if the SSL certificate is populated.
2062 if (sslCertificate != null) {
2063 // Extract the certificate to strings.
2064 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2065 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2066 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2067 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2068 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2069 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2070 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2071 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2073 // Add the certificate to the intent.
2074 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2075 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2076 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2077 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2078 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2079 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2080 domainsIntent.putExtra("ssl_start_date", startDateLong);
2081 domainsIntent.putExtra("ssl_end_date", endDateLong);
2084 // Check to see if the current IP addresses have been received.
2085 if (currentWebView.hasCurrentIpAddresses()) {
2086 // Add the current IP addresses to the intent.
2087 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2091 startActivity(domainsIntent);
2092 } else if (menuItemId == R.id.settings) { // Settings.
2093 // Set the flag to reapply app settings on restart when returning from Settings.
2094 reapplyAppSettingsOnRestart = true;
2096 // Set the flag to reapply the domain settings on restart when returning from Settings.
2097 reapplyDomainSettingsOnRestart = true;
2099 // Launch the settings activity.
2100 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2101 startActivity(settingsIntent);
2102 } else if (menuItemId == R.id.import_export) { // Import/Export.
2103 // Create an intent to launch the import/export activity.
2104 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2107 startActivity(importExportIntent);
2108 } else if (menuItemId == R.id.logcat) { // Logcat.
2109 // Create an intent to launch the logcat activity.
2110 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2113 startActivity(logcatIntent);
2114 } else if (menuItemId == R.id.guide) { // Guide.
2115 // Create an intent to launch the guide activity.
2116 Intent guideIntent = new Intent(this, GuideActivity.class);
2119 startActivity(guideIntent);
2120 } else if (menuItemId == R.id.about) { // About
2121 // Create an intent to launch the about activity.
2122 Intent aboutIntent = new Intent(this, AboutActivity.class);
2124 // Create a string array for the blocklist versions.
2125 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],
2126 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2128 // Add the blocklist versions to the intent.
2129 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2132 startActivity(aboutIntent);
2135 // Close the navigation drawer.
2136 drawerLayout.closeDrawer(GravityCompat.START);
2141 public void onPostCreate(Bundle savedInstanceState) {
2142 // Run the default commands.
2143 super.onPostCreate(savedInstanceState);
2145 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2146 actionBarDrawerToggle.syncState();
2150 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2151 // Run the default commands.
2152 super.onConfigurationChanged(newConfig);
2154 // Reload the ad for the free flavor if not in full screen mode.
2155 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2156 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2157 View adView = findViewById(R.id.adview);
2159 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2160 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2161 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2164 // `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:
2165 // https://code.google.com/p/android/issues/detail?id=20493#c8
2166 // ActivityCompat.invalidateOptionsMenu(this);
2170 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2171 // Get the hit test result.
2172 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2174 // Define the URL strings.
2175 final String imageUrl;
2176 final String linkUrl;
2178 // Get handles for the system managers.
2179 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2181 // Remove the lint errors below that the clipboard manager might be null.
2182 assert clipboardManager != null;
2184 // Process the link according to the type.
2185 switch (hitTestResult.getType()) {
2186 // `SRC_ANCHOR_TYPE` is a link.
2187 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2188 // Get the target URL.
2189 linkUrl = hitTestResult.getExtra();
2191 // Set the target URL as the title of the `ContextMenu`.
2192 menu.setHeaderTitle(linkUrl);
2194 // Add an Open in New Tab entry.
2195 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2196 // Load the link URL in a new tab and move to it.
2197 addNewTab(linkUrl, true);
2199 // Consume the event.
2203 // Add an Open in Background entry.
2204 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2205 // Load the link URL in a new tab but do not move to it.
2206 addNewTab(linkUrl, false);
2208 // Consume the event.
2212 // Add an Open with App entry.
2213 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2214 openWithApp(linkUrl);
2216 // Consume the event.
2220 // Add an Open with Browser entry.
2221 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2222 openWithBrowser(linkUrl);
2224 // Consume the event.
2228 // Add a Copy URL entry.
2229 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2230 // Save the link URL in a `ClipData`.
2231 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2233 // Set the `ClipData` as the clipboard's primary clip.
2234 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2236 // Consume the event.
2240 // Add a Save URL entry.
2241 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2242 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2243 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2244 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2246 // Consume the event.
2250 // Add an empty Cancel entry, which by default closes the context menu.
2251 menu.add(R.string.cancel);
2254 // `IMAGE_TYPE` is an image.
2255 case WebView.HitTestResult.IMAGE_TYPE:
2256 // Get the image URL.
2257 imageUrl = hitTestResult.getExtra();
2259 // Remove the incorrect lint warning below that the image URL might be null.
2260 assert imageUrl != null;
2262 // Set the context menu title.
2263 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2264 // Truncate the image URL before making it the title.
2265 menu.setHeaderTitle(imageUrl.substring(0, 100));
2266 } else { // The image URL does not contain the full image data.
2267 // Set the image URL as the title of the context menu.
2268 menu.setHeaderTitle(imageUrl);
2271 // Add an Open in New Tab entry.
2272 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2273 // Load the image in a new tab.
2274 addNewTab(imageUrl, true);
2276 // Consume the event.
2280 // Add an Open with App entry.
2281 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2282 // Open the image URL with an external app.
2283 openWithApp(imageUrl);
2285 // Consume the event.
2289 // Add an Open with Browser entry.
2290 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2291 // Open the image URL with an external browser.
2292 openWithBrowser(imageUrl);
2294 // Consume the event.
2298 // Add a View Image entry.
2299 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2300 // Load the image in the current tab.
2301 loadUrl(currentWebView, imageUrl);
2303 // Consume the event.
2307 // Add a Save Image entry.
2308 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2309 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2310 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2311 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2313 // Consume the event.
2317 // Add a Copy URL entry.
2318 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2319 // Save the image URL in a clip data.
2320 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2322 // Set the clip data as the clipboard's primary clip.
2323 clipboardManager.setPrimaryClip(imageTypeClipData);
2325 // Consume the event.
2329 // Add an empty Cancel entry, which by default closes the context menu.
2330 menu.add(R.string.cancel);
2333 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2334 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2335 // Get the image URL.
2336 imageUrl = hitTestResult.getExtra();
2338 // Instantiate a handler.
2339 Handler handler = new Handler();
2341 // Get a message from the handler.
2342 Message message = handler.obtainMessage();
2344 // Request the image details from the last touched node be returned in the message.
2345 currentWebView.requestFocusNodeHref(message);
2347 // Get the link URL from the message data.
2348 linkUrl = message.getData().getString("url");
2350 // Set the link URL as the title of the context menu.
2351 menu.setHeaderTitle(linkUrl);
2353 // Add an Open in New Tab entry.
2354 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2355 // Load the link URL in a new tab and move to it.
2356 addNewTab(linkUrl, true);
2358 // Consume the event.
2362 // Add an Open in Background entry.
2363 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2364 // Lod the link URL in a new tab but do not move to it.
2365 addNewTab(linkUrl, false);
2367 // Consume the event.
2371 // Add an Open Image in New Tab entry.
2372 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2373 // Load the image in a new tab and move to it.
2374 addNewTab(imageUrl, true);
2376 // Consume the event.
2380 // Add an Open with App entry.
2381 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2382 // Open the link URL with an external app.
2383 openWithApp(linkUrl);
2385 // Consume the event.
2389 // Add an Open with Browser entry.
2390 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2391 // Open the link URL with an external browser.
2392 openWithBrowser(linkUrl);
2394 // Consume the event.
2398 // Add a View Image entry.
2399 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2400 // View the image in the current tab.
2401 loadUrl(currentWebView, imageUrl);
2403 // Consume the event.
2407 // Add a Save Image entry.
2408 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2409 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2410 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2411 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2413 // Consume the event.
2417 // Add a Copy URL entry.
2418 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2419 // Save the link URL in a clip data.
2420 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2422 // Set the clip data as the clipboard's primary clip.
2423 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2425 // Consume the event.
2429 // Add a Save URL entry.
2430 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2431 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2432 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2433 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2435 // Consume the event.
2439 // Add an empty Cancel entry, which by default closes the context menu.
2440 menu.add(R.string.cancel);
2443 case WebView.HitTestResult.EMAIL_TYPE:
2444 // Get the target URL.
2445 linkUrl = hitTestResult.getExtra();
2447 // Set the target URL as the title of the `ContextMenu`.
2448 menu.setHeaderTitle(linkUrl);
2450 // Add a Write Email entry.
2451 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2452 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2453 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2455 // Parse the url and set it as the data for the `Intent`.
2456 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2458 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2459 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2463 startActivity(emailIntent);
2464 } catch (ActivityNotFoundException exception) {
2465 // Display a snackbar.
2466 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2469 // Consume the event.
2473 // Add a Copy Email Address entry.
2474 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2475 // Save the email address in a `ClipData`.
2476 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2478 // Set the `ClipData` as the clipboard's primary clip.
2479 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2481 // Consume the event.
2485 // Add an empty Cancel entry, which by default closes the context menu.
2486 menu.add(R.string.cancel);
2492 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2493 // Get a handle for the bookmarks list view.
2494 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2497 Dialog dialog = dialogFragment.getDialog();
2499 // Remove the incorrect lint warning below that the dialog might be null.
2500 assert dialog != null;
2502 // Get the views from the dialog fragment.
2503 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2504 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2506 // Extract the strings from the edit texts.
2507 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2508 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2510 // Create a favorite icon byte array output stream.
2511 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2513 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2514 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2516 // Convert the favorite icon byte array stream to a byte array.
2517 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2519 // Display the new bookmark below the current items in the (0 indexed) list.
2520 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2522 // Create the bookmark.
2523 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2525 // Update the bookmarks cursor with the current contents of this folder.
2526 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2528 // Update the list view.
2529 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2531 // Scroll to the new bookmark.
2532 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2536 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2537 // Get a handle for the bookmarks list view.
2538 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2541 Dialog dialog = dialogFragment.getDialog();
2543 // Remove the incorrect lint warning below that the dialog might be null.
2544 assert dialog != null;
2546 // Get handles for the views in the dialog fragment.
2547 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2548 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2549 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2551 // Get new folder name string.
2552 String folderNameString = createFolderNameEditText.getText().toString();
2554 // Create a folder icon bitmap.
2555 Bitmap folderIconBitmap;
2557 // Set the folder icon bitmap according to the dialog.
2558 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2559 // Get the default folder icon drawable.
2560 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2562 // Convert the folder icon drawable to a bitmap drawable.
2563 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2565 // Convert the folder icon bitmap drawable to a bitmap.
2566 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2567 } else { // Use the WebView favorite icon.
2568 // Copy the favorite icon bitmap to the folder icon bitmap.
2569 folderIconBitmap = favoriteIconBitmap;
2572 // Create a folder icon byte array output stream.
2573 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2575 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2576 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2578 // Convert the folder icon byte array stream to a byte array.
2579 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2581 // Move all the bookmarks down one in the display order.
2582 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2583 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2584 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2587 // Create the folder, which will be placed at the top of the `ListView`.
2588 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2590 // Update the bookmarks cursor with the current contents of this folder.
2591 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2593 // Update the `ListView`.
2594 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2596 // Scroll to the new folder.
2597 bookmarksListView.setSelection(0);
2601 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2602 // Remove the incorrect lint warning below that the dialog fragment might be null.
2603 assert dialogFragment != null;
2606 Dialog dialog = dialogFragment.getDialog();
2608 // Remove the incorrect lint warning below that the dialog might be null.
2609 assert dialog != null;
2611 // Get handles for the views from the dialog.
2612 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2613 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2614 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2615 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2617 // Get the new folder name.
2618 String newFolderNameString = editFolderNameEditText.getText().toString();
2620 // Check if the favorite icon has changed.
2621 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2622 // Update the name in the database.
2623 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2624 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2625 // Create the new folder icon Bitmap.
2626 Bitmap folderIconBitmap;
2628 // Populate the new folder icon bitmap.
2629 if (defaultFolderIconRadioButton.isChecked()) {
2630 // Get the default folder icon drawable.
2631 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2633 // Convert the folder icon drawable to a bitmap drawable.
2634 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2636 // Convert the folder icon bitmap drawable to a bitmap.
2637 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2638 } else { // Use the `WebView` favorite icon.
2639 // Copy the favorite icon bitmap to the folder icon bitmap.
2640 folderIconBitmap = favoriteIconBitmap;
2643 // Create a folder icon byte array output stream.
2644 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2646 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2647 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2649 // Convert the folder icon byte array stream to a byte array.
2650 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2652 // Update the folder icon in the database.
2653 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2654 } else { // The folder icon and the name have changed.
2655 // Get the new folder icon `Bitmap`.
2656 Bitmap folderIconBitmap;
2657 if (defaultFolderIconRadioButton.isChecked()) {
2658 // Get the default folder icon drawable.
2659 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2661 // Convert the folder icon drawable to a bitmap drawable.
2662 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2664 // Convert the folder icon bitmap drawable to a bitmap.
2665 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2666 } else { // Use the `WebView` favorite icon.
2667 // Copy the favorite icon bitmap to the folder icon bitmap.
2668 folderIconBitmap = favoriteIconBitmap;
2671 // Create a folder icon byte array output stream.
2672 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2674 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2675 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2677 // Convert the folder icon byte array stream to a byte array.
2678 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2680 // Update the folder name and icon in the database.
2681 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2684 // Update the bookmarks cursor with the current contents of this folder.
2685 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2687 // Update the `ListView`.
2688 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2691 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2693 public void onBackPressed() {
2694 // Check the different options for processing `back`.
2695 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2696 // Close the navigation drawer.
2697 drawerLayout.closeDrawer(GravityCompat.START);
2698 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2699 // close the bookmarks drawer.
2700 drawerLayout.closeDrawer(GravityCompat.END);
2701 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2702 // Re-enable the screen timeout.
2703 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2705 // Unset the full screen video flag.
2706 displayingFullScreenVideo = false;
2708 // Remove all the views from the full screen video frame layout.
2709 fullScreenVideoFrameLayout.removeAllViews();
2711 // Hide the full screen video frame layout.
2712 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2714 // Enable the sliding drawers.
2715 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2717 // Show the main content relative layout.
2718 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2720 // Apply the appropriate full screen mode flags.
2721 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2722 // Hide the banner ad in the free flavor.
2723 if (BuildConfig.FLAVOR.contentEquals("free")) {
2724 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2725 View adView = findViewById(R.id.adview);
2727 // Hide the banner ad.
2728 AdHelper.hideAd(adView);
2731 /* Hide the system bars.
2732 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2733 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2734 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2735 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2737 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2738 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2740 // Reload the website if the app bar is hidden. Otherwise, there is some bug in Android that causes the WebView to be entirely black.
2742 // Reload the WebView.
2743 currentWebView.reload();
2745 } else { // Switch to normal viewing mode.
2746 // Remove the `SYSTEM_UI` flags from the root frame layout.
2747 rootFrameLayout.setSystemUiVisibility(0);
2750 // Reload the ad for the free flavor if not in full screen mode.
2751 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2752 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2753 View adView = findViewById(R.id.adview);
2755 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2756 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2758 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2759 // Get the current web back forward list.
2760 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2762 // Get the previous entry URL.
2763 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2765 // Apply the domain settings.
2766 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2769 currentWebView.goBack();
2770 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2771 // Close the current tab.
2773 } else { // There isn't anything to do in Privacy Browser.
2774 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2775 if (Build.VERSION.SDK_INT >= 21) {
2776 finishAndRemoveTask();
2781 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2786 // Process the results of a file browse.
2788 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2789 // Run the default commands.
2790 super.onActivityResult(requestCode, resultCode, returnedIntent);
2792 // Run the commands that correlate to the specified request code.
2793 switch (requestCode) {
2794 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2795 // File uploads only work on API >= 21.
2796 if (Build.VERSION.SDK_INT >= 21) {
2797 // Pass the file to the WebView.
2798 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2802 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2803 // Don't do anything if the user pressed back from the file picker.
2804 if (resultCode == Activity.RESULT_OK) {
2805 // Get a handle for the save dialog fragment.
2806 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2808 // Only update the file name if the dialog still exists.
2809 if (saveWebpageDialogFragment != null) {
2810 // Get a handle for the save webpage dialog.
2811 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2813 // Remove the incorrect lint warning below that the dialog might be null.
2814 assert saveWebpageDialog != null;
2816 // Get a handle for the file name edit text.
2817 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2818 TextView fileExistsWarningTextView = saveWebpageDialog.findViewById(R.id.file_exists_warning_textview);
2820 // Instantiate the file name helper.
2821 FileNameHelper fileNameHelper = new FileNameHelper();
2823 // Get the file path if it isn't null.
2824 if (returnedIntent.getData() != null) {
2825 // Convert the file name URI to a file name path.
2826 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2828 // Set the file name path as the text of the file name edit text.
2829 fileNameEditText.setText(fileNamePath);
2831 // Move the cursor to the end of the file name edit text.
2832 fileNameEditText.setSelection(fileNamePath.length());
2834 // Hide the file exists warning.
2835 fileExistsWarningTextView.setVisibility(View.GONE);
2841 case BROWSE_OPEN_REQUEST_CODE:
2842 // Don't do anything if the user pressed back from the file picker.
2843 if (resultCode == Activity.RESULT_OK) {
2844 // Get a handle for the open dialog fragment.
2845 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2847 // Only update the file name if the dialog still exists.
2848 if (openDialogFragment != null) {
2849 // Get a handle for the open dialog.
2850 Dialog openDialog = openDialogFragment.getDialog();
2852 // Remove the incorrect lint warning below that the dialog might be null.
2853 assert openDialog != null;
2855 // Get a handle for the file name edit text.
2856 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2858 // Instantiate the file name helper.
2859 FileNameHelper fileNameHelper = new FileNameHelper();
2861 // Get the file path if it isn't null.
2862 if (returnedIntent.getData() != null) {
2863 // Convert the file name URI to a file name path.
2864 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2866 // Set the file name path as the text of the file name edit text.
2867 fileNameEditText.setText(fileNamePath);
2869 // Move the cursor to the end of the file name edit text.
2870 fileNameEditText.setSelection(fileNamePath.length());
2878 private void loadUrlFromTextBox() {
2879 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2880 String unformattedUrlString = urlEditText.getText().toString().trim();
2882 // Initialize the formatted URL string.
2885 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2886 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2887 // Load the entire content URL.
2888 url = unformattedUrlString;
2889 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2890 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2891 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2892 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2893 unformattedUrlString = "https://" + unformattedUrlString;
2896 // Initialize `unformattedUrl`.
2897 URL unformattedUrl = null;
2899 // 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.
2901 unformattedUrl = new URL(unformattedUrlString);
2902 } catch (MalformedURLException e) {
2903 e.printStackTrace();
2906 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2907 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2908 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2909 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2910 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2911 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2914 Uri.Builder uri = new Uri.Builder();
2915 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2917 // Decode the URI as a UTF-8 string in.
2919 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2920 } catch (UnsupportedEncodingException exception) {
2921 // Do nothing. The formatted URL string will remain blank.
2923 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2924 // Create an encoded URL String.
2925 String encodedUrlString;
2927 // Sanitize the search input.
2929 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2930 } catch (UnsupportedEncodingException exception) {
2931 encodedUrlString = "";
2934 // Add the base search URL.
2935 url = searchURL + encodedUrlString;
2938 // 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.
2939 urlEditText.clearFocus();
2942 loadUrl(currentWebView, url);
2945 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2946 // Sanitize the URL.
2947 url = sanitizeUrl(url);
2949 // Apply the domain settings and load the URL.
2950 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2953 public void findPreviousOnPage(View view) {
2954 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2955 currentWebView.findNext(false);
2958 public void findNextOnPage(View view) {
2959 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2960 currentWebView.findNext(true);
2963 public void closeFindOnPage(View view) {
2964 // Get a handle for the views.
2965 Toolbar toolbar = findViewById(R.id.toolbar);
2966 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2967 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2969 // Delete the contents of `find_on_page_edittext`.
2970 findOnPageEditText.setText(null);
2972 // Clear the highlighted phrases if the WebView is not null.
2973 if (currentWebView != null) {
2974 currentWebView.clearMatches();
2977 // Hide the find on page linear layout.
2978 findOnPageLinearLayout.setVisibility(View.GONE);
2980 // Show the toolbar.
2981 toolbar.setVisibility(View.VISIBLE);
2983 // Get a handle for the input method manager.
2984 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2986 // Remove the lint warning below that the input method manager might be null.
2987 assert inputMethodManager != null;
2989 // Hide the keyboard.
2990 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2994 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2995 // Remove the incorrect lint warning below that the dialog fragment might be null.
2996 assert dialogFragment != null;
2999 Dialog dialog = dialogFragment.getDialog();
3001 // Remove the incorrect lint warning below tha the dialog might be null.
3002 assert dialog != null;
3004 // Get a handle for the font size edit text.
3005 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
3007 // Initialize the new font size variable with the current font size.
3008 int newFontSize = currentWebView.getSettings().getTextZoom();
3010 // Get the font size from the edit text.
3012 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
3013 } catch (Exception exception) {
3014 // If the edit text does not contain a valid font size do nothing.
3017 // Apply the new font size.
3018 currentWebView.getSettings().setTextZoom(newFontSize);
3022 public void onOpen(DialogFragment dialogFragment) {
3024 Dialog dialog = dialogFragment.getDialog();
3026 // Remove the incorrect lint warning below that the dialog might be null.
3027 assert dialog != null;
3029 // Get a handle for the file name edit text.
3030 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3032 // Get the file path string.
3033 openFilePath = fileNameEditText.getText().toString();
3035 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3036 applyDomainSettings(currentWebView, "file://" + openFilePath, true, false, false);
3038 // Check to see if the storage permission is needed.
3039 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
3041 currentWebView.loadUrl("file://" + openFilePath);
3042 } else { // The storage permission has not been granted.
3043 // Get the external private directory file.
3044 File externalPrivateDirectoryFile = getExternalFilesDir(null);
3046 // Remove the incorrect lint error below that the file might be null.
3047 assert externalPrivateDirectoryFile != null;
3049 // Get the external private directory string.
3050 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
3052 // Check to see if the file path is in the external private directory.
3053 if (openFilePath.startsWith(externalPrivateDirectory)) { // the file path is in the external private directory.
3055 currentWebView.loadUrl("file://" + openFilePath);
3056 } else { // The file path is in a public directory.
3057 // Check if the user has previously denied the storage permission.
3058 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3059 // Instantiate the storage permission alert dialog.
3060 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.OPEN);
3062 // Show the storage permission alert dialog. The permission will be requested the the dialog is closed.
3063 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
3064 } else { // Show the permission request directly.
3065 // Request the write external storage permission. The file will be opened when it finishes.
3066 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, StoragePermissionDialog.OPEN);
3073 public void onSaveWebpage(int saveType, String originalUrlString, DialogFragment dialogFragment) {
3075 Dialog dialog = dialogFragment.getDialog();
3077 // Remove the incorrect lint warning below that the dialog might be null.
3078 assert dialog != null;
3080 // Get a handle for the edit texts.
3081 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3082 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3085 if ((originalUrlString != null) && originalUrlString.startsWith("data:")) {
3086 // Save the original URL.
3087 saveWebpageUrl = originalUrlString;
3089 // Get the URL from the edit text, which may have been modified.
3090 saveWebpageUrl = dialogUrlEditText.getText().toString();
3093 // Get the file path from the edit text.
3094 saveWebpageFilePath = fileNameEditText.getText().toString();
3096 // Check to see if the storage permission is needed.
3097 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
3098 //Save the webpage according to the save type.
3100 case StoragePermissionDialog.SAVE_URL:
3102 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3105 case StoragePermissionDialog.SAVE_ARCHIVE:
3106 // Save the webpage archive.
3107 saveWebpageArchive(saveWebpageFilePath);
3110 case StoragePermissionDialog.SAVE_IMAGE:
3111 // Save the webpage image.
3112 new SaveWebpageImage(this, this, saveWebpageFilePath, currentWebView).execute();
3116 // Reset the strings.
3117 saveWebpageUrl = "";
3118 saveWebpageFilePath = "";
3119 } else { // The storage permission has not been granted.
3120 // Get the external private directory file.
3121 File externalPrivateDirectoryFile = getExternalFilesDir(null);
3123 // Remove the incorrect lint error below that the file might be null.
3124 assert externalPrivateDirectoryFile != null;
3126 // Get the external private directory string.
3127 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
3129 // Check to see if the file path is in the external private directory.
3130 if (saveWebpageFilePath.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
3131 // Save the webpage according to the save type.
3133 case StoragePermissionDialog.SAVE_URL:
3135 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3138 case StoragePermissionDialog.SAVE_ARCHIVE:
3139 // Save the webpage archive.
3140 saveWebpageArchive(saveWebpageFilePath);
3143 case StoragePermissionDialog.SAVE_IMAGE:
3144 // Save the webpage image.
3145 new SaveWebpageImage(this, this, saveWebpageFilePath, currentWebView).execute();
3149 // Reset the strings.
3150 saveWebpageUrl = "";
3151 saveWebpageFilePath = "";
3152 } else { // The file path is in a public directory.
3153 // Check if the user has previously denied the storage permission.
3154 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3155 // Instantiate the storage permission alert dialog.
3156 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(saveType);
3158 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
3159 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
3160 } else { // Show the permission request directly.
3161 // Request the write external storage permission according to the save type. The URL will be saved when it finishes.
3162 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, saveType);
3169 public void onCloseStoragePermissionDialog(int requestType) {
3170 // Request the write external storage permission according to the request type. The file will be opened when it finishes.
3171 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestType);
3176 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3177 //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).
3178 if (grantResults.length > 0) {
3179 switch (requestCode) {
3180 case StoragePermissionDialog.OPEN:
3181 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3182 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3184 currentWebView.loadUrl("file://" + openFilePath);
3185 } else { // The storage permission was not granted.
3186 // Display an error snackbar.
3187 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3191 case StoragePermissionDialog.SAVE_URL:
3192 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3193 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3194 // Save the raw URL.
3195 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3196 } else { // The storage permission was not granted.
3197 // Display an error snackbar.
3198 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3202 case StoragePermissionDialog.SAVE_ARCHIVE:
3203 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3204 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3205 // Save the webpage archive.
3206 saveWebpageArchive(saveWebpageFilePath);
3207 } else { // The storage permission was not granted.
3208 // Display an error snackbar.
3209 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3213 case StoragePermissionDialog.SAVE_IMAGE:
3214 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3215 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3216 // Save the webpage image.
3217 new SaveWebpageImage(this, this, saveWebpageFilePath, currentWebView).execute();
3218 } else { // The storage permission was not granted.
3219 // Display an error snackbar.
3220 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3225 // Reset the strings.
3227 saveWebpageUrl = "";
3228 saveWebpageFilePath = "";
3232 private void initializeApp() {
3233 // Get a handle for the input method.
3234 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3236 // Remove the lint warning below that the input method manager might be null.
3237 assert inputMethodManager != null;
3239 // Initialize the gray foreground color spans for highlighting the URLs. The deprecated `getResources()` must be used until API >= 23.
3240 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3241 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3243 // Get the current theme status.
3244 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3246 // Set the red color span according to the theme.
3247 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3248 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3250 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
3253 // Remove the formatting from the URL edit text when the user is editing the text.
3254 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3255 if (hasFocus) { // The user is editing the URL text box.
3256 // Remove the highlighting.
3257 urlEditText.getText().removeSpan(redColorSpan);
3258 urlEditText.getText().removeSpan(initialGrayColorSpan);
3259 urlEditText.getText().removeSpan(finalGrayColorSpan);
3260 } else { // The user has stopped editing the URL text box.
3261 // Move to the beginning of the string.
3262 urlEditText.setSelection(0);
3264 // Reapply the highlighting.
3269 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3270 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3271 // If the event is a key-down event on the `enter` button, load the URL.
3272 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3273 // Load the URL into the mainWebView and consume the event.
3274 loadUrlFromTextBox();
3276 // If the enter key was pressed, consume the event.
3279 // If any other key was pressed, do not consume the event.
3284 // Create an Orbot status broadcast receiver.
3285 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3287 public void onReceive(Context context, Intent intent) {
3288 // Store the content of the status message in `orbotStatus`.
3289 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3291 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3292 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3293 // Reset the waiting for proxy status.
3294 waitingForProxy = false;
3296 // Get a handle for the waiting for proxy dialog.
3297 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3299 // Dismiss the waiting for proxy dialog if it is displayed.
3300 if (waitingForProxyDialogFragment != null) {
3301 waitingForProxyDialogFragment.dismiss();
3304 // Reload existing URLs and load any URLs that are waiting for the proxy.
3305 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3306 // Get the WebView tab fragment.
3307 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3309 // Get the fragment view.
3310 View fragmentView = webViewTabFragment.getView();
3312 // Only process the WebViews if they exist.
3313 if (fragmentView != null) {
3314 // Get the nested scroll WebView from the tab fragment.
3315 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3317 // Get the waiting for proxy URL string.
3318 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3320 // Load the pending URL if it exists.
3321 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3323 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3325 // Reset the waiting for proxy URL string.
3326 nestedScrollWebView.resetWaitingForProxyUrlString();
3327 } else { // No URL is waiting to be loaded.
3328 // Reload the existing URL.
3329 nestedScrollWebView.reload();
3337 // Register the Orbot status broadcast receiver on `this` context.
3338 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3340 // Get handles for views that need to be modified.
3341 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3342 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3343 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3344 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3345 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3347 // Update the web view pager every time a tab is modified.
3348 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3350 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3355 public void onPageSelected(int position) {
3356 // Close the find on page bar if it is open.
3357 closeFindOnPage(null);
3359 // Set the current WebView.
3360 setCurrentWebView(position);
3362 // 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.
3363 if (tabLayout.getSelectedTabPosition() != position) {
3364 // Wait until the new tab has been created.
3365 tabLayout.post(() -> {
3366 // Get a handle for the tab.
3367 TabLayout.Tab tab = tabLayout.getTabAt(position);
3369 // Assert that the tab is not null.
3379 public void onPageScrollStateChanged(int state) {
3384 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3385 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3387 public void onTabSelected(TabLayout.Tab tab) {
3388 // Select the same page in the view pager.
3389 webViewPager.setCurrentItem(tab.getPosition());
3393 public void onTabUnselected(TabLayout.Tab tab) {
3398 public void onTabReselected(TabLayout.Tab tab) {
3399 // Instantiate the View SSL Certificate dialog.
3400 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3402 // Display the View SSL Certificate dialog.
3403 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3407 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3408 launchBookmarksActivityFab.setOnClickListener(v -> {
3409 // Get a copy of the favorite icon bitmap.
3410 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3412 // Create a favorite icon byte array output stream.
3413 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3415 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3416 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3418 // Convert the favorite icon byte array stream to a byte array.
3419 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3421 // Create an intent to launch the bookmarks activity.
3422 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3424 // Add the extra information to the intent.
3425 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3426 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3427 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3428 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3431 startActivity(bookmarksIntent);
3434 // Set the create new bookmark folder FAB to display an alert dialog.
3435 createBookmarkFolderFab.setOnClickListener(v -> {
3436 // Create a create bookmark folder dialog.
3437 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3439 // Show the create bookmark folder dialog.
3440 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3443 // Set the create new bookmark FAB to display an alert dialog.
3444 createBookmarkFab.setOnClickListener(view -> {
3445 // Instantiate the create bookmark dialog.
3446 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3448 // Display the create bookmark dialog.
3449 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3452 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3453 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3455 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3460 public void onTextChanged(CharSequence s, int start, int before, int count) {
3465 public void afterTextChanged(Editable s) {
3466 // 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.
3467 if (currentWebView != null) {
3468 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3473 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3474 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3475 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3476 // Hide the soft keyboard.
3477 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3479 // Consume the event.
3481 } else { // A different key was pressed.
3482 // Do not consume the event.
3487 // Implement swipe to refresh.
3488 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3490 // Store the default progress view offsets for use later in `initializeWebView()`.
3491 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3492 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3494 // Set the refresh color scheme according to the theme.
3495 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3496 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
3498 swipeRefreshLayout.setColorSchemeResources(R.color.violet_500);
3501 // Initialize a color background typed value.
3502 TypedValue colorBackgroundTypedValue = new TypedValue();
3504 // Get the color background from the theme.
3505 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3507 // Get the color background int from the typed value.
3508 int colorBackgroundInt = colorBackgroundTypedValue.data;
3510 // Set the swipe refresh background color.
3511 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3513 // The drawer titles identify the drawer layouts in accessibility mode.
3514 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3515 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3517 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3518 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3520 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3521 currentBookmarksFolder = "";
3523 // Load the home folder, which is `""` in the database.
3524 loadBookmarksFolder();
3526 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3527 // Convert the id from long to int to match the format of the bookmarks database.
3528 int databaseId = (int) id;
3530 // Get the bookmark cursor for this ID.
3531 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3533 // Move the bookmark cursor to the first row.
3534 bookmarkCursor.moveToFirst();
3536 // Act upon the bookmark according to the type.
3537 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3538 // Store the new folder name in `currentBookmarksFolder`.
3539 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3541 // Load the new folder.
3542 loadBookmarksFolder();
3543 } else { // The selected bookmark is not a folder.
3544 // Load the bookmark URL.
3545 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3547 // Close the bookmarks drawer.
3548 drawerLayout.closeDrawer(GravityCompat.END);
3551 // Close the `Cursor`.
3552 bookmarkCursor.close();
3555 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3556 // Convert the database ID from `long` to `int`.
3557 int databaseId = (int) id;
3559 // Find out if the selected bookmark is a folder.
3560 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3563 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3564 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3566 // Instantiate the edit folder bookmark dialog.
3567 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3569 // Show the edit folder bookmark dialog.
3570 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3572 // Get the bookmark cursor for this ID.
3573 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3575 // Move the bookmark cursor to the first row.
3576 bookmarkCursor.moveToFirst();
3578 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3579 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3582 // Consume the event.
3586 // The drawer listener is used to update the navigation menu.
3587 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3589 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3593 public void onDrawerOpened(@NonNull View drawerView) {
3597 public void onDrawerClosed(@NonNull View drawerView) {
3601 public void onDrawerStateChanged(int newState) {
3602 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3603 // Update the navigation menu items if the WebView is not null.
3604 if (currentWebView != null) {
3605 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3606 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3607 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3608 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3610 // Hide the keyboard (if displayed).
3611 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3614 // 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.
3615 urlEditText.clearFocus();
3616 currentWebView.clearFocus();
3621 // 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).
3622 customHeaders.put("X-Requested-With", "");
3624 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3625 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3627 // Get a handle for the WebView.
3628 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3630 // Store the default user agent.
3631 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3633 // Destroy the bare WebView.
3634 bareWebView.destroy();
3637 private void applyAppSettings() {
3638 // Get a handle for the shared preferences.
3639 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3641 // Store the values from the shared preferences in variables.
3642 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3643 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3644 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3645 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3646 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3647 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3648 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3649 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3650 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3652 // Apply the saved proxy mode if the app has been restarted.
3653 if (savedProxyMode != null) {
3654 // Apply the saved proxy mode.
3655 proxyMode = savedProxyMode;
3657 // Reset the saved proxy mode.
3658 savedProxyMode = null;
3661 // Get the search string.
3662 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3664 // Set the search string.
3665 if (searchString.equals("Custom URL")) { // A custom search string is used.
3666 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3667 } else { // A custom search string is not used.
3668 searchURL = searchString;
3674 // Set Do Not Track status.
3675 if (doNotTrackEnabled) {
3676 customHeaders.put("DNT", "1");
3678 customHeaders.remove("DNT");
3681 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3682 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3683 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3684 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3685 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3687 // Add the scrolling behavior to the layout parameters.
3689 // Enable scrolling of the app bar.
3690 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3691 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3692 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3693 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3695 // Disable scrolling of the app bar.
3696 swipeRefreshLayoutParams.setBehavior(null);
3697 toolbarLayoutParams.setScrollFlags(0);
3698 findOnPageLayoutParams.setScrollFlags(0);
3699 tabsLayoutParams.setScrollFlags(0);
3701 // Expand the app bar if it is currently collapsed.
3702 appBarLayout.setExpanded(true);
3705 // Apply the modified layout parameters.
3706 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3707 toolbar.setLayoutParams(toolbarLayoutParams);
3708 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3709 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3711 // Set the app bar scrolling for each WebView.
3712 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3713 // Get the WebView tab fragment.
3714 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3716 // Get the fragment view.
3717 View fragmentView = webViewTabFragment.getView();
3719 // Only modify the WebViews if they exist.
3720 if (fragmentView != null) {
3721 // Get the nested scroll WebView from the tab fragment.
3722 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3724 // Set the app bar scrolling.
3725 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3729 // Update the full screen browsing mode settings.
3730 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3731 // Update the visibility of the app bar, which might have changed in the settings.
3733 // Hide the tab linear layout.
3734 tabsLinearLayout.setVisibility(View.GONE);
3736 // Hide the action bar.
3739 // Show the tab linear layout.
3740 tabsLinearLayout.setVisibility(View.VISIBLE);
3742 // Show the action bar.
3746 // Hide the banner ad in the free flavor.
3747 if (BuildConfig.FLAVOR.contentEquals("free")) {
3748 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3749 View adView = findViewById(R.id.adview);
3751 // Hide the banner ad.
3752 AdHelper.hideAd(adView);
3755 /* Hide the system bars.
3756 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3757 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3758 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3759 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3761 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3762 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3763 } else { // Privacy Browser is not in full screen browsing mode.
3764 // 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.
3765 inFullScreenBrowsingMode = false;
3767 // Show the tab linear layout.
3768 tabsLinearLayout.setVisibility(View.VISIBLE);
3770 // Show the action bar.
3773 // Show the banner ad in the free flavor.
3774 if (BuildConfig.FLAVOR.contentEquals("free")) {
3775 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3776 View adView = findViewById(R.id.adview);
3778 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3779 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
3780 AdHelper.initializeAds(adView, getApplicationContext(), this, getSupportFragmentManager(), getString(R.string.ad_unit_id));
3783 // Remove the `SYSTEM_UI` flags from the root frame layout.
3784 rootFrameLayout.setSystemUiVisibility(0);
3789 public void navigateHistory(String url, int steps) {
3790 // Apply the domain settings.
3791 applyDomainSettings(currentWebView, url, false, false, false);
3793 // Load the history entry.
3794 currentWebView.goBackOrForward(steps);
3798 public void pinnedErrorGoBack() {
3799 // Get the current web back forward list.
3800 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3802 // Get the previous entry URL.
3803 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3805 // Apply the domain settings.
3806 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3809 currentWebView.goBack();
3812 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3813 @SuppressLint("SetJavaScriptEnabled")
3814 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3815 // Store the current URL.
3816 nestedScrollWebView.setCurrentUrl(url);
3818 // Parse the URL into a URI.
3819 Uri uri = Uri.parse(url);
3821 // Extract the domain from `uri`.
3822 String newHostName = uri.getHost();
3824 // Strings don't like to be null.
3825 if (newHostName == null) {
3829 // 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.
3830 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3831 // Set the new host name as the current domain name.
3832 nestedScrollWebView.setCurrentDomainName(newHostName);
3834 // Reset the ignoring of pinned domain information.
3835 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3837 // Clear any pinned SSL certificate or IP addresses.
3838 nestedScrollWebView.clearPinnedSslCertificate();
3839 nestedScrollWebView.clearPinnedIpAddresses();
3841 // Reset the favorite icon if specified.
3843 // Initialize the favorite icon.
3844 nestedScrollWebView.initializeFavoriteIcon();
3846 // Get the current page position.
3847 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3849 // Get the corresponding tab.
3850 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3852 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3854 // Get the tab custom view.
3855 View tabCustomView = tab.getCustomView();
3857 // Remove the warning below that the tab custom view might be null.
3858 assert tabCustomView != null;
3860 // Get the tab views.
3861 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3862 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3864 // Set the default favorite icon as the favorite icon for this tab.
3865 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3867 // Set the loading title text.
3868 tabTitleTextView.setText(R.string.loading);
3872 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3873 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3875 // Get a full cursor from `domainsDatabaseHelper`.
3876 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3878 // Initialize `domainSettingsSet`.
3879 Set<String> domainSettingsSet = new HashSet<>();
3881 // Get the domain name column index.
3882 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3884 // Populate `domainSettingsSet`.
3885 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3886 // Move `domainsCursor` to the current row.
3887 domainNameCursor.moveToPosition(i);
3889 // Store the domain name in `domainSettingsSet`.
3890 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3893 // Close `domainNameCursor.
3894 domainNameCursor.close();
3896 // Initialize the domain name in database variable.
3897 String domainNameInDatabase = null;
3899 // Check the hostname against the domain settings set.
3900 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3901 // Record the domain name in the database.
3902 domainNameInDatabase = newHostName;
3904 // Set the domain settings applied tracker to true.
3905 nestedScrollWebView.setDomainSettingsApplied(true);
3906 } else { // The hostname is not contained in the domain settings set.
3907 // Set the domain settings applied tracker to false.
3908 nestedScrollWebView.setDomainSettingsApplied(false);
3911 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3912 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3913 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3914 // Set the domain settings applied tracker to true.
3915 nestedScrollWebView.setDomainSettingsApplied(true);
3917 // Store the applied domain names as it appears in the database.
3918 domainNameInDatabase = "*." + newHostName;
3921 // Strip out the lowest subdomain of of the host name.
3922 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3926 // Get a handle for the shared preferences.
3927 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3929 // Store the general preference information.
3930 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3931 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3932 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3933 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3934 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3935 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3937 // Get the WebView theme entry values string array.
3938 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3940 // Get a handle for the cookie manager.
3941 CookieManager cookieManager = CookieManager.getInstance();
3943 // Initialize the user agent array adapter and string array.
3944 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3945 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3947 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3948 // Get a cursor for the current host and move it to the first position.
3949 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3950 currentDomainSettingsCursor.moveToFirst();
3952 // Get the settings from the cursor.
3953 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3954 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3955 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3956 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3957 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3958 // Form data can be removed once the minimum API >= 26.
3959 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3960 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3961 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3962 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3963 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3964 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3965 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3966 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3967 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3968 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3969 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3970 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3971 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3972 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3973 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3974 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3975 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3976 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WEBVIEW_THEME));
3977 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3978 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3979 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3980 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3981 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3982 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3983 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3984 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3985 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3986 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3987 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3989 // Get the pinned SSL date longs.
3990 long pinnedSslStartDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE));
3991 long pinnedSslEndDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE));
3993 // Define the pinned SSL date variables.
3994 Date pinnedSslStartDate;
3995 Date pinnedSslEndDate;
3997 // 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.
3998 if (pinnedSslStartDateLong == 0) {
3999 pinnedSslStartDate = null;
4001 pinnedSslStartDate = new Date(pinnedSslStartDateLong);
4004 // 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.
4005 if (pinnedSslEndDateLong == 0) {
4006 pinnedSslEndDate = null;
4008 pinnedSslEndDate = new Date(pinnedSslEndDateLong);
4011 // Close the current host domain settings cursor.
4012 currentDomainSettingsCursor.close();
4014 // If there is a pinned SSL certificate, store it in the WebView.
4015 if (pinnedSslCertificate) {
4016 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
4017 pinnedSslStartDate, pinnedSslEndDate);
4020 // If there is a pinned IP address, store it in the WebView.
4021 if (pinnedIpAddresses) {
4022 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
4025 // Apply the cookie domain settings.
4026 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4028 // Set third-party cookies status if API >= 21.
4029 if (Build.VERSION.SDK_INT >= 21) {
4030 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
4033 // Apply the form data setting if the API < 26.
4034 if (Build.VERSION.SDK_INT < 26) {
4035 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4038 // Apply the font size.
4039 try { // Try the specified font size to see if it is valid.
4040 if (fontSize == 0) { // Apply the default font size.
4041 // Try to set the font size from the value in the app settings.
4042 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4043 } else { // Apply the font size from domain settings.
4044 nestedScrollWebView.getSettings().setTextZoom(fontSize);
4046 } catch (Exception exception) { // The specified font size is invalid
4047 // Set the font size to be 100%
4048 nestedScrollWebView.getSettings().setTextZoom(100);
4051 // Set the user agent.
4052 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4053 // Get the array position of the default user agent name.
4054 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4056 // Set the user agent according to the system default.
4057 switch (defaultUserAgentArrayPosition) {
4058 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4059 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4060 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4063 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4064 // Set the user agent to `""`, which uses the default value.
4065 nestedScrollWebView.getSettings().setUserAgentString("");
4068 case SETTINGS_CUSTOM_USER_AGENT:
4069 // Set the default custom user agent.
4070 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4074 // Get the user agent string from the user agent data array
4075 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4077 } else { // Set the user agent according to the stored name.
4078 // Get the array position of the user agent name.
4079 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4081 switch (userAgentArrayPosition) {
4082 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4083 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
4086 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4087 // Set the user agent to `""`, which uses the default value.
4088 nestedScrollWebView.getSettings().setUserAgentString("");
4092 // Get the user agent string from the user agent data array.
4093 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4097 // Set swipe to refresh.
4098 switch (swipeToRefreshInt) {
4099 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4100 // Store the swipe to refresh status in the nested scroll WebView.
4101 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4103 // Update the swipe refresh layout.
4104 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4105 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4106 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4107 } else { // Swipe to refresh is disabled.
4108 // Disable the swipe refresh layout.
4109 swipeRefreshLayout.setEnabled(false);
4113 case DomainsDatabaseHelper.ENABLED:
4114 // Store the swipe to refresh status in the nested scroll WebView.
4115 nestedScrollWebView.setSwipeToRefresh(true);
4117 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4118 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4121 case DomainsDatabaseHelper.DISABLED:
4122 // Store the swipe to refresh status in the nested scroll WebView.
4123 nestedScrollWebView.setSwipeToRefresh(false);
4125 // Disable swipe to refresh.
4126 swipeRefreshLayout.setEnabled(false);
4129 // Check to see if WebView themes are supported.
4130 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4131 // Set the WebView theme.
4132 switch (webViewThemeInt) {
4133 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4134 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4135 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4136 // Turn off the WebView dark mode.
4137 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4138 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4139 // Turn on the WebView dark mode.
4140 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4141 } else { // The system default theme is selected.
4142 // Get the current system theme status.
4143 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4145 // Set the WebView theme according to the current system theme status.
4146 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4147 // Turn off the WebView dark mode.
4148 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4149 } else { // The system is in night mode.
4150 // Turn on the WebView dark mode.
4151 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4156 case DomainsDatabaseHelper.LIGHT_THEME:
4157 // Turn off the WebView dark mode.
4158 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4161 case DomainsDatabaseHelper.DARK_THEME:
4162 // Turn on the WebView dark mode.
4163 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4168 // Set the viewport.
4169 switch (wideViewportInt) {
4170 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4171 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4174 case DomainsDatabaseHelper.ENABLED:
4175 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4178 case DomainsDatabaseHelper.DISABLED:
4179 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4183 // Set the loading of webpage images.
4184 switch (displayWebpageImagesInt) {
4185 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4186 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4189 case DomainsDatabaseHelper.ENABLED:
4190 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4193 case DomainsDatabaseHelper.DISABLED:
4194 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4198 // Get the current theme status.
4199 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4201 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4202 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4203 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
4205 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
4207 } else { // The new URL does not have custom domain settings. Load the defaults.
4208 // Store the values from the shared preferences.
4209 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4210 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4211 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4212 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4213 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4214 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4215 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4216 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4217 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4218 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4219 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4220 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4222 // Apply the default first-party cookie setting.
4223 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4225 // Apply the default font size setting.
4227 // Try to set the font size from the value in the app settings.
4228 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4229 } catch (Exception exception) {
4230 // If the app settings value is invalid, set the font size to 100%.
4231 nestedScrollWebView.getSettings().setTextZoom(100);
4234 // Apply the form data setting if the API < 26.
4235 if (Build.VERSION.SDK_INT < 26) {
4236 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4239 // Store the swipe to refresh status in the nested scroll WebView.
4240 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4242 // Update the swipe refresh layout.
4243 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4244 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4245 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4246 } else { // Swipe to refresh is disabled.
4247 // Disable the swipe refresh layout.
4248 swipeRefreshLayout.setEnabled(false);
4251 // Reset the pinned variables.
4252 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4254 // Set third-party cookies status if API >= 21.
4255 if (Build.VERSION.SDK_INT >= 21) {
4256 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4259 // Get the array position of the user agent name.
4260 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4262 // Set the user agent.
4263 switch (userAgentArrayPosition) {
4264 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4265 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4266 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4269 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4270 // Set the user agent to `""`, which uses the default value.
4271 nestedScrollWebView.getSettings().setUserAgentString("");
4274 case SETTINGS_CUSTOM_USER_AGENT:
4275 // Set the default custom user agent.
4276 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4280 // Get the user agent string from the user agent data array
4281 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4284 // Apply the WebView theme if supported by the installed WebView.
4285 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4286 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4287 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4288 // Turn off the WebView dark mode.
4289 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4290 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4291 // Turn on the WebView dark mode.
4292 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4293 } else { // The system default theme is selected.
4294 // Get the current system theme status.
4295 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4297 // Set the WebView theme according to the current system theme status.
4298 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4299 // Turn off the WebView dark mode.
4300 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4301 } else { // The system is in night mode.
4302 // Turn on the WebView dark mode.
4303 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4308 // Set the viewport.
4309 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4311 // Set the loading of webpage images.
4312 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4314 // Set a transparent background on the URL relative layout.
4315 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4318 // Close the domains database helper.
4319 domainsDatabaseHelper.close();
4321 // Update the privacy icons.
4322 updatePrivacyIcons(true);
4325 // Reload the website if returning from the Domains activity.
4326 if (reloadWebsite) {
4327 nestedScrollWebView.reload();
4330 // 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.
4332 nestedScrollWebView.loadUrl(url, customHeaders);
4336 private void applyProxy(boolean reloadWebViews) {
4337 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4338 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4340 // Reset the waiting for proxy tracker.
4341 waitingForProxy = false;
4343 // Get the current theme status.
4344 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4346 // Update the user interface and reload the WebViews if requested.
4347 switch (proxyMode) {
4348 case ProxyHelper.NONE:
4349 // Initialize a color background typed value.
4350 TypedValue colorBackgroundTypedValue = new TypedValue();
4352 // Get the color background from the theme.
4353 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4355 // Get the color background int from the typed value.
4356 int colorBackgroundInt = colorBackgroundTypedValue.data;
4358 // Set the default app bar layout background.
4359 appBarLayout.setBackgroundColor(colorBackgroundInt);
4362 case ProxyHelper.TOR:
4363 // Set the app bar background to indicate proxying through Orbot is enabled.
4364 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4365 appBarLayout.setBackgroundResource(R.color.blue_50);
4367 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4370 // Check to see if Orbot is installed.
4372 // Get the package manager.
4373 PackageManager packageManager = getPackageManager();
4375 // 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.
4376 packageManager.getPackageInfo("org.torproject.android", 0);
4378 // Check to see if the proxy is ready.
4379 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4380 // Set the waiting for proxy status.
4381 waitingForProxy = true;
4383 // Show the waiting for proxy dialog if it isn't already displayed.
4384 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4385 // Get a handle for the waiting for proxy alert dialog.
4386 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4388 // Display the waiting for proxy alert dialog.
4389 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4392 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4393 // Show the Orbot not installed dialog if it is not already displayed.
4394 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4395 // Get a handle for the Orbot not installed alert dialog.
4396 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4398 // Display the Orbot not installed alert dialog.
4399 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4404 case ProxyHelper.I2P:
4405 // Set the app bar background to indicate proxying through Orbot is enabled.
4406 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4407 appBarLayout.setBackgroundResource(R.color.blue_50);
4409 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4412 // Check to see if I2P is installed.
4414 // Get the package manager.
4415 PackageManager packageManager = getPackageManager();
4417 // 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.
4418 packageManager.getPackageInfo("org.torproject.android", 0);
4419 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4420 // Sow the I2P not installed dialog if it is not already displayed.
4421 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4422 // Get a handle for the waiting for proxy alert dialog.
4423 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4425 // Display the I2P not installed alert dialog.
4426 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4431 case ProxyHelper.CUSTOM:
4432 // Set the app bar background to indicate proxying through Orbot is enabled.
4433 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4434 appBarLayout.setBackgroundResource(R.color.blue_50);
4436 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4441 // Reload the WebViews if requested and not waiting for the proxy.
4442 if (reloadWebViews && !waitingForProxy) {
4443 // Reload the WebViews.
4444 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4445 // Get the WebView tab fragment.
4446 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4448 // Get the fragment view.
4449 View fragmentView = webViewTabFragment.getView();
4451 // Only reload the WebViews if they exist.
4452 if (fragmentView != null) {
4453 // Get the nested scroll WebView from the tab fragment.
4454 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4456 // Reload the WebView.
4457 nestedScrollWebView.reload();
4463 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4464 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4465 if ((optionsMenu != null) && (currentWebView != null)) {
4466 // Update the privacy icon.
4467 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4468 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4469 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4470 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4471 } else { // All the dangerous features are disabled.
4472 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4475 // Get the current theme status.
4476 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4478 // Update the first-party cookies icon.
4479 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4480 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4481 } else { // First-party cookies are disabled.
4482 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4483 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4485 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4489 // Update the refresh icon.
4490 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4491 // Set the icon according to the theme.
4492 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4493 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4495 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4497 } else { // The stop icon is displayed.
4498 // Set the icon according to the theme.
4499 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4500 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
4502 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
4506 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4507 if (runInvalidateOptionsMenu) {
4508 invalidateOptionsMenu();
4513 private void highlightUrlText() {
4514 // Only highlight the URL text if the box is not currently selected.
4515 if (!urlEditText.hasFocus()) {
4516 // Get the URL string.
4517 String urlString = urlEditText.getText().toString();
4519 // Highlight the URL according to the protocol.
4520 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4521 // De-emphasize everything before the file name.
4522 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4523 } else { // This is a web URL.
4524 // Get the index of the `/` immediately after the domain name.
4525 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4527 // Create a base URL string.
4530 // Get the base URL.
4531 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4532 // Get the base URL.
4533 baseUrl = urlString.substring(0, endOfDomainName);
4534 } else { // There are no characters after the base URL.
4535 // Set the base URL to be the entire URL string.
4536 baseUrl = urlString;
4539 // Get the index of the last `.` in the domain.
4540 int lastDotIndex = baseUrl.lastIndexOf(".");
4542 // Get the index of the penultimate `.` in the domain.
4543 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4545 // Markup the beginning of the URL.
4546 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4547 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4549 // De-emphasize subdomains.
4550 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4551 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4553 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4554 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4555 // De-emphasize the protocol and the additional subdomains.
4556 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4557 } else { // There is only one subdomain in the domain name.
4558 // De-emphasize only the protocol.
4559 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4563 // De-emphasize the text after the domain name.
4564 if (endOfDomainName > 0) {
4565 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4571 private void loadBookmarksFolder() {
4572 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4573 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4575 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4576 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4578 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4579 // Inflate the individual item layout. `false` does not attach it to the root.
4580 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4584 public void bindView(View view, Context context, Cursor cursor) {
4585 // Get handles for the views.
4586 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4587 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4589 // Get the favorite icon byte array from the cursor.
4590 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4592 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4593 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4595 // Display the bitmap in `bookmarkFavoriteIcon`.
4596 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4598 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4599 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4600 bookmarkNameTextView.setText(bookmarkNameString);
4602 // Make the font bold for folders.
4603 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4604 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4605 } else { // Reset the font to default for normal bookmarks.
4606 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4611 // Get a handle for the bookmarks list view.
4612 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4614 // Populate the list view with the adapter.
4615 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4617 // Get a handle for the bookmarks title text view.
4618 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4620 // Set the bookmarks drawer title.
4621 if (currentBookmarksFolder.isEmpty()) {
4622 bookmarksTitleTextView.setText(R.string.bookmarks);
4624 bookmarksTitleTextView.setText(currentBookmarksFolder);
4628 private void openWithApp(String url) {
4629 // Create an open with app intent with `ACTION_VIEW`.
4630 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4632 // Set the URI but not the MIME type. This should open all available apps.
4633 openWithAppIntent.setData(Uri.parse(url));
4635 // Flag the intent to open in a new task.
4636 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4640 // Show the chooser.
4641 startActivity(openWithAppIntent);
4642 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4643 // Show a snackbar with the error.
4644 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4648 private void openWithBrowser(String url) {
4649 // Create an open with browser intent with `ACTION_VIEW`.
4650 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4652 // Set the URI and the MIME type. `"text/html"` should load browser options.
4653 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4655 // Flag the intent to open in a new task.
4656 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4660 // Show the chooser.
4661 startActivity(openWithBrowserIntent);
4662 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4663 // Show a snackbar with the error.
4664 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4668 private String sanitizeUrl(String url) {
4669 // Sanitize Google Analytics.
4670 if (sanitizeGoogleAnalytics) {
4672 if (url.contains("?utm_")) {
4673 url = url.substring(0, url.indexOf("?utm_"));
4677 if (url.contains("&utm_")) {
4678 url = url.substring(0, url.indexOf("&utm_"));
4682 // Sanitize Facebook Click IDs.
4683 if (sanitizeFacebookClickIds) {
4684 // Remove `?fbclid=`.
4685 if (url.contains("?fbclid=")) {
4686 url = url.substring(0, url.indexOf("?fbclid="));
4689 // Remove `&fbclid=`.
4690 if (url.contains("&fbclid=")) {
4691 url = url.substring(0, url.indexOf("&fbclid="));
4694 // Remove `?fbadid=`.
4695 if (url.contains("?fbadid=")) {
4696 url = url.substring(0, url.indexOf("?fbadid="));
4699 // Remove `&fbadid=`.
4700 if (url.contains("&fbadid=")) {
4701 url = url.substring(0, url.indexOf("&fbadid="));
4705 // Sanitize Twitter AMP redirects.
4706 if (sanitizeTwitterAmpRedirects) {
4708 if (url.contains("?amp=1")) {
4709 url = url.substring(0, url.indexOf("?amp=1"));
4713 // Return the sanitized URL.
4717 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4718 // Store the blocklists.
4719 easyList = combinedBlocklists.get(0);
4720 easyPrivacy = combinedBlocklists.get(1);
4721 fanboysAnnoyanceList = combinedBlocklists.get(2);
4722 fanboysSocialList = combinedBlocklists.get(3);
4723 ultraList = combinedBlocklists.get(4);
4724 ultraPrivacy = combinedBlocklists.get(5);
4726 // Check to see if the activity has been restarted with a saved state.
4727 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4728 // Add the first tab.
4729 addNewTab("", true);
4730 } else { // The activity has been restarted.
4731 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4732 for (int i = 0; i < savedStateArrayList.size(); i++) {
4734 tabLayout.addTab(tabLayout.newTab());
4737 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4739 // Remove the lint warning below that the current tab might be null.
4740 assert newTab != null;
4742 // Set a custom view on the new tab.
4743 newTab.setCustomView(R.layout.tab_custom_view);
4745 // Add the new page.
4746 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4749 // Reset the saved state variables.
4750 savedStateArrayList = null;
4751 savedNestedScrollWebViewStateArrayList = null;
4753 // Restore the selected tab position.
4754 if (savedTabPosition == 0) { // The first tab is selected.
4755 // Set the first page as the current WebView.
4756 setCurrentWebView(0);
4757 } else { // the first tab is not selected.
4758 // Move to the selected tab.
4759 webViewPager.setCurrentItem(savedTabPosition);
4762 // Get the intent that started the app.
4763 Intent intent = getIntent();
4765 // Reset the intent. This prevents a duplicate tab from being created on restart.
4766 setIntent(new Intent());
4768 // Get the information from the intent.
4769 String intentAction = intent.getAction();
4770 Uri intentUriData = intent.getData();
4771 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4773 // Determine if this is a web search.
4774 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4776 // 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.
4777 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4778 // Get the shared preferences.
4779 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4781 // Create a URL string.
4784 // If the intent action is a web search, perform the search.
4785 if (isWebSearch) { // The intent is a web search.
4786 // Create an encoded URL string.
4787 String encodedUrlString;
4789 // Sanitize the search input and convert it to a search.
4791 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4792 } catch (UnsupportedEncodingException exception) {
4793 encodedUrlString = "";
4796 // Add the base search URL.
4797 url = searchURL + encodedUrlString;
4798 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4799 // Set the intent data as the URL.
4800 url = intentUriData.toString();
4801 } else { // The intent contains a string, which might be a URL.
4802 // Set the intent string as the URL.
4803 url = intentStringExtra;
4806 // Add a new tab if specified in the preferences.
4807 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4808 // Set the loading new intent flag.
4809 loadingNewIntent = true;
4812 addNewTab(url, true);
4813 } else { // Load the URL in the current tab.
4815 loadUrl(currentWebView, url);
4821 public void addTab(View view) {
4822 // Add a new tab with a blank URL.
4823 addNewTab("", true);
4826 private void addNewTab(String url, boolean moveToTab) {
4827 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4828 urlEditText.clearFocus();
4830 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4831 int newTabNumber = tabLayout.getTabCount();
4834 tabLayout.addTab(tabLayout.newTab());
4837 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4839 // Remove the lint warning below that the current tab might be null.
4840 assert newTab != null;
4842 // Set a custom view on the new tab.
4843 newTab.setCustomView(R.layout.tab_custom_view);
4845 // Add the new WebView page.
4846 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4849 public void closeTab(View view) {
4850 // Run the command according to the number of tabs.
4851 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4852 // Close the current tab.
4854 } else { // There is only one tab open.
4859 private void closeCurrentTab() {
4860 // Get the current tab number.
4861 int currentTabNumber = tabLayout.getSelectedTabPosition();
4863 // Delete the current tab.
4864 tabLayout.removeTabAt(currentTabNumber);
4866 // Delete the current page. If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
4867 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4868 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4869 setCurrentWebView(currentTabNumber);
4872 // Expand the app bar if it is currently collapsed.
4873 appBarLayout.setExpanded(true);
4876 private void saveWebpageArchive(String filePath) {
4877 // Save the webpage archive.
4878 currentWebView.saveWebArchive(filePath);
4880 // Display a snackbar.
4881 Snackbar saveWebpageArchiveSnackbar = Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + filePath, Snackbar.LENGTH_SHORT);
4883 // Add an open option to the snackbar.
4884 saveWebpageArchiveSnackbar.setAction(R.string.open, (View view) -> {
4885 // Get a file for the file name string.
4886 File file = new File(filePath);
4888 // Declare a file URI variable.
4891 // Get the URI for the file according to the Android version.
4892 if (Build.VERSION.SDK_INT >= 24) { // Use a file provider.
4893 fileUri = FileProvider.getUriForFile(this, getString(R.string.file_provider), file);
4894 } else { // Get the raw file path URI.
4895 fileUri = Uri.fromFile(file);
4898 // Get a handle for the content resolver.
4899 ContentResolver contentResolver = getContentResolver();
4901 // Create an open intent with `ACTION_VIEW`.
4902 Intent openIntent = new Intent(Intent.ACTION_VIEW);
4904 // Set the URI and the MIME type.
4905 openIntent.setDataAndType(fileUri, contentResolver.getType(fileUri));
4907 // Allow the app to read the file URI.
4908 openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
4910 // Show the chooser.
4911 startActivity(Intent.createChooser(openIntent, getString(R.string.open)));
4914 // Show the snackbar.
4915 saveWebpageArchiveSnackbar.show();
4918 private void clearAndExit() {
4919 // Get a handle for the shared preferences.
4920 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4922 // Close the bookmarks cursor and database.
4923 bookmarksCursor.close();
4924 bookmarksDatabaseHelper.close();
4926 // Get the status of the clear everything preference.
4927 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4929 // Get a handle for the runtime.
4930 Runtime runtime = Runtime.getRuntime();
4932 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4933 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4934 String privateDataDirectoryString = getApplicationInfo().dataDir;
4937 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4938 // The command to remove cookies changed slightly in API 21.
4939 if (Build.VERSION.SDK_INT >= 21) {
4940 CookieManager.getInstance().removeAllCookies(null);
4942 CookieManager.getInstance().removeAllCookie();
4945 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4947 // Two commands must be used because `Runtime.exec()` does not like `*`.
4948 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4949 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4951 // Wait until the processes have finished.
4952 deleteCookiesProcess.waitFor();
4953 deleteCookiesJournalProcess.waitFor();
4954 } catch (Exception exception) {
4955 // Do nothing if an error is thrown.
4959 // Clear DOM storage.
4960 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4961 // Ask `WebStorage` to clear the DOM storage.
4962 WebStorage webStorage = WebStorage.getInstance();
4963 webStorage.deleteAllData();
4965 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4967 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4968 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4970 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4971 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4972 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4973 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4974 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4976 // Wait until the processes have finished.
4977 deleteLocalStorageProcess.waitFor();
4978 deleteIndexProcess.waitFor();
4979 deleteQuotaManagerProcess.waitFor();
4980 deleteQuotaManagerJournalProcess.waitFor();
4981 deleteDatabaseProcess.waitFor();
4982 } catch (Exception exception) {
4983 // Do nothing if an error is thrown.
4987 // Clear form data if the API < 26.
4988 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4989 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4990 webViewDatabase.clearFormData();
4992 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4994 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4995 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4996 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4998 // Wait until the processes have finished.
4999 deleteWebDataProcess.waitFor();
5000 deleteWebDataJournalProcess.waitFor();
5001 } catch (Exception exception) {
5002 // Do nothing if an error is thrown.
5006 // Clear the logcat.
5007 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
5009 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5010 Process process = Runtime.getRuntime().exec("logcat -b all -c");
5012 // Wait for the process to finish.
5014 } catch (IOException|InterruptedException exception) {
5020 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
5021 // Clear the cache from each WebView.
5022 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
5023 // Get the WebView tab fragment.
5024 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
5026 // Get the WebView fragment view.
5027 View webViewFragmentView = webViewTabFragment.getView();
5029 // Only clear the cache if the WebView exists.
5030 if (webViewFragmentView != null) {
5031 // Get the nested scroll WebView from the tab fragment.
5032 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
5034 // Clear the cache for this WebView.
5035 nestedScrollWebView.clearCache(true);
5039 // Manually delete the cache directories.
5041 // Delete the main cache directory.
5042 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
5044 // Delete the secondary `Service Worker` cache directory.
5045 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
5046 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5048 // Wait until the processes have finished.
5049 deleteCacheProcess.waitFor();
5050 deleteServiceWorkerProcess.waitFor();
5051 } catch (Exception exception) {
5052 // Do nothing if an error is thrown.
5056 // Wipe out each WebView.
5057 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
5058 // Get the WebView tab fragment.
5059 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
5061 // Get the WebView frame layout.
5062 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
5064 // Only wipe out the WebView if it exists.
5065 if (webViewFrameLayout != null) {
5066 // Get the nested scroll WebView from the tab fragment.
5067 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
5069 // Clear SSL certificate preferences for this WebView.
5070 nestedScrollWebView.clearSslPreferences();
5072 // Clear the back/forward history for this WebView.
5073 nestedScrollWebView.clearHistory();
5075 // Remove all the views from the frame layout.
5076 webViewFrameLayout.removeAllViews();
5078 // Destroy the internal state of the WebView.
5079 nestedScrollWebView.destroy();
5083 // Clear the custom headers.
5084 customHeaders.clear();
5086 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
5087 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
5088 if (clearEverything) {
5090 // Delete the folder.
5091 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
5093 // Wait until the process has finished.
5094 deleteAppWebviewProcess.waitFor();
5095 } catch (Exception exception) {
5096 // Do nothing if an error is thrown.
5100 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
5101 if (Build.VERSION.SDK_INT >= 21) {
5102 finishAndRemoveTask();
5107 // Remove the terminated program from RAM. The status code is `0`.
5111 public void bookmarksBack(View view) {
5112 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
5113 // close the bookmarks drawer.
5114 drawerLayout.closeDrawer(GravityCompat.END);
5115 } else { // A subfolder is displayed.
5116 // Place the former parent folder in `currentFolder`.
5117 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
5119 // Load the new folder.
5120 loadBookmarksFolder();
5124 private void setCurrentWebView(int pageNumber) {
5125 // Stop the swipe to refresh indicator if it is running
5126 swipeRefreshLayout.setRefreshing(false);
5128 // Get the WebView tab fragment.
5129 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
5131 // Get the fragment view.
5132 View webViewFragmentView = webViewTabFragment.getView();
5134 // Set the current WebView if the fragment view is not null.
5135 if (webViewFragmentView != null) { // The fragment has been populated.
5136 // Store the current WebView.
5137 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
5139 // Update the status of swipe to refresh.
5140 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
5141 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5142 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
5143 } else { // Swipe to refresh is disabled.
5144 // Disable the swipe refresh layout.
5145 swipeRefreshLayout.setEnabled(false);
5148 // Get a handle for the cookie manager.
5149 CookieManager cookieManager = CookieManager.getInstance();
5151 // Set the first-party cookie status.
5152 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
5154 // Update the privacy icons. `true` redraws the icons in the app bar.
5155 updatePrivacyIcons(true);
5157 // Get a handle for the input method manager.
5158 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5160 // Remove the lint warning below that the input method manager might be null.
5161 assert inputMethodManager != null;
5163 // Get the current URL.
5164 String url = currentWebView.getUrl();
5166 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5167 if (!loadingNewIntent) { // A new intent is not being loaded.
5168 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5169 // Display the hint in the URL edit text.
5170 urlEditText.setText("");
5172 // Request focus for the URL text box.
5173 urlEditText.requestFocus();
5175 // Display the keyboard.
5176 inputMethodManager.showSoftInput(urlEditText, 0);
5177 } else { // The WebView has a loaded URL.
5178 // Clear the focus from the URL text box.
5179 urlEditText.clearFocus();
5181 // Hide the soft keyboard.
5182 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5184 // Display the current URL in the URL text box.
5185 urlEditText.setText(url);
5187 // Highlight the URL text.
5190 } else { // A new intent is being loaded.
5191 // Reset the loading new intent tracker.
5192 loadingNewIntent = false;
5195 // Set the background to indicate the domain settings status.
5196 if (currentWebView.getDomainSettingsApplied()) {
5197 // Get the current theme status.
5198 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5200 // Set a green background on the URL relative layout to indicate that custom domain settings are being used.
5201 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
5202 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
5204 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
5207 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5209 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5210 // Create a handler to set the current WebView.
5211 Handler setCurrentWebViewHandler = new Handler();
5213 // Create a runnable to set the current WebView.
5214 Runnable setCurrentWebWebRunnable = () -> {
5215 // Set the current WebView.
5216 setCurrentWebView(pageNumber);
5219 // Try setting the current WebView again after 100 milliseconds.
5220 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5225 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5226 // Get a handle for the shared preferences.
5227 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5229 // Get the WebView theme.
5230 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5232 // Get the WebView theme entry values string array.
5233 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5235 // Apply the WebView theme if supported by the installed WebView.
5236 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5237 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5238 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5239 // Turn off the WebView dark mode.
5240 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5242 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5243 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5244 nestedScrollWebView.setVisibility(View.VISIBLE);
5245 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5246 // Turn on the WebView dark mode.
5247 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5248 } else { // The system default theme is selected.
5249 // Get the current system theme status.
5250 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5252 // Set the WebView theme according to the current system theme status.
5253 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5254 // Turn off the WebView dark mode.
5255 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5257 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5258 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5259 nestedScrollWebView.setVisibility(View.VISIBLE);
5260 } else { // The system is in night mode.
5261 // Turn on the WebView dark mode.
5262 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5267 // Get a handle for the activity
5268 Activity activity = this;
5270 // Get a handle for the input method manager.
5271 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5273 // Instantiate the blocklist helper.
5274 BlocklistHelper blocklistHelper = new BlocklistHelper();
5276 // Remove the lint warning below that the input method manager might be null.
5277 assert inputMethodManager != null;
5279 // Initialize the favorite icon.
5280 nestedScrollWebView.initializeFavoriteIcon();
5282 // Set the app bar scrolling.
5283 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5285 // Allow pinch to zoom.
5286 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5288 // Hide zoom controls.
5289 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5291 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5292 if (Build.VERSION.SDK_INT >= 21) {
5293 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5296 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5297 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5299 // Explicitly disable geolocation.
5300 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5302 // Create a double-tap gesture detector to toggle full-screen mode.
5303 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5304 // Override `onDoubleTap()`. All other events are handled using the default settings.
5306 public boolean onDoubleTap(MotionEvent event) {
5307 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5308 // Toggle the full screen browsing mode tracker.
5309 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5311 // Toggle the full screen browsing mode.
5312 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5313 // Hide the app bar if specified.
5315 // Close the find on page bar if it is visible.
5316 closeFindOnPage(null);
5318 // Hide the tab linear layout.
5319 tabsLinearLayout.setVisibility(View.GONE);
5321 // Hide the action bar.
5324 // Check to see if the app bar is normally scrolled.
5325 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5326 // Get the swipe refresh layout parameters.
5327 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5329 // Remove the off-screen scrolling layout.
5330 swipeRefreshLayoutParams.setBehavior(null);
5331 } else { // The app bar is not scrolled when it is displayed.
5332 // Remove the padding from the top of the swipe refresh layout.
5333 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5335 // The swipe refresh circle must be moved above the now removed status bar location.
5336 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5340 // Hide the banner ad in the free flavor.
5341 if (BuildConfig.FLAVOR.contentEquals("free")) {
5342 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5343 View adView = findViewById(R.id.adview);
5345 // Hide the banner ad.
5346 AdHelper.hideAd(adView);
5349 /* Hide the system bars.
5350 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5351 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5352 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5353 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5355 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5356 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5357 } else { // Switch to normal viewing mode.
5358 // Show the app bar if it was hidden.
5360 // Show the tab linear layout.
5361 tabsLinearLayout.setVisibility(View.VISIBLE);
5363 // Show the action bar.
5366 // Check to see if the app bar is normally scrolled.
5367 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5368 // Get the swipe refresh layout parameters.
5369 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5371 // Add the off-screen scrolling layout.
5372 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5373 } else { // The app bar is not scrolled when it is displayed.
5374 // The swipe refresh layout must be manually moved below the app bar layout.
5375 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5377 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5378 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5382 // Show the banner ad in the free flavor.
5383 if (BuildConfig.FLAVOR.contentEquals("free")) {
5384 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5385 View adView = findViewById(R.id.adview);
5387 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5388 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5391 // Remove the `SYSTEM_UI` flags from the root frame layout.
5392 rootFrameLayout.setSystemUiVisibility(0);
5395 // Consume the double-tap.
5397 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5403 // Pass all touch events on the WebView through the double-tap gesture detector.
5404 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5405 // Call `performClick()` on the view, which is required for accessibility.
5406 view.performClick();
5408 // Send the event to the gesture detector.
5409 return doubleTapGestureDetector.onTouchEvent(event);
5412 // Register the WebView for a context menu. This is used to see link targets and download images.
5413 registerForContextMenu(nestedScrollWebView);
5415 // Allow the downloading of files.
5416 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5417 // Define a formatted file size string.
5418 String formattedFileSizeString;
5420 // Process the content length if it contains data.
5421 if (contentLength > 0) { // The content length is greater than 0.
5422 // Format the content length as a string.
5423 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5424 } else { // The content length is not greater than 0.
5425 // Set the formatted file size string to be `unknown size`.
5426 formattedFileSizeString = getString(R.string.unknown_size);
5429 // Get the file name from the content disposition.
5430 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5432 // Instantiate the save dialog.
5433 DialogFragment saveDialogFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_URL, downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5434 nestedScrollWebView.getAcceptFirstPartyCookies());
5436 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5437 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5440 // Update the find on page count.
5441 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5442 // Get a handle for `findOnPageCountTextView`.
5443 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5446 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5447 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5448 // Set `findOnPageCountTextView` to `0/0`.
5449 findOnPageCountTextView.setText(R.string.zero_of_zero);
5450 } else if (isDoneCounting) { // There are matches.
5451 // `activeMatchOrdinal` is zero-based.
5452 int activeMatch = activeMatchOrdinal + 1;
5454 // Build the match string.
5455 String matchString = activeMatch + "/" + numberOfMatches;
5457 // Set `findOnPageCountTextView`.
5458 findOnPageCountTextView.setText(matchString);
5463 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5464 // 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.
5465 if (Build.VERSION.SDK_INT >= 23) {
5466 nestedScrollWebView.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
5467 if (nestedScrollWebView.getSwipeToRefresh()) {
5468 // Only enable swipe to refresh if the WebView is scrolled to the top.
5469 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5471 // Disable swipe to refresh.
5472 swipeRefreshLayout.setEnabled(false);
5475 // Reinforce the system UI visibility flags if in full screen browsing mode.
5476 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5477 if (inFullScreenBrowsingMode) {
5478 /* Hide the system bars.
5479 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5480 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5481 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5482 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5484 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5485 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5489 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5490 if (nestedScrollWebView.getSwipeToRefresh()) {
5491 // Only enable swipe to refresh if the WebView is scrolled to the top.
5492 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5494 // Disable swipe to refresh.
5495 swipeRefreshLayout.setEnabled(false);
5499 // Reinforce the system UI visibility flags if in full screen browsing mode.
5500 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5501 if (inFullScreenBrowsingMode) {
5502 /* Hide the system bars.
5503 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5504 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5505 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5506 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5508 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5509 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5514 // Set the web chrome client.
5515 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5516 // Update the progress bar when a page is loading.
5518 public void onProgressChanged(WebView view, int progress) {
5519 // Update the progress bar.
5520 progressBar.setProgress(progress);
5522 // Set the visibility of the progress bar.
5523 if (progress < 100) {
5524 // Show the progress bar.
5525 progressBar.setVisibility(View.VISIBLE);
5527 // Hide the progress bar.
5528 progressBar.setVisibility(View.GONE);
5530 //Stop the swipe to refresh indicator if it is running
5531 swipeRefreshLayout.setRefreshing(false);
5533 // 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.
5534 nestedScrollWebView.setVisibility(View.VISIBLE);
5538 // Set the favorite icon when it changes.
5540 public void onReceivedIcon(WebView view, Bitmap icon) {
5541 // Only update the favorite icon if the website has finished loading.
5542 if (progressBar.getVisibility() == View.GONE) {
5543 // Store the new favorite icon.
5544 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5546 // Get the current page position.
5547 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5549 // Get the current tab.
5550 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5552 // Check to see if the tab has been populated.
5554 // Get the custom view from the tab.
5555 View tabView = tab.getCustomView();
5557 // Check to see if the custom tab view has been populated.
5558 if (tabView != null) {
5559 // Get the favorite icon image view from the tab.
5560 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5562 // Display the favorite icon in the tab.
5563 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5569 // Save a copy of the title when it changes.
5571 public void onReceivedTitle(WebView view, String title) {
5572 // Get the current page position.
5573 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5575 // Get the current tab.
5576 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5578 // Only populate the title text view if the tab has been fully created.
5580 // Get the custom view from the tab.
5581 View tabView = tab.getCustomView();
5583 // Only populate the title text view if the tab view has been fully populated.
5584 if (tabView != null) {
5585 // Get the title text view from the tab.
5586 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5588 // Set the title according to the URL.
5589 if (title.equals("about:blank")) {
5590 // Set the title to indicate a new tab.
5591 tabTitleTextView.setText(R.string.new_tab);
5593 // Set the title as the tab text.
5594 tabTitleTextView.setText(title);
5600 // Enter full screen video.
5602 public void onShowCustomView(View video, CustomViewCallback callback) {
5603 // Set the full screen video flag.
5604 displayingFullScreenVideo = true;
5606 // Pause the ad if this is the free flavor.
5607 if (BuildConfig.FLAVOR.contentEquals("free")) {
5608 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5609 View adView = findViewById(R.id.adview);
5611 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5612 AdHelper.pauseAd(adView);
5615 // Hide the keyboard.
5616 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5618 // Hide the main content relative layout.
5619 mainContentRelativeLayout.setVisibility(View.GONE);
5621 /* Hide the system bars.
5622 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5623 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5624 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5625 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5627 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5628 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5630 // Disable the sliding drawers.
5631 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5633 // Add the video view to the full screen video frame layout.
5634 fullScreenVideoFrameLayout.addView(video);
5636 // Show the full screen video frame layout.
5637 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5639 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5640 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5643 // Exit full screen video.
5645 public void onHideCustomView() {
5646 // Re-enable the screen timeout.
5647 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5649 // Unset the full screen video flag.
5650 displayingFullScreenVideo = false;
5652 // Remove all the views from the full screen video frame layout.
5653 fullScreenVideoFrameLayout.removeAllViews();
5655 // Hide the full screen video frame layout.
5656 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5658 // Enable the sliding drawers.
5659 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5661 // Show the main content relative layout.
5662 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5664 // Apply the appropriate full screen mode flags.
5665 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5666 // Hide the app bar if specified.
5668 // Hide the tab linear layout.
5669 tabsLinearLayout.setVisibility(View.GONE);
5671 // Hide the action bar.
5675 // Hide the banner ad in the free flavor.
5676 if (BuildConfig.FLAVOR.contentEquals("free")) {
5677 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5678 View adView = findViewById(R.id.adview);
5680 // Hide the banner ad.
5681 AdHelper.hideAd(adView);
5684 /* Hide the system bars.
5685 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5686 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5687 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5688 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5690 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5691 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5692 } else { // Switch to normal viewing mode.
5693 // Remove the `SYSTEM_UI` flags from the root frame layout.
5694 rootFrameLayout.setSystemUiVisibility(0);
5697 // Reload the ad for the free flavor if not in full screen mode.
5698 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5699 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5700 View adView = findViewById(R.id.adview);
5702 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5703 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5709 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5710 // Show the file chooser if the device is running API >= 21.
5711 if (Build.VERSION.SDK_INT >= 21) {
5712 // Store the file path callback.
5713 fileChooserCallback = filePathCallback;
5715 // Create an intent to open a chooser based on the file chooser parameters.
5716 Intent fileChooserIntent = fileChooserParams.createIntent();
5718 // Get a handle for the package manager.
5719 PackageManager packageManager = getPackageManager();
5721 // Check to see if the file chooser intent resolves to an installed package.
5722 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5723 // Start the file chooser intent.
5724 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5725 } else { // The file chooser intent will cause a crash.
5726 // Create a generic intent to open a chooser.
5727 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5729 // Request an openable file.
5730 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5732 // Set the file type to everything.
5733 genericFileChooserIntent.setType("*/*");
5735 // Start the generic file chooser intent.
5736 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5743 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5744 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5745 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5747 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5748 // Sanitize the url.
5749 url = sanitizeUrl(url);
5751 // Handle the URL according to the type.
5752 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5753 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5754 loadUrl(nestedScrollWebView, url);
5756 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5757 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5759 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5760 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5761 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5763 // Parse the url and set it as the data for the intent.
5764 emailIntent.setData(Uri.parse(url));
5766 // Open the email program in a new task instead of as part of Privacy Browser.
5767 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5771 startActivity(emailIntent);
5772 } catch (ActivityNotFoundException exception) {
5773 // Display a snackbar.
5774 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5778 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5780 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5781 // Open the dialer and load the phone number, but wait for the user to place the call.
5782 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5784 // Add the phone number to the intent.
5785 dialIntent.setData(Uri.parse(url));
5787 // Open the dialer in a new task instead of as part of Privacy Browser.
5788 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5792 startActivity(dialIntent);
5793 } catch (ActivityNotFoundException exception) {
5794 // Display a snackbar.
5795 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5798 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5800 } else { // Load a system chooser to select an app that can handle the URL.
5801 // Open an app that can handle the URL.
5802 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5804 // Add the URL to the intent.
5805 genericIntent.setData(Uri.parse(url));
5807 // List all apps that can handle the URL instead of just opening the first one.
5808 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5810 // Open the app in a new task instead of as part of Privacy Browser.
5811 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5813 // Start the app or display a snackbar if no app is available to handle the URL.
5815 startActivity(genericIntent);
5816 } catch (ActivityNotFoundException exception) {
5817 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5820 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5825 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5827 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5828 // Check to see if the resource request is for the main URL.
5829 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5830 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5834 // 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.
5835 while (ultraPrivacy == null) {
5836 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5837 synchronized (this) {
5839 // Check to see if the blocklists have been populated after 100 ms.
5841 } catch (InterruptedException exception) {
5847 // Sanitize the URL.
5848 url = sanitizeUrl(url);
5850 // Create an empty web resource response to be used if the resource request is blocked.
5851 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5853 // Reset the whitelist results tracker.
5854 String[] whitelistResultStringArray = null;
5856 // Initialize the third party request tracker.
5857 boolean isThirdPartyRequest = false;
5859 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5860 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5862 // Store a copy of the current domain for use in later requests.
5863 String currentDomain = currentBaseDomain;
5865 // Nobody is happy when comparing null strings.
5866 if ((currentBaseDomain != null) && (url != null)) {
5867 // Convert the request URL to a URI.
5868 Uri requestUri = Uri.parse(url);
5870 // Get the request host name.
5871 String requestBaseDomain = requestUri.getHost();
5873 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5874 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5875 // Determine the current base domain.
5876 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5877 // Remove the first subdomain.
5878 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5881 // Determine the request base domain.
5882 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5883 // Remove the first subdomain.
5884 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5887 // Update the third party request tracker.
5888 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5892 // Get the current WebView page position.
5893 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5895 // Determine if the WebView is currently displayed.
5896 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5898 // Block third-party requests if enabled.
5899 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5900 // Add the result to the resource requests.
5901 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5903 // Increment the blocked requests counters.
5904 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5905 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5907 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5908 if (webViewDisplayed) {
5909 // Updating the UI must be run from the UI thread.
5910 activity.runOnUiThread(() -> {
5911 // Update the menu item titles.
5912 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5914 // Update the options menu if it has been populated.
5915 if (optionsMenu != null) {
5916 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5917 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5918 getString(R.string.block_all_third_party_requests));
5923 // Return an empty web resource response.
5924 return emptyWebResourceResponse;
5927 // Check UltraList if it is enabled.
5928 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5929 // Check the URL against UltraList.
5930 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5932 // Process the UltraList results.
5933 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5934 // Add the result to the resource requests.
5935 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5937 // Increment the blocked requests counters.
5938 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5939 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5941 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5942 if (webViewDisplayed) {
5943 // Updating the UI must be run from the UI thread.
5944 activity.runOnUiThread(() -> {
5945 // Update the menu item titles.
5946 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5948 // Update the options menu if it has been populated.
5949 if (optionsMenu != null) {
5950 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5951 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5956 // The resource request was blocked. Return an empty web resource response.
5957 return emptyWebResourceResponse;
5958 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5959 // Add a whitelist entry to the resource requests array.
5960 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5962 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5967 // Check UltraPrivacy if it is enabled.
5968 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5969 // Check the URL against UltraPrivacy.
5970 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5972 // Process the UltraPrivacy results.
5973 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5974 // Add the result to the resource requests.
5975 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5976 ultraPrivacyResults[5]});
5978 // Increment the blocked requests counters.
5979 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5980 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5982 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5983 if (webViewDisplayed) {
5984 // Updating the UI must be run from the UI thread.
5985 activity.runOnUiThread(() -> {
5986 // Update the menu item titles.
5987 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5989 // Update the options menu if it has been populated.
5990 if (optionsMenu != null) {
5991 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5992 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5997 // The resource request was blocked. Return an empty web resource response.
5998 return emptyWebResourceResponse;
5999 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
6000 // Add a whitelist entry to the resource requests array.
6001 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
6002 ultraPrivacyResults[5]});
6004 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
6009 // Check EasyList if it is enabled.
6010 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
6011 // Check the URL against EasyList.
6012 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
6014 // Process the EasyList results.
6015 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
6016 // Add the result to the resource requests.
6017 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
6019 // Increment the blocked requests counters.
6020 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6021 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
6023 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6024 if (webViewDisplayed) {
6025 // Updating the UI must be run from the UI thread.
6026 activity.runOnUiThread(() -> {
6027 // Update the menu item titles.
6028 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6030 // Update the options menu if it has been populated.
6031 if (optionsMenu != null) {
6032 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6033 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
6038 // The resource request was blocked. Return an empty web resource response.
6039 return emptyWebResourceResponse;
6040 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
6041 // Update the whitelist result string array tracker.
6042 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
6046 // Check EasyPrivacy if it is enabled.
6047 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
6048 // Check the URL against EasyPrivacy.
6049 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
6051 // Process the EasyPrivacy results.
6052 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
6053 // Add the result to the resource requests.
6054 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
6055 easyPrivacyResults[5]});
6057 // Increment the blocked requests counters.
6058 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6059 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
6061 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6062 if (webViewDisplayed) {
6063 // Updating the UI must be run from the UI thread.
6064 activity.runOnUiThread(() -> {
6065 // Update the menu item titles.
6066 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6068 // Update the options menu if it has been populated.
6069 if (optionsMenu != null) {
6070 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6071 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
6076 // The resource request was blocked. Return an empty web resource response.
6077 return emptyWebResourceResponse;
6078 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
6079 // Update the whitelist result string array tracker.
6080 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
6084 // Check Fanboy’s Annoyance List if it is enabled.
6085 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
6086 // Check the URL against Fanboy's Annoyance List.
6087 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
6089 // Process the Fanboy's Annoyance List results.
6090 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
6091 // Add the result to the resource requests.
6092 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
6093 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
6095 // Increment the blocked requests counters.
6096 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6097 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
6099 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6100 if (webViewDisplayed) {
6101 // Updating the UI must be run from the UI thread.
6102 activity.runOnUiThread(() -> {
6103 // Update the menu item titles.
6104 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6106 // Update the options menu if it has been populated.
6107 if (optionsMenu != null) {
6108 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6109 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
6110 getString(R.string.fanboys_annoyance_list));
6115 // The resource request was blocked. Return an empty web resource response.
6116 return emptyWebResourceResponse;
6117 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
6118 // Update the whitelist result string array tracker.
6119 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
6120 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
6122 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
6123 // Check the URL against Fanboy's Annoyance List.
6124 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
6126 // Process the Fanboy's Social Blocking List results.
6127 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
6128 // Add the result to the resource requests.
6129 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6130 fanboysSocialListResults[4], fanboysSocialListResults[5]});
6132 // Increment the blocked requests counters.
6133 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6134 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
6136 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6137 if (webViewDisplayed) {
6138 // Updating the UI must be run from the UI thread.
6139 activity.runOnUiThread(() -> {
6140 // Update the menu item titles.
6141 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6143 // Update the options menu if it has been populated.
6144 if (optionsMenu != null) {
6145 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6146 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
6147 getString(R.string.fanboys_social_blocking_list));
6152 // The resource request was blocked. Return an empty web resource response.
6153 return emptyWebResourceResponse;
6154 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
6155 // Update the whitelist result string array tracker.
6156 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6157 fanboysSocialListResults[4], fanboysSocialListResults[5]};
6161 // Add the request to the log because it hasn't been processed by any of the previous checks.
6162 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
6163 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
6164 } else { // The request didn't match any blocklist entry. Log it as a default request.
6165 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
6168 // The resource request has not been blocked. `return null` loads the requested resource.
6172 // Handle HTTP authentication requests.
6174 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
6175 // Store the handler.
6176 nestedScrollWebView.setHttpAuthHandler(handler);
6178 // Instantiate an HTTP authentication dialog.
6179 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
6181 // Show the HTTP authentication dialog.
6182 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
6186 public void onPageStarted(WebView view, String url, Bitmap favicon) {
6187 // Get the preferences.
6188 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
6190 // 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.
6191 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6192 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6193 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6195 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6196 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6198 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6199 appBarHeight = appBarLayout.getHeight();
6201 // The swipe refresh layout must be manually moved below the app bar layout.
6202 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6204 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6205 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6208 // Reset the list of resource requests.
6209 nestedScrollWebView.clearResourceRequests();
6211 // Reset the requests counters.
6212 nestedScrollWebView.resetRequestsCounters();
6214 // Get the current page position.
6215 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6217 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6218 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6219 // Display the formatted URL text.
6220 urlEditText.setText(url);
6222 // Apply text highlighting to `urlTextBox`.
6225 // Hide the keyboard.
6226 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6229 // Reset the list of host IP addresses.
6230 nestedScrollWebView.clearCurrentIpAddresses();
6232 // Get a URI for the current URL.
6233 Uri currentUri = Uri.parse(url);
6235 // Get the IP addresses for the host.
6236 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6238 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6239 if (optionsMenu != null) {
6241 optionsRefreshMenuItem.setTitle(R.string.stop);
6243 // Get the app bar and theme preferences.
6244 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6246 // If the icon is displayed in the AppBar, set it according to the theme.
6247 if (displayAdditionalAppBarIcons) {
6248 // Get the current theme status.
6249 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6251 // Set the stop icon according to the theme.
6252 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6253 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
6255 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
6262 public void onPageFinished(WebView view, String url) {
6263 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6264 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6265 CookieManager.getInstance().flush();
6268 // Update the Refresh menu item if the options menu has been created.
6269 if (optionsMenu != null) {
6270 // Reset the Refresh title.
6271 optionsRefreshMenuItem.setTitle(R.string.refresh);
6273 // Get the app bar and theme preferences.
6274 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6276 // If the icon is displayed in the app bar, reset it according to the theme.
6277 if (displayAdditionalAppBarIcons) {
6278 // Get the current theme status.
6279 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6281 // Set the icon according to the theme.
6282 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6283 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6285 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6290 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6291 if (incognitoModeEnabled) {
6292 // Clear the cache. `true` includes disk files.
6293 nestedScrollWebView.clearCache(true);
6295 // Clear the back/forward history.
6296 nestedScrollWebView.clearHistory();
6298 // Manually delete cache folders.
6300 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6301 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6302 String privateDataDirectoryString = getApplicationInfo().dataDir;
6304 // Delete the main cache directory.
6305 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6307 // Delete the secondary `Service Worker` cache directory.
6308 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6309 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6310 } catch (IOException exception) {
6311 // Do nothing if an error is thrown.
6314 // Clear the logcat.
6316 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6317 Runtime.getRuntime().exec("logcat -b all -c");
6318 } catch (IOException exception) {
6323 // Get the current page position.
6324 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6326 // 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.
6327 String currentUrl = nestedScrollWebView.getUrl();
6329 // Get the current tab.
6330 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6332 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6333 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6334 // Probably some sort of race condition when Privacy Browser is being resumed.
6335 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6336 // Check to see if the URL is `about:blank`.
6337 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6338 // Display the hint in the URL edit text.
6339 urlEditText.setText("");
6341 // Request focus for the URL text box.
6342 urlEditText.requestFocus();
6344 // Display the keyboard.
6345 inputMethodManager.showSoftInput(urlEditText, 0);
6347 // Apply the domain settings. This clears any settings from the previous domain.
6348 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6350 // Only populate the title text view if the tab has been fully created.
6352 // Get the custom view from the tab.
6353 View tabView = tab.getCustomView();
6355 // Remove the incorrect warning below that the current tab view might be null.
6356 assert tabView != null;
6358 // Get the title text view from the tab.
6359 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6361 // Set the title as the tab text.
6362 tabTitleTextView.setText(R.string.new_tab);
6364 } else { // The WebView has loaded a webpage.
6365 // Update the URL edit text if it is not currently being edited.
6366 if (!urlEditText.hasFocus()) {
6367 // 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.
6368 String sanitizedUrl = sanitizeUrl(currentUrl);
6370 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6371 urlEditText.setText(sanitizedUrl);
6373 // Apply text highlighting to the URL.
6377 // Only populate the title text view if the tab has been fully created.
6379 // Get the custom view from the tab.
6380 View tabView = tab.getCustomView();
6382 // Remove the incorrect warning below that the current tab view might be null.
6383 assert tabView != null;
6385 // Get the title text view from the tab.
6386 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6388 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6389 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6395 // Handle SSL Certificate errors.
6397 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6398 // Get the current website SSL certificate.
6399 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6401 // Extract the individual pieces of information from the current website SSL certificate.
6402 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6403 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6404 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6405 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6406 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6407 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6408 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6409 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6411 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6412 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6413 // Get the pinned SSL certificate.
6414 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6416 // Extract the arrays from the array list.
6417 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6418 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6420 // Check if the current SSL certificate matches the pinned certificate.
6421 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6422 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6423 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6424 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6426 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6429 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6430 // Store the SSL error handler.
6431 nestedScrollWebView.setSslErrorHandler(handler);
6433 // Instantiate an SSL certificate error alert dialog.
6434 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6436 // Show the SSL certificate error dialog.
6437 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6442 // Check to see if the state is being restored.
6443 if (restoringState) { // The state is being restored.
6444 // Resume the nested scroll WebView JavaScript timers.
6445 nestedScrollWebView.resumeTimers();
6446 } else if (pageNumber == 0) { // The first page is being loaded.
6447 // Set this nested scroll WebView as the current WebView.
6448 currentWebView = nestedScrollWebView;
6450 // Initialize the URL to load string.
6451 String urlToLoadString;
6453 // Get the intent that started the app.
6454 Intent launchingIntent = getIntent();
6456 // Reset the intent. This prevents a duplicate tab from being created on restart.
6457 setIntent(new Intent());
6459 // Get the information from the intent.
6460 String launchingIntentAction = launchingIntent.getAction();
6461 Uri launchingIntentUriData = launchingIntent.getData();
6462 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6464 // Parse the launching intent URL.
6465 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6466 // Create an encoded URL string.
6467 String encodedUrlString;
6469 // Sanitize the search input and convert it to a search.
6471 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6472 } catch (UnsupportedEncodingException exception) {
6473 encodedUrlString = "";
6476 // Store the web search as the URL to load.
6477 urlToLoadString = searchURL + encodedUrlString;
6478 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6479 // Store the URI as a URL.
6480 urlToLoadString = launchingIntentUriData.toString();
6481 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6483 urlToLoadString = launchingIntentStringExtra;
6484 } else if (!url.equals("")) { // The activity has been restarted.
6485 // Load the saved URL.
6486 urlToLoadString = url;
6487 } else { // The is no URL in the intent.
6488 // Store the homepage to be loaded.
6489 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6492 // Load the website if not waiting for the proxy.
6493 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6494 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6495 } else { // Load the URL.
6496 loadUrl(nestedScrollWebView, urlToLoadString);
6499 // 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.
6500 // 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.
6501 setIntent(new Intent());
6502 } else { // This is not the first tab.
6504 loadUrl(nestedScrollWebView, url);
6506 // Set the focus and display the keyboard if the URL is blank.
6507 if (url.equals("")) {
6508 // Request focus for the URL text box.
6509 urlEditText.requestFocus();
6511 // Create a display keyboard handler.
6512 Handler displayKeyboardHandler = new Handler();
6514 // Create a display keyboard runnable.
6515 Runnable displayKeyboardRunnable = () -> {
6516 // Display the keyboard.
6517 inputMethodManager.showSoftInput(urlEditText, 0);
6520 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6521 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);