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 ActionBar actionBar;
330 private LinearLayout findOnPageLinearLayout;
331 private LinearLayout tabsLinearLayout;
332 private TabLayout tabLayout;
333 private SwipeRefreshLayout swipeRefreshLayout;
334 private ViewPager webViewPager;
335 private FrameLayout fullScreenVideoFrameLayout;
337 // Declare the class menus.
338 private Menu optionsMenu;
340 // Declare the class menu items.
341 private MenuItem navigationBackMenuItem;
342 private MenuItem navigationForwardMenuItem;
343 private MenuItem navigationHistoryMenuItem;
344 private MenuItem navigationRequestsMenuItem;
345 private MenuItem optionsPrivacyMenuItem;
346 private MenuItem optionsRefreshMenuItem;
347 private MenuItem optionsFirstPartyCookiesMenuItem;
348 private MenuItem optionsThirdPartyCookiesMenuItem;
349 private MenuItem optionsDomStorageMenuItem;
350 private MenuItem optionsSaveFormDataMenuItem;
351 private MenuItem optionsClearDataMenuItem;
352 private MenuItem optionsClearCookiesMenuItem;
353 private MenuItem optionsClearDomStorageMenuItem;
354 private MenuItem optionsClearFormDataMenuItem;
355 private MenuItem optionsBlocklistsMenuItem;
356 private MenuItem optionsEasyListMenuItem;
357 private MenuItem optionsEasyPrivacyMenuItem;
358 private MenuItem optionsFanboysAnnoyanceListMenuItem;
359 private MenuItem optionsFanboysSocialBlockingListMenuItem;
360 private MenuItem optionsUltraListMenuItem;
361 private MenuItem optionsUltraPrivacyMenuItem;
362 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
363 private MenuItem optionsProxyMenuItem;
364 private MenuItem optionsProxyNoneMenuItem;
365 private MenuItem optionsProxyTorMenuItem;
366 private MenuItem optionsProxyI2pMenuItem;
367 private MenuItem optionsProxyCustomMenuItem;
368 private MenuItem optionsUserAgentMenuItem;
369 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
370 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
371 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
372 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
373 private MenuItem optionsUserAgentSafariOnIosMenuItem;
374 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
375 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
376 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
377 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
378 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
379 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
380 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
381 private MenuItem optionsUserAgentCustomMenuItem;
382 private MenuItem optionsSwipeToRefreshMenuItem;
383 private MenuItem optionsWideViewportMenuItem;
384 private MenuItem optionsDisplayImagesMenuItem;
385 private MenuItem optionsDarkWebViewMenuItem;
386 private MenuItem optionsFontSizeMenuItem;
387 private MenuItem optionsAddOrEditDomainMenuItem;
390 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
391 @SuppressLint("ClickableViewAccessibility")
392 protected void onCreate(Bundle savedInstanceState) {
393 // Run the default commands.
394 super.onCreate(savedInstanceState);
396 // Check to see if the activity has been restarted.
397 if (savedInstanceState != null) {
398 // Store the saved instance state variables.
399 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
400 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
401 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
402 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
405 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
406 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
408 // Get a handle for the shared preferences.
409 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
411 // Get the screenshot preference.
412 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
413 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
415 // Get the theme entry values string array.
416 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
418 // 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.
419 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
420 // Apply the light theme.
421 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
422 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
423 // Apply the dark theme.
424 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
425 } else { // The system default theme is selected.
426 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
427 // Follow the system default theme.
428 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
429 } else { // The system default theme is not supported.
430 // Follow the battery saver mode.
431 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
435 // Disable screenshots if not allowed.
436 if (!allowScreenshots) {
437 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
440 // 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.
441 if (Build.VERSION.SDK_INT >= 21) {
442 WebView.enableSlowWholeDocumentDraw();
446 setTheme(R.style.PrivacyBrowser);
448 // Set the content view.
449 setContentView(R.layout.main_framelayout);
451 // Get handles for the views.
452 rootFrameLayout = findViewById(R.id.root_framelayout);
453 drawerLayout = findViewById(R.id.drawerlayout);
454 mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
455 appBarLayout = findViewById(R.id.appbar_layout);
456 toolbar = findViewById(R.id.toolbar);
457 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
458 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
459 tabLayout = findViewById(R.id.tablayout);
460 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
461 webViewPager = findViewById(R.id.webviewpager);
462 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
464 // Get a handle for the navigation view.
465 NavigationView navigationView = findViewById(R.id.navigationview);
467 // Get a handle for the navigation menu.
468 Menu navigationMenu = navigationView.getMenu();
470 // Get handles for the navigation menu items.
471 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
472 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
473 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
474 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
476 // Listen for touches on the navigation menu.
477 navigationView.setNavigationItemSelectedListener(this);
479 // Get a handle for the app compat delegate.
480 AppCompatDelegate appCompatDelegate = getDelegate();
482 // Set the support action bar.
483 appCompatDelegate.setSupportActionBar(toolbar);
485 // Get a handle for the action bar.
486 actionBar = appCompatDelegate.getSupportActionBar();
488 // Remove the incorrect lint warning below that the action bar might be null.
489 assert actionBar != null;
491 // Add the custom layout, which shows the URL text bar.
492 actionBar.setCustomView(R.layout.url_app_bar);
493 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
495 // Create the hamburger icon at the start of the AppBar.
496 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
498 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
499 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
501 // Initialize the web view pager adapter.
502 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
504 // Set the pager adapter on the web view pager.
505 webViewPager.setAdapter(webViewPagerAdapter);
507 // Store up to 100 tabs in memory.
508 webViewPager.setOffscreenPageLimit(100);
510 // Initialize the app.
513 // Apply the app settings from the shared preferences.
516 // Populate the blocklists.
517 populateBlocklists = new PopulateBlocklists(this, this).execute();
521 protected void onNewIntent(Intent intent) {
522 // Run the default commands.
523 super.onNewIntent(intent);
525 // Replace the intent that started the app with this one.
528 // Check to see if the app is being restarted from a saved state.
529 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
530 // Get the information from the intent.
531 String intentAction = intent.getAction();
532 Uri intentUriData = intent.getData();
533 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
535 // Determine if this is a web search.
536 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
538 // 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.
539 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
540 // Get the shared preferences.
541 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
543 // Create a URL string.
546 // If the intent action is a web search, perform the search.
547 if (isWebSearch) { // The intent is a web search.
548 // Create an encoded URL string.
549 String encodedUrlString;
551 // Sanitize the search input and convert it to a search.
553 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
554 } catch (UnsupportedEncodingException exception) {
555 encodedUrlString = "";
558 // Add the base search URL.
559 url = searchURL + encodedUrlString;
560 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
561 // Set the intent data as the URL.
562 url = intentUriData.toString();
563 } else { // The intent contains a string, which might be a URL.
564 // Set the intent string as the URL.
565 url = intentStringExtra;
568 // Add a new tab if specified in the preferences.
569 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
570 // Set the loading new intent flag.
571 loadingNewIntent = true;
574 addNewTab(url, true);
575 } else { // Load the URL in the current tab.
577 loadUrl(currentWebView, url);
580 // Close the navigation drawer if it is open.
581 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
582 drawerLayout.closeDrawer(GravityCompat.START);
585 // Close the bookmarks drawer if it is open.
586 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
587 drawerLayout.closeDrawer(GravityCompat.END);
594 public void onRestart() {
595 // Run the default commands.
598 // Apply the app settings if returning from the Settings activity.
599 if (reapplyAppSettingsOnRestart) {
600 // Reset the reapply app settings on restart tracker.
601 reapplyAppSettingsOnRestart = false;
603 // Apply the app settings.
607 // Apply the domain settings if returning from the settings or domains activity.
608 if (reapplyDomainSettingsOnRestart) {
609 // Reset the reapply domain settings on restart tracker.
610 reapplyDomainSettingsOnRestart = false;
612 // Reapply the domain settings for each tab.
613 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
614 // Get the WebView tab fragment.
615 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
617 // Get the fragment view.
618 View fragmentView = webViewTabFragment.getView();
620 // Only reload the WebViews if they exist.
621 if (fragmentView != null) {
622 // Get the nested scroll WebView from the tab fragment.
623 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
625 // Reset the current domain name so the domain settings will be reapplied.
626 nestedScrollWebView.resetCurrentDomainName();
628 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
629 if (nestedScrollWebView.getUrl() != null) {
630 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
636 // Update the bookmarks drawer if returning from the Bookmarks activity.
637 if (restartFromBookmarksActivity) {
638 // Close the bookmarks drawer.
639 drawerLayout.closeDrawer(GravityCompat.END);
641 // Reload the bookmarks drawer.
642 loadBookmarksFolder();
644 // Reset `restartFromBookmarksActivity`.
645 restartFromBookmarksActivity = false;
648 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
649 updatePrivacyIcons(true);
652 // `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.
654 public void onStart() {
655 // Run the default commands.
658 // Resume any WebViews.
659 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
660 // Get the WebView tab fragment.
661 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
663 // Get the fragment view.
664 View fragmentView = webViewTabFragment.getView();
666 // Only resume the WebViews if they exist (they won't when the app is first created).
667 if (fragmentView != null) {
668 // Get the nested scroll WebView from the tab fragment.
669 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
671 // Resume the nested scroll WebView.
672 nestedScrollWebView.onResume();
676 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
677 if (currentWebView != null) {
678 currentWebView.resumeTimers();
681 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
682 if (!proxyMode.equals(ProxyHelper.NONE)) {
686 // Reapply any system UI flags and the ad in the free flavor.
687 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
688 /* Hide the system bars.
689 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
690 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
691 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
692 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
694 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
695 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
696 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
697 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
698 View adView = findViewById(R.id.adview);
701 AdHelper.resumeAd(adView);
705 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
707 public void onStop() {
708 // Run the default commands.
711 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
712 // Get the WebView tab fragment.
713 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
715 // Get the fragment view.
716 View fragmentView = webViewTabFragment.getView();
718 // Only pause the WebViews if they exist (they won't when the app is first created).
719 if (fragmentView != null) {
720 // Get the nested scroll WebView from the tab fragment.
721 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
723 // Pause the nested scroll WebView.
724 nestedScrollWebView.onPause();
728 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
729 if (currentWebView != null) {
730 currentWebView.pauseTimers();
733 // Pause the ad or it will continue to consume resources in the background on the free flavor.
734 if (BuildConfig.FLAVOR.contentEquals("free")) {
735 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
736 View adView = findViewById(R.id.adview);
739 AdHelper.pauseAd(adView);
744 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
745 // Run the default commands.
746 super.onSaveInstanceState(savedInstanceState);
748 // Create the saved state array lists.
749 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
750 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
752 // Get the URLs from each tab.
753 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
754 // Get the WebView tab fragment.
755 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
757 // Get the fragment view.
758 View fragmentView = webViewTabFragment.getView();
760 if (fragmentView != null) {
761 // Get the nested scroll WebView from the tab fragment.
762 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
764 // Create saved state bundle.
765 Bundle savedStateBundle = new Bundle();
767 // Get the current states.
768 nestedScrollWebView.saveState(savedStateBundle);
769 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
771 // Store the saved states in the array lists.
772 savedStateArrayList.add(savedStateBundle);
773 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
777 // Get the current tab position.
778 int currentTabPosition = tabLayout.getSelectedTabPosition();
780 // Store the saved states in the bundle.
781 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
782 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
783 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
784 savedInstanceState.putString(PROXY_MODE, proxyMode);
788 public void onDestroy() {
789 // Unregister the orbot status broadcast receiver if it exists.
790 if (orbotStatusBroadcastReceiver != null) {
791 this.unregisterReceiver(orbotStatusBroadcastReceiver);
794 // Close the bookmarks cursor if it exists.
795 if (bookmarksCursor != null) {
796 bookmarksCursor.close();
799 // Close the bookmarks database if it exists.
800 if (bookmarksDatabaseHelper != null) {
801 bookmarksDatabaseHelper.close();
804 // Stop populating the blocklists if the AsyncTask is running in the background.
805 if (populateBlocklists != null) {
806 populateBlocklists.cancel(true);
809 // Run the default commands.
814 public boolean onCreateOptionsMenu(Menu menu) {
815 // Inflate the menu. This adds items to the action bar if it is present.
816 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
818 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
821 // Get handles for the class menu items.
822 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
823 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
824 optionsFirstPartyCookiesMenuItem = menu.findItem(R.id.first_party_cookies);
825 optionsThirdPartyCookiesMenuItem = menu.findItem(R.id.third_party_cookies);
826 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
827 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
828 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
829 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
830 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
831 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
832 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
833 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
834 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
835 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
836 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
837 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
838 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
839 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
840 optionsProxyMenuItem = menu.findItem(R.id.proxy);
841 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
842 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
843 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
844 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
845 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
846 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
847 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
848 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
849 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
850 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
851 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
852 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
853 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
854 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
855 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
856 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
857 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
858 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
859 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
860 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
861 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
862 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
863 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
864 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
866 // Get handles for the method menu items.
867 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
868 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
870 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
871 updatePrivacyIcons(false);
873 // Only display third-party cookies if API >= 21
874 optionsThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
876 // Only display the form data menu items if the API < 26.
877 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
878 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
880 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
881 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
883 // Only display the dark WebView menu item if API >= 21.
884 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
886 // Only show Ad Consent if this is the free flavor.
887 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
889 // Get the shared preferences.
890 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
892 // Get the dark theme and app bar preferences.
893 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
895 // 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.
896 if (displayAdditionalAppBarIcons) {
897 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
898 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
899 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
900 } else { //Do not display the additional icons.
901 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
902 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
903 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
906 // Replace Refresh with Stop if a URL is already loading.
907 if (currentWebView != null && currentWebView.getProgress() != 100) {
909 optionsRefreshMenuItem.setTitle(R.string.stop);
911 // Set the icon if it is displayed in the app bar.
912 if (displayAdditionalAppBarIcons) {
913 // Get the current theme status.
914 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
916 // Set the icon according to the current theme status.
917 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
918 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
920 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
930 public boolean onPrepareOptionsMenu(Menu menu) {
931 // Get a handle for the cookie manager.
932 CookieManager cookieManager = CookieManager.getInstance();
934 // Initialize the current user agent string and the font size.
935 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
938 // 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.
939 if (currentWebView != null) {
940 // Set the add or edit domain text.
941 if (currentWebView.getDomainSettingsApplied()) {
942 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
944 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
947 // Get the current user agent from the WebView.
948 currentUserAgent = currentWebView.getSettings().getUserAgentString();
950 // Get the current font size from the
951 fontSize = currentWebView.getSettings().getTextZoom();
953 // Set the status of the menu item checkboxes.
954 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
955 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
956 optionsEasyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
957 optionsEasyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
958 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
959 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
960 optionsUltraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
961 optionsUltraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
962 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
963 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
964 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
965 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
967 // Initialize the display names for the blocklists with the number of blocked requests.
968 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
969 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
970 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
971 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
972 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
973 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
974 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
975 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
977 // Only modify third-party cookies if the API >= 21.
978 if (Build.VERSION.SDK_INT >= 21) {
979 // Set the status of the third-party cookies checkbox.
980 optionsThirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
982 // Enable third-party cookies if first-party cookies are enabled.
983 optionsThirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
986 // Enable DOM Storage if JavaScript is enabled.
987 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
989 // Set the checkbox status for dark WebView if the WebView supports it.
990 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
991 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
995 // Set the checked status of the first party cookies menu item.
996 optionsFirstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
998 // Enable Clear Cookies if there are any.
999 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1001 // 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`.
1002 String privateDataDirectoryString = getApplicationInfo().dataDir;
1004 // Get a count of the number of files in the Local Storage directory.
1005 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1006 int localStorageDirectoryNumberOfFiles = 0;
1007 if (localStorageDirectory.exists()) {
1008 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1009 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1012 // Get a count of the number of files in the IndexedDB directory.
1013 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1014 int indexedDBDirectoryNumberOfFiles = 0;
1015 if (indexedDBDirectory.exists()) {
1016 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1017 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1020 // Enable Clear DOM Storage if there is any.
1021 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1023 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1024 if (Build.VERSION.SDK_INT < 26) {
1025 // Get the WebView database.
1026 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1028 // Enable the clear form data menu item if there is anything to clear.
1029 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1032 // Enable Clear Data if any of the submenu items are enabled.
1033 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1035 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1036 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1038 // Set the proxy title and check the applied proxy.
1039 switch (proxyMode) {
1040 case ProxyHelper.NONE:
1041 // Set the proxy title.
1042 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1044 // Check the proxy None radio button.
1045 optionsProxyNoneMenuItem.setChecked(true);
1048 case ProxyHelper.TOR:
1049 // Set the proxy title.
1050 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1052 // Check the proxy Tor radio button.
1053 optionsProxyTorMenuItem.setChecked(true);
1056 case ProxyHelper.I2P:
1057 // Set the proxy title.
1058 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1060 // Check the proxy I2P radio button.
1061 optionsProxyI2pMenuItem.setChecked(true);
1064 case ProxyHelper.CUSTOM:
1065 // Set the proxy title.
1066 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1068 // Check the proxy Custom radio button.
1069 optionsProxyCustomMenuItem.setChecked(true);
1073 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1074 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1075 // Update the user agent menu item title.
1076 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1078 // Select the Privacy Browser radio box.
1079 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1080 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1081 // Update the user agent menu item title.
1082 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1084 // Select the WebView Default radio box.
1085 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1086 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1087 // Update the user agent menu item title.
1088 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1090 // Select the Firefox on Android radio box.
1091 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1092 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1093 // Update the user agent menu item title.
1094 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1096 // Select the Chrome on Android radio box.
1097 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1098 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1099 // Update the user agent menu item title.
1100 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1102 // Select the Safari on iOS radio box.
1103 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1104 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1105 // Update the user agent menu item title.
1106 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1108 // Select the Firefox on Linux radio box.
1109 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1110 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1111 // Update the user agent menu item title.
1112 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1114 // Select the Chromium on Linux radio box.
1115 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1116 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1117 // Update the user agent menu item title.
1118 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1120 // Select the Firefox on Windows radio box.
1121 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1122 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1123 // Update the user agent menu item title.
1124 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1126 // Select the Chrome on Windows radio box.
1127 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1128 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1129 // Update the user agent menu item title.
1130 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1132 // Select the Edge on Windows radio box.
1133 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1134 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1135 // Update the user agent menu item title.
1136 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1138 // Select the Internet on Windows radio box.
1139 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1140 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1141 // Update the user agent menu item title.
1142 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1144 // Select the Safari on macOS radio box.
1145 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1146 } else { // Custom user agent.
1147 // Update the user agent menu item title.
1148 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1150 // Select the Custom radio box.
1151 optionsUserAgentCustomMenuItem.setChecked(true);
1154 // Set the font size title.
1155 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1157 // Run all the other default commands.
1158 super.onPrepareOptionsMenu(menu);
1160 // Display the menu.
1165 public boolean onOptionsItemSelected(MenuItem menuItem) {
1166 // Get a handle for the shared preferences.
1167 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1169 // Get a handle for the cookie manager.
1170 CookieManager cookieManager = CookieManager.getInstance();
1172 // Get the selected menu item ID.
1173 int menuItemId = menuItem.getItemId();
1175 // Run the commands that correlate to the selected menu item.
1176 if (menuItemId == R.id.javascript) { // JavaScript.
1177 // Toggle the JavaScript status.
1178 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1180 // Update the privacy icon.
1181 updatePrivacyIcons(true);
1183 // Display a `Snackbar`.
1184 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1185 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1186 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1187 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1188 } else { // Privacy mode.
1189 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1192 // Reload the current WebView.
1193 currentWebView.reload();
1195 // Consume the event.
1197 } else if (menuItemId == R.id.refresh) { // Refresh.
1198 // Run the command that correlates to the current status of the menu item.
1199 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1200 // Reload the current WebView.
1201 currentWebView.reload();
1202 } else { // The stop button was pushed.
1203 // Stop the loading of the WebView.
1204 currentWebView.stopLoading();
1207 // Consume the event.
1209 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1210 // Open the bookmarks drawer.
1211 drawerLayout.openDrawer(GravityCompat.END);
1213 // Consume the event.
1215 } else if (menuItemId == R.id.first_party_cookies) { // First-party cookies.
1216 // Switch the first-party cookie status.
1217 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1219 // Store the first-party cookie status.
1220 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1222 // Update the menu checkbox.
1223 menuItem.setChecked(cookieManager.acceptCookie());
1225 // Update the privacy icon.
1226 updatePrivacyIcons(true);
1228 // Display a snackbar.
1229 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1230 Snackbar.make(webViewPager, R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1231 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1232 Snackbar.make(webViewPager, R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1233 } else { // Privacy mode.
1234 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1237 // Reload the current WebView.
1238 currentWebView.reload();
1240 // Consume the event.
1242 } else if (menuItemId == R.id.third_party_cookies) { // Third-party cookies.
1243 // Only act if the API >= 21. Otherwise, there are no third-party cookie controls.
1244 if (Build.VERSION.SDK_INT >= 21) {
1245 // Toggle the status of thirdPartyCookiesEnabled.
1246 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1248 // Update the menu checkbox.
1249 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1251 // Display a snackbar.
1252 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1253 Snackbar.make(webViewPager, R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1255 Snackbar.make(webViewPager, R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1258 // Reload the current WebView.
1259 currentWebView.reload();
1262 // Consume the event.
1264 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1265 // Toggle the status of domStorageEnabled.
1266 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1268 // Update the menu checkbox.
1269 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1271 // Update the privacy icon.
1272 updatePrivacyIcons(true);
1274 // Display a snackbar.
1275 if (currentWebView.getSettings().getDomStorageEnabled()) {
1276 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1278 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1281 // Reload the current WebView.
1282 currentWebView.reload();
1284 // Consume the event.
1286 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1287 // Switch the status of saveFormDataEnabled.
1288 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1290 // Update the menu checkbox.
1291 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1293 // Display a snackbar.
1294 if (currentWebView.getSettings().getSaveFormData()) {
1295 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1297 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1300 // Update the privacy icon.
1301 updatePrivacyIcons(true);
1303 // Reload the current WebView.
1304 currentWebView.reload();
1306 // Consume the event.
1308 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1309 // Create a snackbar.
1310 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1311 .setAction(R.string.undo, v -> {
1312 // Do nothing because everything will be handled by `onDismissed()` below.
1314 .addCallback(new Snackbar.Callback() {
1316 public void onDismissed(Snackbar snackbar, int event) {
1317 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1318 // Delete the cookies, which command varies by SDK.
1319 if (Build.VERSION.SDK_INT < 21) {
1320 cookieManager.removeAllCookie();
1322 cookieManager.removeAllCookies(null);
1329 // Consume the event.
1331 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1332 // Create a snackbar.
1333 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1334 .setAction(R.string.undo, v -> {
1335 // Do nothing because everything will be handled by `onDismissed()` below.
1337 .addCallback(new Snackbar.Callback() {
1339 public void onDismissed(Snackbar snackbar, int event) {
1340 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1341 // Delete the DOM Storage.
1342 WebStorage webStorage = WebStorage.getInstance();
1343 webStorage.deleteAllData();
1345 // Initialize a handler to manually delete the DOM storage files and directories.
1346 Handler deleteDomStorageHandler = new Handler();
1348 // Setup a runnable to manually delete the DOM storage files and directories.
1349 Runnable deleteDomStorageRunnable = () -> {
1351 // Get a handle for the runtime.
1352 Runtime runtime = Runtime.getRuntime();
1354 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1355 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1356 String privateDataDirectoryString = getApplicationInfo().dataDir;
1358 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1359 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1361 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1362 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1363 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1364 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1365 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1367 // Wait for the processes to finish.
1368 deleteLocalStorageProcess.waitFor();
1369 deleteIndexProcess.waitFor();
1370 deleteQuotaManagerProcess.waitFor();
1371 deleteQuotaManagerJournalProcess.waitFor();
1372 deleteDatabasesProcess.waitFor();
1373 } catch (Exception exception) {
1374 // Do nothing if an error is thrown.
1378 // Manually delete the DOM storage files after 200 milliseconds.
1379 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1385 // Consume the event.
1387 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1388 // Create a snackbar.
1389 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1390 .setAction(R.string.undo, v -> {
1391 // Do nothing because everything will be handled by `onDismissed()` below.
1393 .addCallback(new Snackbar.Callback() {
1395 public void onDismissed(Snackbar snackbar, int event) {
1396 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1397 // Get a handle for the webView database.
1398 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1400 // Delete the form data.
1401 webViewDatabase.clearFormData();
1407 // Consume the event.
1409 } else if (menuItemId == R.id.easylist) { // EasyList.
1410 // Toggle the EasyList status.
1411 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1413 // Update the menu checkbox.
1414 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1416 // Reload the current WebView.
1417 currentWebView.reload();
1419 // Consume the event.
1421 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1422 // Toggle the EasyPrivacy status.
1423 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1425 // Update the menu checkbox.
1426 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1428 // Reload the current WebView.
1429 currentWebView.reload();
1431 // Consume the event.
1433 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1434 // Toggle Fanboy's Annoyance List status.
1435 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1437 // Update the menu checkbox.
1438 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1440 // Update the staus of Fanboy's Social Blocking List.
1441 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1443 // Reload the current WebView.
1444 currentWebView.reload();
1446 // Consume the event.
1448 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1449 // Toggle Fanboy's Social Blocking List status.
1450 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1452 // Update the menu checkbox.
1453 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1455 // Reload the current WebView.
1456 currentWebView.reload();
1458 // Consume the event.
1460 } else if (menuItemId == R.id.ultralist) { // UltraList.
1461 // Toggle the UltraList status.
1462 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1464 // Update the menu checkbox.
1465 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1467 // Reload the current WebView.
1468 currentWebView.reload();
1470 // Consume the event.
1472 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1473 // Toggle the UltraPrivacy status.
1474 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1476 // Update the menu checkbox.
1477 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1479 // Reload the current WebView.
1480 currentWebView.reload();
1482 // Consume the event.
1484 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1485 //Toggle the third-party requests blocker status.
1486 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1488 // Update the menu checkbox.
1489 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1491 // Reload the current WebView.
1492 currentWebView.reload();
1494 // Consume the event.
1496 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1497 // Update the proxy mode.
1498 proxyMode = ProxyHelper.NONE;
1500 // Apply the proxy mode.
1503 // Consume the event.
1505 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1506 // Update the proxy mode.
1507 proxyMode = ProxyHelper.TOR;
1509 // Apply the proxy mode.
1512 // Consume the event.
1514 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1515 // Update the proxy mode.
1516 proxyMode = ProxyHelper.I2P;
1518 // Apply the proxy mode.
1521 // Consume the event.
1523 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1524 // Update the proxy mode.
1525 proxyMode = ProxyHelper.CUSTOM;
1527 // Apply the proxy mode.
1530 // Consume the event.
1532 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1533 // Update the user agent.
1534 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1536 // Reload the current WebView.
1537 currentWebView.reload();
1539 // Consume the event.
1541 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1542 // Update the user agent.
1543 currentWebView.getSettings().setUserAgentString("");
1545 // Reload the current WebView.
1546 currentWebView.reload();
1548 // Consume the event.
1550 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1551 // Update the user agent.
1552 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1554 // Reload the current WebView.
1555 currentWebView.reload();
1557 // Consume the event.
1559 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1560 // Update the user agent.
1561 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1563 // Reload the current WebView.
1564 currentWebView.reload();
1566 // Consume the event.
1568 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1569 // Update the user agent.
1570 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1572 // Reload the current WebView.
1573 currentWebView.reload();
1575 // Consume the event.
1577 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1578 // Update the user agent.
1579 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1581 // Reload the current WebView.
1582 currentWebView.reload();
1584 // Consume the event.
1586 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1587 // Update the user agent.
1588 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1590 // Reload the current WebView.
1591 currentWebView.reload();
1593 // Consume the event.
1595 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1596 // Update the user agent.
1597 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1599 // Reload the current WebView.
1600 currentWebView.reload();
1602 // Consume the event.
1604 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1605 // Update the user agent.
1606 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1608 // Reload the current WebView.
1609 currentWebView.reload();
1611 // Consume the event.
1613 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1614 // Update the user agent.
1615 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1617 // Reload the current WebView.
1618 currentWebView.reload();
1620 // Consume the event.
1622 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1623 // Update the user agent.
1624 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1626 // Reload the current WebView.
1627 currentWebView.reload();
1629 // Consume the event.
1631 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1632 // Update the user agent.
1633 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1635 // Reload the current WebView.
1636 currentWebView.reload();
1638 // Consume the event.
1640 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1641 // Update the user agent.
1642 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1644 // Reload the current WebView.
1645 currentWebView.reload();
1647 // Consume the event.
1649 } else if (menuItemId == R.id.font_size) { // Font size.
1650 // Instantiate the font size dialog.
1651 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1653 // Show the font size dialog.
1654 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1656 // Consume the event.
1658 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1659 // Toggle the stored status of swipe to refresh.
1660 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1662 // Get a handle for the swipe refresh layout.
1663 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1665 // Update the swipe refresh layout.
1666 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1667 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1668 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1669 } else { // Swipe to refresh is disabled.
1670 // Disable the swipe refresh layout.
1671 swipeRefreshLayout.setEnabled(false);
1674 // Consume the event.
1676 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1677 // Toggle the viewport.
1678 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1680 // Consume the event.
1682 } else if (menuItemId == R.id.display_images) { // Display images.
1683 // Toggle the displaying of images.
1684 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1685 // Disable loading of images.
1686 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1688 // Reload the website to remove existing images.
1689 currentWebView.reload();
1690 } else { // Images are not currently loaded automatically.
1691 // Enable loading of images. Missing images will be loaded without the need for a reload.
1692 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1695 // Consume the event.
1697 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1698 // Check to see if dark WebView is supported by this WebView.
1699 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1700 // Toggle the dark WebView setting.
1701 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1702 // Turn off dark WebView.
1703 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1704 } else { // Dark WebView is currently disabled.
1705 // Turn on dark WebView.
1706 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1710 // Consume the event.
1712 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1713 // Get a handle for the views.
1714 Toolbar toolbar = findViewById(R.id.toolbar);
1715 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1716 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1718 // Set the minimum height of the find on page linear layout to match the toolbar.
1719 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1721 // Hide the toolbar.
1722 toolbar.setVisibility(View.GONE);
1724 // Show the find on page linear layout.
1725 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1727 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1728 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1729 findOnPageEditText.postDelayed(() -> {
1730 // Set the focus on the find on page edit text.
1731 findOnPageEditText.requestFocus();
1733 // Get a handle for the input method manager.
1734 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1736 // Remove the lint warning below that the input method manager might be null.
1737 assert inputMethodManager != null;
1739 // Display the keyboard. `0` sets no input flags.
1740 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1743 // Consume the event.
1745 } else if (menuItemId == R.id.print) { // Print.
1746 // Get a print manager instance.
1747 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1749 // Remove the lint error below that print manager might be null.
1750 assert printManager != null;
1752 // Create a print document adapter from the current WebView.
1753 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1755 // Print the document.
1756 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1758 // Consume the event.
1760 } else if (menuItemId == R.id.save_url) { // Save URL.
1761 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1762 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1763 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1765 // Consume the event.
1767 } else if (menuItemId == R.id.save_archive) { // Save archive.
1768 // Instantiate the save dialog.
1769 DialogFragment saveArchiveFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_ARCHIVE, null, null, getString(R.string.webpage_mht), null,
1772 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1773 saveArchiveFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1775 // Consume the event.
1777 } else if (menuItemId == R.id.save_image) { // Save image.
1778 // Instantiate the save dialog.
1779 DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_IMAGE, null, null, getString(R.string.webpage_png), null,
1782 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1783 saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1785 // Consume the event.
1787 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1788 // Instantiate the create home screen shortcut dialog.
1789 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1790 currentWebView.getFavoriteOrDefaultIcon());
1792 // Show the create home screen shortcut dialog.
1793 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1795 // Consume the event.
1797 } else if (menuItemId == R.id.view_source) { // View source.
1798 // Create an intent to launch the view source activity.
1799 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1801 // Add the variables to the intent.
1802 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1803 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1806 startActivity(viewSourceIntent);
1808 // Consume the event.
1810 } else if (menuItemId == R.id.share_url) { // Share URL.
1811 // Setup the share string.
1812 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1814 // Create the share intent.
1815 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1817 // Add the share string to the intent.
1818 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1820 // Set the MIME type.
1821 shareIntent.setType("text/plain");
1823 // Set the intent to open in a new task.
1824 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1827 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1829 // Consume the event.
1831 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1832 // Open the URL with an outside app.
1833 openWithApp(currentWebView.getUrl());
1835 // Consume the event.
1837 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1838 // Open the URL with an outside browser.
1839 openWithBrowser(currentWebView.getUrl());
1841 // Consume the event.
1843 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1844 // Check if domain settings currently exist.
1845 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1846 // Reapply the domain settings on returning to `MainWebViewActivity`.
1847 reapplyDomainSettingsOnRestart = true;
1849 // Create an intent to launch the domains activity.
1850 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1852 // Add the extra information to the intent.
1853 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1854 domainsIntent.putExtra("close_on_back", true);
1855 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1857 // Get the current certificate.
1858 SslCertificate sslCertificate = currentWebView.getCertificate();
1860 // Check to see if the SSL certificate is populated.
1861 if (sslCertificate != null) {
1862 // Extract the certificate to strings.
1863 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1864 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1865 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1866 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1867 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1868 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1869 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1870 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1872 // Add the certificate to the intent.
1873 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1874 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1875 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1876 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1877 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1878 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1879 domainsIntent.putExtra("ssl_start_date", startDateLong);
1880 domainsIntent.putExtra("ssl_end_date", endDateLong);
1883 // Check to see if the current IP addresses have been received.
1884 if (currentWebView.hasCurrentIpAddresses()) {
1885 // Add the current IP addresses to the intent.
1886 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1890 startActivity(domainsIntent);
1891 } else { // Add a new domain.
1892 // Apply the new domain settings on returning to `MainWebViewActivity`.
1893 reapplyDomainSettingsOnRestart = true;
1895 // Get the current domain
1896 Uri currentUri = Uri.parse(currentWebView.getUrl());
1897 String currentDomain = currentUri.getHost();
1899 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1900 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1902 // Create the domain and store the database ID.
1903 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1905 // Create an intent to launch the domains activity.
1906 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1908 // Add the extra information to the intent.
1909 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1910 domainsIntent.putExtra("close_on_back", true);
1911 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1913 // Get the current certificate.
1914 SslCertificate sslCertificate = currentWebView.getCertificate();
1916 // Check to see if the SSL certificate is populated.
1917 if (sslCertificate != null) {
1918 // Extract the certificate to strings.
1919 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1920 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1921 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1922 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1923 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1924 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1925 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1926 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1928 // Add the certificate to the intent.
1929 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1930 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1931 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1932 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1933 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1934 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1935 domainsIntent.putExtra("ssl_start_date", startDateLong);
1936 domainsIntent.putExtra("ssl_end_date", endDateLong);
1939 // Check to see if the current IP addresses have been received.
1940 if (currentWebView.hasCurrentIpAddresses()) {
1941 // Add the current IP addresses to the intent.
1942 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1946 startActivity(domainsIntent);
1949 // Consume the event.
1951 } else if (menuItemId == R.id.ad_consent) { // Ad consent.
1952 // Instantiate the ad consent dialog.
1953 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1955 // Display the ad consent dialog.
1956 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1958 // Consume the event.
1960 } else { // There is no match with the options menu. Pass the event up to the parent method.
1961 // Don't consume the event.
1962 return super.onOptionsItemSelected(menuItem);
1966 // removeAllCookies is deprecated, but it is required for API < 21.
1968 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1969 // Get a handle for the shared preferences.
1970 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1972 // Get the menu item ID.
1973 int menuItemId = menuItem.getItemId();
1975 // Run the commands that correspond to the selected menu item.
1976 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
1977 // Clear and exit Privacy Browser.
1979 } else if (menuItemId == R.id.home) { // Home.
1980 // Load the homepage.
1981 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1982 } else if (menuItemId == R.id.back) { // Back.
1983 // Check if the WebView can go back.
1984 if (currentWebView.canGoBack()) {
1985 // Get the current web back forward list.
1986 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1988 // Get the previous entry URL.
1989 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1991 // Apply the domain settings.
1992 applyDomainSettings(currentWebView, previousUrl, false, false, false);
1994 // Load the previous website in the history.
1995 currentWebView.goBack();
1997 } else if (menuItemId == R.id.forward) { // Forward.
1998 // Check if the WebView can go forward.
1999 if (currentWebView.canGoForward()) {
2000 // Get the current web back forward list.
2001 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2003 // Get the next entry URL.
2004 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2006 // Apply the domain settings.
2007 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2009 // Load the next website in the history.
2010 currentWebView.goForward();
2012 } else if (menuItemId == R.id.history) { // History.
2013 // Instantiate the URL history dialog.
2014 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2016 // Show the URL history dialog.
2017 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2018 } else if (menuItemId == R.id.open) { // Open.
2019 // Instantiate the open file dialog.
2020 DialogFragment openDialogFragment = new OpenDialog();
2022 // Show the open file dialog.
2023 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2024 } else if (menuItemId == R.id.requests) { // Requests.
2025 // Populate the resource requests.
2026 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2028 // Create an intent to launch the Requests activity.
2029 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2031 // Add the block third-party requests status to the intent.
2032 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2035 startActivity(requestsIntent);
2036 } else if (menuItemId == R.id.downloads) { // Downloads.
2037 // Launch the system Download Manager.
2038 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2040 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2041 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2044 startActivity(downloadManagerIntent);
2045 } else if (menuItemId == R.id.domains) { // Domains.
2046 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2047 reapplyDomainSettingsOnRestart = true;
2049 // Launch the domains activity.
2050 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2052 // Add the extra information to the intent.
2053 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2055 // Get the current certificate.
2056 SslCertificate sslCertificate = currentWebView.getCertificate();
2058 // Check to see if the SSL certificate is populated.
2059 if (sslCertificate != null) {
2060 // Extract the certificate to strings.
2061 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2062 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2063 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2064 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2065 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2066 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2067 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2068 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2070 // Add the certificate to the intent.
2071 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2072 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2073 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2074 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2075 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2076 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2077 domainsIntent.putExtra("ssl_start_date", startDateLong);
2078 domainsIntent.putExtra("ssl_end_date", endDateLong);
2081 // Check to see if the current IP addresses have been received.
2082 if (currentWebView.hasCurrentIpAddresses()) {
2083 // Add the current IP addresses to the intent.
2084 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2088 startActivity(domainsIntent);
2089 } else if (menuItemId == R.id.settings) { // Settings.
2090 // Set the flag to reapply app settings on restart when returning from Settings.
2091 reapplyAppSettingsOnRestart = true;
2093 // Set the flag to reapply the domain settings on restart when returning from Settings.
2094 reapplyDomainSettingsOnRestart = true;
2096 // Launch the settings activity.
2097 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2098 startActivity(settingsIntent);
2099 } else if (menuItemId == R.id.import_export) { // Import/Export.
2100 // Create an intent to launch the import/export activity.
2101 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2104 startActivity(importExportIntent);
2105 } else if (menuItemId == R.id.logcat) { // Logcat.
2106 // Create an intent to launch the logcat activity.
2107 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2110 startActivity(logcatIntent);
2111 } else if (menuItemId == R.id.guide) { // Guide.
2112 // Create an intent to launch the guide activity.
2113 Intent guideIntent = new Intent(this, GuideActivity.class);
2116 startActivity(guideIntent);
2117 } else if (menuItemId == R.id.about) { // About
2118 // Create an intent to launch the about activity.
2119 Intent aboutIntent = new Intent(this, AboutActivity.class);
2121 // Create a string array for the blocklist versions.
2122 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],
2123 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2125 // Add the blocklist versions to the intent.
2126 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2129 startActivity(aboutIntent);
2132 // Close the navigation drawer.
2133 drawerLayout.closeDrawer(GravityCompat.START);
2138 public void onPostCreate(Bundle savedInstanceState) {
2139 // Run the default commands.
2140 super.onPostCreate(savedInstanceState);
2142 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2143 actionBarDrawerToggle.syncState();
2147 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2148 // Run the default commands.
2149 super.onConfigurationChanged(newConfig);
2151 // Reload the ad for the free flavor if not in full screen mode.
2152 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2153 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2154 View adView = findViewById(R.id.adview);
2156 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2157 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2158 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2161 // `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:
2162 // https://code.google.com/p/android/issues/detail?id=20493#c8
2163 // ActivityCompat.invalidateOptionsMenu(this);
2167 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2168 // Get the hit test result.
2169 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2171 // Define the URL strings.
2172 final String imageUrl;
2173 final String linkUrl;
2175 // Get handles for the system managers.
2176 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2178 // Remove the lint errors below that the clipboard manager might be null.
2179 assert clipboardManager != null;
2181 // Process the link according to the type.
2182 switch (hitTestResult.getType()) {
2183 // `SRC_ANCHOR_TYPE` is a link.
2184 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2185 // Get the target URL.
2186 linkUrl = hitTestResult.getExtra();
2188 // Set the target URL as the title of the `ContextMenu`.
2189 menu.setHeaderTitle(linkUrl);
2191 // Add an Open in New Tab entry.
2192 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2193 // Load the link URL in a new tab and move to it.
2194 addNewTab(linkUrl, true);
2196 // Consume the event.
2200 // Add an Open in Background entry.
2201 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2202 // Load the link URL in a new tab but do not move to it.
2203 addNewTab(linkUrl, false);
2205 // Consume the event.
2209 // Add an Open with App entry.
2210 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2211 openWithApp(linkUrl);
2213 // Consume the event.
2217 // Add an Open with Browser entry.
2218 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2219 openWithBrowser(linkUrl);
2221 // Consume the event.
2225 // Add a Copy URL entry.
2226 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2227 // Save the link URL in a `ClipData`.
2228 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2230 // Set the `ClipData` as the clipboard's primary clip.
2231 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2233 // Consume the event.
2237 // Add a Save URL entry.
2238 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2239 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2240 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2241 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2243 // Consume the event.
2247 // Add an empty Cancel entry, which by default closes the context menu.
2248 menu.add(R.string.cancel);
2251 // `IMAGE_TYPE` is an image.
2252 case WebView.HitTestResult.IMAGE_TYPE:
2253 // Get the image URL.
2254 imageUrl = hitTestResult.getExtra();
2256 // Remove the incorrect lint warning below that the image URL might be null.
2257 assert imageUrl != null;
2259 // Set the context menu title.
2260 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2261 // Truncate the image URL before making it the title.
2262 menu.setHeaderTitle(imageUrl.substring(0, 100));
2263 } else { // The image URL does not contain the full image data.
2264 // Set the image URL as the title of the context menu.
2265 menu.setHeaderTitle(imageUrl);
2268 // Add an Open in New Tab entry.
2269 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2270 // Load the image in a new tab.
2271 addNewTab(imageUrl, true);
2273 // Consume the event.
2277 // Add an Open with App entry.
2278 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2279 // Open the image URL with an external app.
2280 openWithApp(imageUrl);
2282 // Consume the event.
2286 // Add an Open with Browser entry.
2287 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2288 // Open the image URL with an external browser.
2289 openWithBrowser(imageUrl);
2291 // Consume the event.
2295 // Add a View Image entry.
2296 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2297 // Load the image in the current tab.
2298 loadUrl(currentWebView, imageUrl);
2300 // Consume the event.
2304 // Add a Save Image entry.
2305 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2306 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2307 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2308 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2310 // Consume the event.
2314 // Add a Copy URL entry.
2315 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2316 // Save the image URL in a clip data.
2317 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2319 // Set the clip data as the clipboard's primary clip.
2320 clipboardManager.setPrimaryClip(imageTypeClipData);
2322 // Consume the event.
2326 // Add an empty Cancel entry, which by default closes the context menu.
2327 menu.add(R.string.cancel);
2330 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2331 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2332 // Get the image URL.
2333 imageUrl = hitTestResult.getExtra();
2335 // Instantiate a handler.
2336 Handler handler = new Handler();
2338 // Get a message from the handler.
2339 Message message = handler.obtainMessage();
2341 // Request the image details from the last touched node be returned in the message.
2342 currentWebView.requestFocusNodeHref(message);
2344 // Get the link URL from the message data.
2345 linkUrl = message.getData().getString("url");
2347 // Set the link URL as the title of the context menu.
2348 menu.setHeaderTitle(linkUrl);
2350 // Add an Open in New Tab entry.
2351 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2352 // Load the link URL in a new tab and move to it.
2353 addNewTab(linkUrl, true);
2355 // Consume the event.
2359 // Add an Open in Background entry.
2360 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2361 // Lod the link URL in a new tab but do not move to it.
2362 addNewTab(linkUrl, false);
2364 // Consume the event.
2368 // Add an Open Image in New Tab entry.
2369 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2370 // Load the image in a new tab and move to it.
2371 addNewTab(imageUrl, true);
2373 // Consume the event.
2377 // Add an Open with App entry.
2378 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2379 // Open the link URL with an external app.
2380 openWithApp(linkUrl);
2382 // Consume the event.
2386 // Add an Open with Browser entry.
2387 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2388 // Open the link URL with an external browser.
2389 openWithBrowser(linkUrl);
2391 // Consume the event.
2395 // Add a View Image entry.
2396 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2397 // View the image in the current tab.
2398 loadUrl(currentWebView, imageUrl);
2400 // Consume the event.
2404 // Add a Save Image entry.
2405 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2406 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2407 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2408 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2410 // Consume the event.
2414 // Add a Copy URL entry.
2415 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2416 // Save the link URL in a clip data.
2417 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2419 // Set the clip data as the clipboard's primary clip.
2420 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2422 // Consume the event.
2426 // Add a Save URL entry.
2427 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2428 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2429 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2430 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2432 // Consume the event.
2436 // Add an empty Cancel entry, which by default closes the context menu.
2437 menu.add(R.string.cancel);
2440 case WebView.HitTestResult.EMAIL_TYPE:
2441 // Get the target URL.
2442 linkUrl = hitTestResult.getExtra();
2444 // Set the target URL as the title of the `ContextMenu`.
2445 menu.setHeaderTitle(linkUrl);
2447 // Add a Write Email entry.
2448 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2449 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2450 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2452 // Parse the url and set it as the data for the `Intent`.
2453 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2455 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2456 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2460 startActivity(emailIntent);
2461 } catch (ActivityNotFoundException exception) {
2462 // Display a snackbar.
2463 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2466 // Consume the event.
2470 // Add a Copy Email Address entry.
2471 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2472 // Save the email address in a `ClipData`.
2473 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2475 // Set the `ClipData` as the clipboard's primary clip.
2476 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2478 // Consume the event.
2482 // Add an empty Cancel entry, which by default closes the context menu.
2483 menu.add(R.string.cancel);
2489 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2490 // Get a handle for the bookmarks list view.
2491 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2494 Dialog dialog = dialogFragment.getDialog();
2496 // Remove the incorrect lint warning below that the dialog might be null.
2497 assert dialog != null;
2499 // Get the views from the dialog fragment.
2500 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2501 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2503 // Extract the strings from the edit texts.
2504 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2505 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2507 // Create a favorite icon byte array output stream.
2508 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2510 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2511 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2513 // Convert the favorite icon byte array stream to a byte array.
2514 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2516 // Display the new bookmark below the current items in the (0 indexed) list.
2517 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2519 // Create the bookmark.
2520 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2522 // Update the bookmarks cursor with the current contents of this folder.
2523 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2525 // Update the list view.
2526 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2528 // Scroll to the new bookmark.
2529 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2533 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2534 // Get a handle for the bookmarks list view.
2535 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2538 Dialog dialog = dialogFragment.getDialog();
2540 // Remove the incorrect lint warning below that the dialog might be null.
2541 assert dialog != null;
2543 // Get handles for the views in the dialog fragment.
2544 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2545 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2546 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2548 // Get new folder name string.
2549 String folderNameString = createFolderNameEditText.getText().toString();
2551 // Create a folder icon bitmap.
2552 Bitmap folderIconBitmap;
2554 // Set the folder icon bitmap according to the dialog.
2555 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2556 // Get the default folder icon drawable.
2557 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2559 // Convert the folder icon drawable to a bitmap drawable.
2560 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2562 // Convert the folder icon bitmap drawable to a bitmap.
2563 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2564 } else { // Use the WebView favorite icon.
2565 // Copy the favorite icon bitmap to the folder icon bitmap.
2566 folderIconBitmap = favoriteIconBitmap;
2569 // Create a folder icon byte array output stream.
2570 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2572 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2573 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2575 // Convert the folder icon byte array stream to a byte array.
2576 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2578 // Move all the bookmarks down one in the display order.
2579 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2580 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2581 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2584 // Create the folder, which will be placed at the top of the `ListView`.
2585 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2587 // Update the bookmarks cursor with the current contents of this folder.
2588 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2590 // Update the `ListView`.
2591 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2593 // Scroll to the new folder.
2594 bookmarksListView.setSelection(0);
2598 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2599 // Remove the incorrect lint warning below that the dialog fragment might be null.
2600 assert dialogFragment != null;
2603 Dialog dialog = dialogFragment.getDialog();
2605 // Remove the incorrect lint warning below that the dialog might be null.
2606 assert dialog != null;
2608 // Get handles for the views from the dialog.
2609 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2610 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2611 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2612 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2614 // Get the new folder name.
2615 String newFolderNameString = editFolderNameEditText.getText().toString();
2617 // Check if the favorite icon has changed.
2618 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2619 // Update the name in the database.
2620 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2621 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2622 // Create the new folder icon Bitmap.
2623 Bitmap folderIconBitmap;
2625 // Populate the new folder icon bitmap.
2626 if (defaultFolderIconRadioButton.isChecked()) {
2627 // Get the default folder icon drawable.
2628 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2630 // Convert the folder icon drawable to a bitmap drawable.
2631 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2633 // Convert the folder icon bitmap drawable to a bitmap.
2634 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2635 } else { // Use the `WebView` favorite icon.
2636 // Copy the favorite icon bitmap to the folder icon bitmap.
2637 folderIconBitmap = favoriteIconBitmap;
2640 // Create a folder icon byte array output stream.
2641 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2643 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2644 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2646 // Convert the folder icon byte array stream to a byte array.
2647 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2649 // Update the folder icon in the database.
2650 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2651 } else { // The folder icon and the name have changed.
2652 // Get the new folder icon `Bitmap`.
2653 Bitmap folderIconBitmap;
2654 if (defaultFolderIconRadioButton.isChecked()) {
2655 // Get the default folder icon drawable.
2656 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2658 // Convert the folder icon drawable to a bitmap drawable.
2659 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2661 // Convert the folder icon bitmap drawable to a bitmap.
2662 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2663 } else { // Use the `WebView` favorite icon.
2664 // Copy the favorite icon bitmap to the folder icon bitmap.
2665 folderIconBitmap = favoriteIconBitmap;
2668 // Create a folder icon byte array output stream.
2669 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2671 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2672 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2674 // Convert the folder icon byte array stream to a byte array.
2675 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2677 // Update the folder name and icon in the database.
2678 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2681 // Update the bookmarks cursor with the current contents of this folder.
2682 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2684 // Update the `ListView`.
2685 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2688 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2690 public void onBackPressed() {
2691 // Check the different options for processing `back`.
2692 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2693 // Close the navigation drawer.
2694 drawerLayout.closeDrawer(GravityCompat.START);
2695 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2696 // close the bookmarks drawer.
2697 drawerLayout.closeDrawer(GravityCompat.END);
2698 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2699 // Re-enable the screen timeout.
2700 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2702 // Unset the full screen video flag.
2703 displayingFullScreenVideo = false;
2705 // Remove all the views from the full screen video frame layout.
2706 fullScreenVideoFrameLayout.removeAllViews();
2708 // Hide the full screen video frame layout.
2709 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2711 // Enable the sliding drawers.
2712 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2714 // Show the main content relative layout.
2715 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2717 // Apply the appropriate full screen mode flags.
2718 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2719 // Hide the banner ad in the free flavor.
2720 if (BuildConfig.FLAVOR.contentEquals("free")) {
2721 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2722 View adView = findViewById(R.id.adview);
2724 // Hide the banner ad.
2725 AdHelper.hideAd(adView);
2728 /* Hide the system bars.
2729 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2730 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2731 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2732 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2734 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2735 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2737 // Reload the website if the app bar is hidden. Otherwise, there is some bug in Android that causes the WebView to be entirely black.
2739 // Reload the WebView.
2740 currentWebView.reload();
2742 } else { // Switch to normal viewing mode.
2743 // Remove the `SYSTEM_UI` flags from the root frame layout.
2744 rootFrameLayout.setSystemUiVisibility(0);
2747 // Reload the ad for the free flavor if not in full screen mode.
2748 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2749 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2750 View adView = findViewById(R.id.adview);
2752 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2753 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2755 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2756 // Get the current web back forward list.
2757 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2759 // Get the previous entry URL.
2760 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2762 // Apply the domain settings.
2763 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2766 currentWebView.goBack();
2767 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2768 // Close the current tab.
2770 } else { // There isn't anything to do in Privacy Browser.
2771 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2772 if (Build.VERSION.SDK_INT >= 21) {
2773 finishAndRemoveTask();
2778 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2783 // Process the results of a file browse.
2785 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2786 // Run the default commands.
2787 super.onActivityResult(requestCode, resultCode, returnedIntent);
2789 // Run the commands that correlate to the specified request code.
2790 switch (requestCode) {
2791 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2792 // File uploads only work on API >= 21.
2793 if (Build.VERSION.SDK_INT >= 21) {
2794 // Pass the file to the WebView.
2795 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2799 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2800 // Don't do anything if the user pressed back from the file picker.
2801 if (resultCode == Activity.RESULT_OK) {
2802 // Get a handle for the save dialog fragment.
2803 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2805 // Only update the file name if the dialog still exists.
2806 if (saveWebpageDialogFragment != null) {
2807 // Get a handle for the save webpage dialog.
2808 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2810 // Remove the incorrect lint warning below that the dialog might be null.
2811 assert saveWebpageDialog != null;
2813 // Get a handle for the file name edit text.
2814 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2815 TextView fileExistsWarningTextView = saveWebpageDialog.findViewById(R.id.file_exists_warning_textview);
2817 // Instantiate the file name helper.
2818 FileNameHelper fileNameHelper = new FileNameHelper();
2820 // Get the file path if it isn't null.
2821 if (returnedIntent.getData() != null) {
2822 // Convert the file name URI to a file name path.
2823 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2825 // Set the file name path as the text of the file name edit text.
2826 fileNameEditText.setText(fileNamePath);
2828 // Move the cursor to the end of the file name edit text.
2829 fileNameEditText.setSelection(fileNamePath.length());
2831 // Hide the file exists warning.
2832 fileExistsWarningTextView.setVisibility(View.GONE);
2838 case BROWSE_OPEN_REQUEST_CODE:
2839 // Don't do anything if the user pressed back from the file picker.
2840 if (resultCode == Activity.RESULT_OK) {
2841 // Get a handle for the open dialog fragment.
2842 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2844 // Only update the file name if the dialog still exists.
2845 if (openDialogFragment != null) {
2846 // Get a handle for the open dialog.
2847 Dialog openDialog = openDialogFragment.getDialog();
2849 // Remove the incorrect lint warning below that the dialog might be null.
2850 assert openDialog != null;
2852 // Get a handle for the file name edit text.
2853 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2855 // Instantiate the file name helper.
2856 FileNameHelper fileNameHelper = new FileNameHelper();
2858 // Get the file path if it isn't null.
2859 if (returnedIntent.getData() != null) {
2860 // Convert the file name URI to a file name path.
2861 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2863 // Set the file name path as the text of the file name edit text.
2864 fileNameEditText.setText(fileNamePath);
2866 // Move the cursor to the end of the file name edit text.
2867 fileNameEditText.setSelection(fileNamePath.length());
2875 private void loadUrlFromTextBox() {
2876 // Get a handle for the URL edit text.
2877 EditText urlEditText = findViewById(R.id.url_edittext);
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 urlEditText = 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 = urlEditText.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 // Get handles for the URL views.
3254 EditText urlEditText = findViewById(R.id.url_edittext);
3256 // Remove the formatting from the URL edit text when the user is editing the text.
3257 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3258 if (hasFocus) { // The user is editing the URL text box.
3259 // Remove the highlighting.
3260 urlEditText.getText().removeSpan(redColorSpan);
3261 urlEditText.getText().removeSpan(initialGrayColorSpan);
3262 urlEditText.getText().removeSpan(finalGrayColorSpan);
3263 } else { // The user has stopped editing the URL text box.
3264 // Move to the beginning of the string.
3265 urlEditText.setSelection(0);
3267 // Reapply the highlighting.
3272 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3273 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3274 // If the event is a key-down event on the `enter` button, load the URL.
3275 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3276 // Load the URL into the mainWebView and consume the event.
3277 loadUrlFromTextBox();
3279 // If the enter key was pressed, consume the event.
3282 // If any other key was pressed, do not consume the event.
3287 // Create an Orbot status broadcast receiver.
3288 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3290 public void onReceive(Context context, Intent intent) {
3291 // Store the content of the status message in `orbotStatus`.
3292 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3294 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3295 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3296 // Reset the waiting for proxy status.
3297 waitingForProxy = false;
3299 // Get a handle for the waiting for proxy dialog.
3300 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3302 // Dismiss the waiting for proxy dialog if it is displayed.
3303 if (waitingForProxyDialogFragment != null) {
3304 waitingForProxyDialogFragment.dismiss();
3307 // Reload existing URLs and load any URLs that are waiting for the proxy.
3308 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3309 // Get the WebView tab fragment.
3310 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3312 // Get the fragment view.
3313 View fragmentView = webViewTabFragment.getView();
3315 // Only process the WebViews if they exist.
3316 if (fragmentView != null) {
3317 // Get the nested scroll WebView from the tab fragment.
3318 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3320 // Get the waiting for proxy URL string.
3321 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3323 // Load the pending URL if it exists.
3324 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3326 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3328 // Reset the waiting for proxy URL string.
3329 nestedScrollWebView.resetWaitingForProxyUrlString();
3330 } else { // No URL is waiting to be loaded.
3331 // Reload the existing URL.
3332 nestedScrollWebView.reload();
3340 // Register the Orbot status broadcast receiver on `this` context.
3341 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3343 // Get handles for views that need to be modified.
3344 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3345 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3346 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3347 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3348 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3350 // Update the web view pager every time a tab is modified.
3351 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3353 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3358 public void onPageSelected(int position) {
3359 // Close the find on page bar if it is open.
3360 closeFindOnPage(null);
3362 // Set the current WebView.
3363 setCurrentWebView(position);
3365 // 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.
3366 if (tabLayout.getSelectedTabPosition() != position) {
3367 // Wait until the new tab has been created.
3368 tabLayout.post(() -> {
3369 // Get a handle for the tab.
3370 TabLayout.Tab tab = tabLayout.getTabAt(position);
3372 // Assert that the tab is not null.
3382 public void onPageScrollStateChanged(int state) {
3387 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3388 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3390 public void onTabSelected(TabLayout.Tab tab) {
3391 // Select the same page in the view pager.
3392 webViewPager.setCurrentItem(tab.getPosition());
3396 public void onTabUnselected(TabLayout.Tab tab) {
3401 public void onTabReselected(TabLayout.Tab tab) {
3402 // Instantiate the View SSL Certificate dialog.
3403 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3405 // Display the View SSL Certificate dialog.
3406 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3410 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3411 launchBookmarksActivityFab.setOnClickListener(v -> {
3412 // Get a copy of the favorite icon bitmap.
3413 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3415 // Create a favorite icon byte array output stream.
3416 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3418 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3419 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3421 // Convert the favorite icon byte array stream to a byte array.
3422 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3424 // Create an intent to launch the bookmarks activity.
3425 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3427 // Add the extra information to the intent.
3428 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3429 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3430 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3431 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3434 startActivity(bookmarksIntent);
3437 // Set the create new bookmark folder FAB to display an alert dialog.
3438 createBookmarkFolderFab.setOnClickListener(v -> {
3439 // Create a create bookmark folder dialog.
3440 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3442 // Show the create bookmark folder dialog.
3443 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3446 // Set the create new bookmark FAB to display an alert dialog.
3447 createBookmarkFab.setOnClickListener(view -> {
3448 // Instantiate the create bookmark dialog.
3449 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3451 // Display the create bookmark dialog.
3452 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3455 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3456 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3458 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3463 public void onTextChanged(CharSequence s, int start, int before, int count) {
3468 public void afterTextChanged(Editable s) {
3469 // 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.
3470 if (currentWebView != null) {
3471 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3476 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3477 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3478 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3479 // Hide the soft keyboard.
3480 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3482 // Consume the event.
3484 } else { // A different key was pressed.
3485 // Do not consume the event.
3490 // Implement swipe to refresh.
3491 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3493 // Store the default progress view offsets for use later in `initializeWebView()`.
3494 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3495 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3497 // Set the refresh color scheme according to the theme.
3498 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3499 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
3501 swipeRefreshLayout.setColorSchemeResources(R.color.violet_500);
3504 // Initialize a color background typed value.
3505 TypedValue colorBackgroundTypedValue = new TypedValue();
3507 // Get the color background from the theme.
3508 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3510 // Get the color background int from the typed value.
3511 int colorBackgroundInt = colorBackgroundTypedValue.data;
3513 // Set the swipe refresh background color.
3514 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3516 // The drawer titles identify the drawer layouts in accessibility mode.
3517 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3518 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3520 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3521 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3523 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3524 currentBookmarksFolder = "";
3526 // Load the home folder, which is `""` in the database.
3527 loadBookmarksFolder();
3529 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3530 // Convert the id from long to int to match the format of the bookmarks database.
3531 int databaseId = (int) id;
3533 // Get the bookmark cursor for this ID.
3534 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3536 // Move the bookmark cursor to the first row.
3537 bookmarkCursor.moveToFirst();
3539 // Act upon the bookmark according to the type.
3540 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3541 // Store the new folder name in `currentBookmarksFolder`.
3542 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3544 // Load the new folder.
3545 loadBookmarksFolder();
3546 } else { // The selected bookmark is not a folder.
3547 // Load the bookmark URL.
3548 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3550 // Close the bookmarks drawer.
3551 drawerLayout.closeDrawer(GravityCompat.END);
3554 // Close the `Cursor`.
3555 bookmarkCursor.close();
3558 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3559 // Convert the database ID from `long` to `int`.
3560 int databaseId = (int) id;
3562 // Find out if the selected bookmark is a folder.
3563 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3566 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3567 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3569 // Instantiate the edit folder bookmark dialog.
3570 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3572 // Show the edit folder bookmark dialog.
3573 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3575 // Get the bookmark cursor for this ID.
3576 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3578 // Move the bookmark cursor to the first row.
3579 bookmarkCursor.moveToFirst();
3581 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3582 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3585 // Consume the event.
3589 // The drawer listener is used to update the navigation menu.
3590 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3592 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3596 public void onDrawerOpened(@NonNull View drawerView) {
3600 public void onDrawerClosed(@NonNull View drawerView) {
3604 public void onDrawerStateChanged(int newState) {
3605 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3606 // Update the navigation menu items if the WebView is not null.
3607 if (currentWebView != null) {
3608 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3609 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3610 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3611 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3613 // Hide the keyboard (if displayed).
3614 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3617 // 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.
3618 urlEditText.clearFocus();
3619 currentWebView.clearFocus();
3624 // 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).
3625 customHeaders.put("X-Requested-With", "");
3627 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3628 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3630 // Get a handle for the WebView.
3631 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3633 // Store the default user agent.
3634 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3636 // Destroy the bare WebView.
3637 bareWebView.destroy();
3640 private void applyAppSettings() {
3641 // Get a handle for the shared preferences.
3642 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3644 // Store the values from the shared preferences in variables.
3645 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3646 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3647 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3648 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3649 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3650 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3651 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3652 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3653 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3655 // Apply the saved proxy mode if the app has been restarted.
3656 if (savedProxyMode != null) {
3657 // Apply the saved proxy mode.
3658 proxyMode = savedProxyMode;
3660 // Reset the saved proxy mode.
3661 savedProxyMode = null;
3664 // Get the search string.
3665 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3667 // Set the search string.
3668 if (searchString.equals("Custom URL")) { // A custom search string is used.
3669 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3670 } else { // A custom search string is not used.
3671 searchURL = searchString;
3677 // Set Do Not Track status.
3678 if (doNotTrackEnabled) {
3679 customHeaders.put("DNT", "1");
3681 customHeaders.remove("DNT");
3684 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3685 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3686 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3687 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3688 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3690 // Add the scrolling behavior to the layout parameters.
3692 // Enable scrolling of the app bar.
3693 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3694 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3695 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3696 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3698 // Disable scrolling of the app bar.
3699 swipeRefreshLayoutParams.setBehavior(null);
3700 toolbarLayoutParams.setScrollFlags(0);
3701 findOnPageLayoutParams.setScrollFlags(0);
3702 tabsLayoutParams.setScrollFlags(0);
3704 // Expand the app bar if it is currently collapsed.
3705 appBarLayout.setExpanded(true);
3708 // Apply the modified layout parameters.
3709 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3710 toolbar.setLayoutParams(toolbarLayoutParams);
3711 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3712 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3714 // Set the app bar scrolling for each WebView.
3715 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3716 // Get the WebView tab fragment.
3717 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3719 // Get the fragment view.
3720 View fragmentView = webViewTabFragment.getView();
3722 // Only modify the WebViews if they exist.
3723 if (fragmentView != null) {
3724 // Get the nested scroll WebView from the tab fragment.
3725 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3727 // Set the app bar scrolling.
3728 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3732 // Update the full screen browsing mode settings.
3733 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3734 // Update the visibility of the app bar, which might have changed in the settings.
3736 // Hide the tab linear layout.
3737 tabsLinearLayout.setVisibility(View.GONE);
3739 // Hide the action bar.
3742 // Show the tab linear layout.
3743 tabsLinearLayout.setVisibility(View.VISIBLE);
3745 // Show the action bar.
3749 // Hide the banner ad in the free flavor.
3750 if (BuildConfig.FLAVOR.contentEquals("free")) {
3751 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3752 View adView = findViewById(R.id.adview);
3754 // Hide the banner ad.
3755 AdHelper.hideAd(adView);
3758 /* Hide the system bars.
3759 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3760 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3761 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3762 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3764 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3765 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3766 } else { // Privacy Browser is not in full screen browsing mode.
3767 // 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.
3768 inFullScreenBrowsingMode = false;
3770 // Show the tab linear layout.
3771 tabsLinearLayout.setVisibility(View.VISIBLE);
3773 // Show the action bar.
3776 // Show the banner ad in the free flavor.
3777 if (BuildConfig.FLAVOR.contentEquals("free")) {
3778 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3779 View adView = findViewById(R.id.adview);
3781 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3782 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
3783 AdHelper.initializeAds(adView, getApplicationContext(), this, getSupportFragmentManager(), getString(R.string.ad_unit_id));
3786 // Remove the `SYSTEM_UI` flags from the root frame layout.
3787 rootFrameLayout.setSystemUiVisibility(0);
3792 public void navigateHistory(String url, int steps) {
3793 // Apply the domain settings.
3794 applyDomainSettings(currentWebView, url, false, false, false);
3796 // Load the history entry.
3797 currentWebView.goBackOrForward(steps);
3801 public void pinnedErrorGoBack() {
3802 // Get the current web back forward list.
3803 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3805 // Get the previous entry URL.
3806 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3808 // Apply the domain settings.
3809 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3812 currentWebView.goBack();
3815 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3816 @SuppressLint("SetJavaScriptEnabled")
3817 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3818 // Store the current URL.
3819 nestedScrollWebView.setCurrentUrl(url);
3821 // Parse the URL into a URI.
3822 Uri uri = Uri.parse(url);
3824 // Extract the domain from `uri`.
3825 String newHostName = uri.getHost();
3827 // Strings don't like to be null.
3828 if (newHostName == null) {
3832 // 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.
3833 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3834 // Set the new host name as the current domain name.
3835 nestedScrollWebView.setCurrentDomainName(newHostName);
3837 // Reset the ignoring of pinned domain information.
3838 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3840 // Clear any pinned SSL certificate or IP addresses.
3841 nestedScrollWebView.clearPinnedSslCertificate();
3842 nestedScrollWebView.clearPinnedIpAddresses();
3844 // Reset the favorite icon if specified.
3846 // Initialize the favorite icon.
3847 nestedScrollWebView.initializeFavoriteIcon();
3849 // Get the current page position.
3850 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3852 // Get the corresponding tab.
3853 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3855 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3857 // Get the tab custom view.
3858 View tabCustomView = tab.getCustomView();
3860 // Remove the warning below that the tab custom view might be null.
3861 assert tabCustomView != null;
3863 // Get the tab views.
3864 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3865 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3867 // Set the default favorite icon as the favorite icon for this tab.
3868 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3870 // Set the loading title text.
3871 tabTitleTextView.setText(R.string.loading);
3875 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3876 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3878 // Get a full cursor from `domainsDatabaseHelper`.
3879 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3881 // Initialize `domainSettingsSet`.
3882 Set<String> domainSettingsSet = new HashSet<>();
3884 // Get the domain name column index.
3885 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3887 // Populate `domainSettingsSet`.
3888 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3889 // Move `domainsCursor` to the current row.
3890 domainNameCursor.moveToPosition(i);
3892 // Store the domain name in `domainSettingsSet`.
3893 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3896 // Close `domainNameCursor.
3897 domainNameCursor.close();
3899 // Initialize the domain name in database variable.
3900 String domainNameInDatabase = null;
3902 // Check the hostname against the domain settings set.
3903 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3904 // Record the domain name in the database.
3905 domainNameInDatabase = newHostName;
3907 // Set the domain settings applied tracker to true.
3908 nestedScrollWebView.setDomainSettingsApplied(true);
3909 } else { // The hostname is not contained in the domain settings set.
3910 // Set the domain settings applied tracker to false.
3911 nestedScrollWebView.setDomainSettingsApplied(false);
3914 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3915 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3916 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3917 // Set the domain settings applied tracker to true.
3918 nestedScrollWebView.setDomainSettingsApplied(true);
3920 // Store the applied domain names as it appears in the database.
3921 domainNameInDatabase = "*." + newHostName;
3924 // Strip out the lowest subdomain of of the host name.
3925 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3929 // Get a handle for the shared preferences.
3930 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3932 // Store the general preference information.
3933 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3934 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3935 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3936 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3937 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3938 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3940 // Get the WebView theme entry values string array.
3941 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3943 // Get a handle for the cookie manager.
3944 CookieManager cookieManager = CookieManager.getInstance();
3946 // Get handles for the views.
3947 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3948 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3950 // Initialize the user agent array adapter and string array.
3951 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3952 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3954 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3955 // Get a cursor for the current host and move it to the first position.
3956 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3957 currentDomainSettingsCursor.moveToFirst();
3959 // Get the settings from the cursor.
3960 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3961 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3962 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3963 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3964 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3965 // Form data can be removed once the minimum API >= 26.
3966 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3967 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3968 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3969 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3970 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3971 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3972 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3973 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3974 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3975 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3976 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3977 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3978 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3979 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3980 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3981 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3982 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3983 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WEBVIEW_THEME));
3984 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3985 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3986 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3987 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3988 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3989 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3990 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3991 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3992 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3993 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3994 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3996 // Get the pinned SSL date longs.
3997 long pinnedSslStartDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE));
3998 long pinnedSslEndDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE));
4000 // Define the pinned SSL date variables.
4001 Date pinnedSslStartDate;
4002 Date pinnedSslEndDate;
4004 // 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.
4005 if (pinnedSslStartDateLong == 0) {
4006 pinnedSslStartDate = null;
4008 pinnedSslStartDate = new Date(pinnedSslStartDateLong);
4011 // 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.
4012 if (pinnedSslEndDateLong == 0) {
4013 pinnedSslEndDate = null;
4015 pinnedSslEndDate = new Date(pinnedSslEndDateLong);
4018 // Close the current host domain settings cursor.
4019 currentDomainSettingsCursor.close();
4021 // If there is a pinned SSL certificate, store it in the WebView.
4022 if (pinnedSslCertificate) {
4023 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
4024 pinnedSslStartDate, pinnedSslEndDate);
4027 // If there is a pinned IP address, store it in the WebView.
4028 if (pinnedIpAddresses) {
4029 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
4032 // Apply the cookie domain settings.
4033 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4035 // Set third-party cookies status if API >= 21.
4036 if (Build.VERSION.SDK_INT >= 21) {
4037 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
4040 // Apply the form data setting if the API < 26.
4041 if (Build.VERSION.SDK_INT < 26) {
4042 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4045 // Apply the font size.
4046 try { // Try the specified font size to see if it is valid.
4047 if (fontSize == 0) { // Apply the default font size.
4048 // Try to set the font size from the value in the app settings.
4049 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4050 } else { // Apply the font size from domain settings.
4051 nestedScrollWebView.getSettings().setTextZoom(fontSize);
4053 } catch (Exception exception) { // The specified font size is invalid
4054 // Set the font size to be 100%
4055 nestedScrollWebView.getSettings().setTextZoom(100);
4058 // Set the user agent.
4059 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4060 // Get the array position of the default user agent name.
4061 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4063 // Set the user agent according to the system default.
4064 switch (defaultUserAgentArrayPosition) {
4065 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4066 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4067 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4070 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4071 // Set the user agent to `""`, which uses the default value.
4072 nestedScrollWebView.getSettings().setUserAgentString("");
4075 case SETTINGS_CUSTOM_USER_AGENT:
4076 // Set the default custom user agent.
4077 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4081 // Get the user agent string from the user agent data array
4082 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4084 } else { // Set the user agent according to the stored name.
4085 // Get the array position of the user agent name.
4086 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4088 switch (userAgentArrayPosition) {
4089 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4090 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
4093 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4094 // Set the user agent to `""`, which uses the default value.
4095 nestedScrollWebView.getSettings().setUserAgentString("");
4099 // Get the user agent string from the user agent data array.
4100 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4104 // Set swipe to refresh.
4105 switch (swipeToRefreshInt) {
4106 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4107 // Store the swipe to refresh status in the nested scroll WebView.
4108 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4110 // Update the swipe refresh layout.
4111 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4112 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4113 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4114 } else { // Swipe to refresh is disabled.
4115 // Disable the swipe refresh layout.
4116 swipeRefreshLayout.setEnabled(false);
4120 case DomainsDatabaseHelper.ENABLED:
4121 // Store the swipe to refresh status in the nested scroll WebView.
4122 nestedScrollWebView.setSwipeToRefresh(true);
4124 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4125 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4128 case DomainsDatabaseHelper.DISABLED:
4129 // Store the swipe to refresh status in the nested scroll WebView.
4130 nestedScrollWebView.setSwipeToRefresh(false);
4132 // Disable swipe to refresh.
4133 swipeRefreshLayout.setEnabled(false);
4136 // Check to see if WebView themes are supported.
4137 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4138 // Set the WebView theme.
4139 switch (webViewThemeInt) {
4140 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4141 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4142 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4143 // Turn off the WebView dark mode.
4144 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4145 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4146 // Turn on the WebView dark mode.
4147 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4148 } else { // The system default theme is selected.
4149 // Get the current system theme status.
4150 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4152 // Set the WebView theme according to the current system theme status.
4153 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4154 // Turn off the WebView dark mode.
4155 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4156 } else { // The system is in night mode.
4157 // Turn on the WebView dark mode.
4158 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4163 case DomainsDatabaseHelper.LIGHT_THEME:
4164 // Turn off the WebView dark mode.
4165 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4168 case DomainsDatabaseHelper.DARK_THEME:
4169 // Turn on the WebView dark mode.
4170 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4175 // Set the viewport.
4176 switch (wideViewportInt) {
4177 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4178 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4181 case DomainsDatabaseHelper.ENABLED:
4182 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4185 case DomainsDatabaseHelper.DISABLED:
4186 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4190 // Set the loading of webpage images.
4191 switch (displayWebpageImagesInt) {
4192 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4193 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4196 case DomainsDatabaseHelper.ENABLED:
4197 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4200 case DomainsDatabaseHelper.DISABLED:
4201 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4205 // Get the current theme status.
4206 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4208 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4209 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4210 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
4212 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
4214 } else { // The new URL does not have custom domain settings. Load the defaults.
4215 // Store the values from the shared preferences.
4216 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4217 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4218 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4219 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4220 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4221 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4222 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4223 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4224 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4225 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4226 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4227 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4229 // Apply the default first-party cookie setting.
4230 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4232 // Apply the default font size setting.
4234 // Try to set the font size from the value in the app settings.
4235 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4236 } catch (Exception exception) {
4237 // If the app settings value is invalid, set the font size to 100%.
4238 nestedScrollWebView.getSettings().setTextZoom(100);
4241 // Apply the form data setting if the API < 26.
4242 if (Build.VERSION.SDK_INT < 26) {
4243 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4246 // Store the swipe to refresh status in the nested scroll WebView.
4247 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4249 // Update the swipe refresh layout.
4250 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4251 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4252 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4253 } else { // Swipe to refresh is disabled.
4254 // Disable the swipe refresh layout.
4255 swipeRefreshLayout.setEnabled(false);
4258 // Reset the pinned variables.
4259 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4261 // Set third-party cookies status if API >= 21.
4262 if (Build.VERSION.SDK_INT >= 21) {
4263 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4266 // Get the array position of the user agent name.
4267 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4269 // Set the user agent.
4270 switch (userAgentArrayPosition) {
4271 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4272 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4273 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4276 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4277 // Set the user agent to `""`, which uses the default value.
4278 nestedScrollWebView.getSettings().setUserAgentString("");
4281 case SETTINGS_CUSTOM_USER_AGENT:
4282 // Set the default custom user agent.
4283 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4287 // Get the user agent string from the user agent data array
4288 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4291 // Apply the WebView theme if supported by the installed WebView.
4292 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4293 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4294 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4295 // Turn off the WebView dark mode.
4296 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4297 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4298 // Turn on the WebView dark mode.
4299 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4300 } else { // The system default theme is selected.
4301 // Get the current system theme status.
4302 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4304 // Set the WebView theme according to the current system theme status.
4305 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4306 // Turn off the WebView dark mode.
4307 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4308 } else { // The system is in night mode.
4309 // Turn on the WebView dark mode.
4310 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4315 // Set the viewport.
4316 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4318 // Set the loading of webpage images.
4319 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4321 // Set a transparent background on URL edit text.
4322 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4325 // Close the domains database helper.
4326 domainsDatabaseHelper.close();
4328 // Update the privacy icons.
4329 updatePrivacyIcons(true);
4332 // Reload the website if returning from the Domains activity.
4333 if (reloadWebsite) {
4334 nestedScrollWebView.reload();
4337 // 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.
4339 nestedScrollWebView.loadUrl(url, customHeaders);
4343 private void applyProxy(boolean reloadWebViews) {
4344 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4345 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4347 // Reset the waiting for proxy tracker.
4348 waitingForProxy = false;
4350 // Get the current theme status.
4351 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4353 // Update the user interface and reload the WebViews if requested.
4354 switch (proxyMode) {
4355 case ProxyHelper.NONE:
4356 // Initialize a color background typed value.
4357 TypedValue colorBackgroundTypedValue = new TypedValue();
4359 // Get the color background from the theme.
4360 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4362 // Get the color background int from the typed value.
4363 int colorBackgroundInt = colorBackgroundTypedValue.data;
4365 // Set the default app bar layout background.
4366 appBarLayout.setBackgroundColor(colorBackgroundInt);
4369 case ProxyHelper.TOR:
4370 // Set the app bar background to indicate proxying through Orbot is enabled.
4371 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4372 appBarLayout.setBackgroundResource(R.color.blue_50);
4374 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4377 // Check to see if Orbot is installed.
4379 // Get the package manager.
4380 PackageManager packageManager = getPackageManager();
4382 // 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.
4383 packageManager.getPackageInfo("org.torproject.android", 0);
4385 // Check to see if the proxy is ready.
4386 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4387 // Set the waiting for proxy status.
4388 waitingForProxy = true;
4390 // Show the waiting for proxy dialog if it isn't already displayed.
4391 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4392 // Get a handle for the waiting for proxy alert dialog.
4393 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4395 // Display the waiting for proxy alert dialog.
4396 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4399 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4400 // Show the Orbot not installed dialog if it is not already displayed.
4401 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4402 // Get a handle for the Orbot not installed alert dialog.
4403 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4405 // Display the Orbot not installed alert dialog.
4406 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4411 case ProxyHelper.I2P:
4412 // Set the app bar background to indicate proxying through Orbot is enabled.
4413 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4414 appBarLayout.setBackgroundResource(R.color.blue_50);
4416 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4419 // Check to see if I2P is installed.
4421 // Get the package manager.
4422 PackageManager packageManager = getPackageManager();
4424 // 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.
4425 packageManager.getPackageInfo("org.torproject.android", 0);
4426 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4427 // Sow the I2P not installed dialog if it is not already displayed.
4428 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4429 // Get a handle for the waiting for proxy alert dialog.
4430 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4432 // Display the I2P not installed alert dialog.
4433 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4438 case ProxyHelper.CUSTOM:
4439 // Set the app bar background to indicate proxying through Orbot is enabled.
4440 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4441 appBarLayout.setBackgroundResource(R.color.blue_50);
4443 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4448 // Reload the WebViews if requested and not waiting for the proxy.
4449 if (reloadWebViews && !waitingForProxy) {
4450 // Reload the WebViews.
4451 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4452 // Get the WebView tab fragment.
4453 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4455 // Get the fragment view.
4456 View fragmentView = webViewTabFragment.getView();
4458 // Only reload the WebViews if they exist.
4459 if (fragmentView != null) {
4460 // Get the nested scroll WebView from the tab fragment.
4461 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4463 // Reload the WebView.
4464 nestedScrollWebView.reload();
4470 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4471 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4472 if ((optionsMenu != null) && (currentWebView != null)) {
4473 // Update the privacy icon.
4474 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4475 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4476 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4477 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4478 } else { // All the dangerous features are disabled.
4479 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4482 // Get the current theme status.
4483 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4485 // Update the first-party cookies icon.
4486 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4487 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4488 } else { // First-party cookies are disabled.
4489 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4490 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4492 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4496 // Update the refresh icon.
4497 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4498 // Set the icon according to the theme.
4499 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4500 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4502 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4504 } else { // The stop icon is displayed.
4505 // Set the icon according to the theme.
4506 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4507 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
4509 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
4513 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4514 if (runInvalidateOptionsMenu) {
4515 invalidateOptionsMenu();
4520 private void highlightUrlText() {
4521 // Get a handle for the URL edit text.
4522 EditText urlEditText = findViewById(R.id.url_edittext);
4524 // Only highlight the URL text if the box is not currently selected.
4525 if (!urlEditText.hasFocus()) {
4526 // Get the URL string.
4527 String urlString = urlEditText.getText().toString();
4529 // Highlight the URL according to the protocol.
4530 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4531 // De-emphasize everything before the file name.
4532 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4533 } else { // This is a web URL.
4534 // Get the index of the `/` immediately after the domain name.
4535 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4537 // Create a base URL string.
4540 // Get the base URL.
4541 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4542 // Get the base URL.
4543 baseUrl = urlString.substring(0, endOfDomainName);
4544 } else { // There are no characters after the base URL.
4545 // Set the base URL to be the entire URL string.
4546 baseUrl = urlString;
4549 // Get the index of the last `.` in the domain.
4550 int lastDotIndex = baseUrl.lastIndexOf(".");
4552 // Get the index of the penultimate `.` in the domain.
4553 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4555 // Markup the beginning of the URL.
4556 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4557 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4559 // De-emphasize subdomains.
4560 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4561 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4563 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4564 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4565 // De-emphasize the protocol and the additional subdomains.
4566 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4567 } else { // There is only one subdomain in the domain name.
4568 // De-emphasize only the protocol.
4569 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4573 // De-emphasize the text after the domain name.
4574 if (endOfDomainName > 0) {
4575 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4581 private void loadBookmarksFolder() {
4582 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4583 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4585 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4586 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4588 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4589 // Inflate the individual item layout. `false` does not attach it to the root.
4590 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4594 public void bindView(View view, Context context, Cursor cursor) {
4595 // Get handles for the views.
4596 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4597 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4599 // Get the favorite icon byte array from the cursor.
4600 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4602 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4603 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4605 // Display the bitmap in `bookmarkFavoriteIcon`.
4606 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4608 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4609 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4610 bookmarkNameTextView.setText(bookmarkNameString);
4612 // Make the font bold for folders.
4613 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4614 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4615 } else { // Reset the font to default for normal bookmarks.
4616 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4621 // Get a handle for the bookmarks list view.
4622 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4624 // Populate the list view with the adapter.
4625 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4627 // Get a handle for the bookmarks title text view.
4628 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4630 // Set the bookmarks drawer title.
4631 if (currentBookmarksFolder.isEmpty()) {
4632 bookmarksTitleTextView.setText(R.string.bookmarks);
4634 bookmarksTitleTextView.setText(currentBookmarksFolder);
4638 private void openWithApp(String url) {
4639 // Create an open with app intent with `ACTION_VIEW`.
4640 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4642 // Set the URI but not the MIME type. This should open all available apps.
4643 openWithAppIntent.setData(Uri.parse(url));
4645 // Flag the intent to open in a new task.
4646 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4650 // Show the chooser.
4651 startActivity(openWithAppIntent);
4652 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4653 // Show a snackbar with the error.
4654 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4658 private void openWithBrowser(String url) {
4659 // Create an open with browser intent with `ACTION_VIEW`.
4660 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4662 // Set the URI and the MIME type. `"text/html"` should load browser options.
4663 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4665 // Flag the intent to open in a new task.
4666 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4670 // Show the chooser.
4671 startActivity(openWithBrowserIntent);
4672 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4673 // Show a snackbar with the error.
4674 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4678 private String sanitizeUrl(String url) {
4679 // Sanitize Google Analytics.
4680 if (sanitizeGoogleAnalytics) {
4682 if (url.contains("?utm_")) {
4683 url = url.substring(0, url.indexOf("?utm_"));
4687 if (url.contains("&utm_")) {
4688 url = url.substring(0, url.indexOf("&utm_"));
4692 // Sanitize Facebook Click IDs.
4693 if (sanitizeFacebookClickIds) {
4694 // Remove `?fbclid=`.
4695 if (url.contains("?fbclid=")) {
4696 url = url.substring(0, url.indexOf("?fbclid="));
4699 // Remove `&fbclid=`.
4700 if (url.contains("&fbclid=")) {
4701 url = url.substring(0, url.indexOf("&fbclid="));
4704 // Remove `?fbadid=`.
4705 if (url.contains("?fbadid=")) {
4706 url = url.substring(0, url.indexOf("?fbadid="));
4709 // Remove `&fbadid=`.
4710 if (url.contains("&fbadid=")) {
4711 url = url.substring(0, url.indexOf("&fbadid="));
4715 // Sanitize Twitter AMP redirects.
4716 if (sanitizeTwitterAmpRedirects) {
4718 if (url.contains("?amp=1")) {
4719 url = url.substring(0, url.indexOf("?amp=1"));
4723 // Return the sanitized URL.
4727 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4728 // Store the blocklists.
4729 easyList = combinedBlocklists.get(0);
4730 easyPrivacy = combinedBlocklists.get(1);
4731 fanboysAnnoyanceList = combinedBlocklists.get(2);
4732 fanboysSocialList = combinedBlocklists.get(3);
4733 ultraList = combinedBlocklists.get(4);
4734 ultraPrivacy = combinedBlocklists.get(5);
4736 // Check to see if the activity has been restarted with a saved state.
4737 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4738 // Add the first tab.
4739 addNewTab("", true);
4740 } else { // The activity has been restarted.
4741 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4742 for (int i = 0; i < savedStateArrayList.size(); i++) {
4744 tabLayout.addTab(tabLayout.newTab());
4747 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4749 // Remove the lint warning below that the current tab might be null.
4750 assert newTab != null;
4752 // Set a custom view on the new tab.
4753 newTab.setCustomView(R.layout.tab_custom_view);
4755 // Add the new page.
4756 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4759 // Reset the saved state variables.
4760 savedStateArrayList = null;
4761 savedNestedScrollWebViewStateArrayList = null;
4763 // Restore the selected tab position.
4764 if (savedTabPosition == 0) { // The first tab is selected.
4765 // Set the first page as the current WebView.
4766 setCurrentWebView(0);
4767 } else { // the first tab is not selected.
4768 // Move to the selected tab.
4769 webViewPager.setCurrentItem(savedTabPosition);
4772 // Get the intent that started the app.
4773 Intent intent = getIntent();
4775 // Reset the intent. This prevents a duplicate tab from being created on restart.
4776 setIntent(new Intent());
4778 // Get the information from the intent.
4779 String intentAction = intent.getAction();
4780 Uri intentUriData = intent.getData();
4781 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4783 // Determine if this is a web search.
4784 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4786 // 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.
4787 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4788 // Get the shared preferences.
4789 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4791 // Create a URL string.
4794 // If the intent action is a web search, perform the search.
4795 if (isWebSearch) { // The intent is a web search.
4796 // Create an encoded URL string.
4797 String encodedUrlString;
4799 // Sanitize the search input and convert it to a search.
4801 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4802 } catch (UnsupportedEncodingException exception) {
4803 encodedUrlString = "";
4806 // Add the base search URL.
4807 url = searchURL + encodedUrlString;
4808 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4809 // Set the intent data as the URL.
4810 url = intentUriData.toString();
4811 } else { // The intent contains a string, which might be a URL.
4812 // Set the intent string as the URL.
4813 url = intentStringExtra;
4816 // Add a new tab if specified in the preferences.
4817 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4818 // Set the loading new intent flag.
4819 loadingNewIntent = true;
4822 addNewTab(url, true);
4823 } else { // Load the URL in the current tab.
4825 loadUrl(currentWebView, url);
4831 public void addTab(View view) {
4832 // Add a new tab with a blank URL.
4833 addNewTab("", true);
4836 private void addNewTab(String url, boolean moveToTab) {
4837 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4838 int newTabNumber = tabLayout.getTabCount();
4841 tabLayout.addTab(tabLayout.newTab());
4844 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4846 // Remove the lint warning below that the current tab might be null.
4847 assert newTab != null;
4849 // Set a custom view on the new tab.
4850 newTab.setCustomView(R.layout.tab_custom_view);
4852 // Add the new WebView page.
4853 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4856 public void closeTab(View view) {
4857 // Run the command according to the number of tabs.
4858 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4859 // Close the current tab.
4861 } else { // There is only one tab open.
4866 private void closeCurrentTab() {
4867 // Pause the current WebView. This prevents buffered audio from playing after the tab is closed.
4868 currentWebView.onPause();
4870 // Get the current tab number.
4871 int currentTabNumber = tabLayout.getSelectedTabPosition();
4873 // Delete the current tab.
4874 tabLayout.removeTabAt(currentTabNumber);
4876 // Delete the current page. If the selected page number did not change during the delete, it will return true, meaning that the current WebView must be reset.
4877 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4878 setCurrentWebView(currentTabNumber);
4881 // Expand the app bar if it is currently collapsed.
4882 appBarLayout.setExpanded(true);
4885 private void saveWebpageArchive(String filePath) {
4886 // Save the webpage archive.
4887 currentWebView.saveWebArchive(filePath);
4889 // Display a snackbar.
4890 Snackbar saveWebpageArchiveSnackbar = Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + filePath, Snackbar.LENGTH_SHORT);
4892 // Add an open option to the snackbar.
4893 saveWebpageArchiveSnackbar.setAction(R.string.open, (View view) -> {
4894 // Get a file for the file name string.
4895 File file = new File(filePath);
4897 // Declare a file URI variable.
4900 // Get the URI for the file according to the Android version.
4901 if (Build.VERSION.SDK_INT >= 24) { // Use a file provider.
4902 fileUri = FileProvider.getUriForFile(this, getString(R.string.file_provider), file);
4903 } else { // Get the raw file path URI.
4904 fileUri = Uri.fromFile(file);
4907 // Get a handle for the content resolver.
4908 ContentResolver contentResolver = getContentResolver();
4910 // Create an open intent with `ACTION_VIEW`.
4911 Intent openIntent = new Intent(Intent.ACTION_VIEW);
4913 // Set the URI and the MIME type.
4914 openIntent.setDataAndType(fileUri, contentResolver.getType(fileUri));
4916 // Allow the app to read the file URI.
4917 openIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
4919 // Show the chooser.
4920 startActivity(Intent.createChooser(openIntent, getString(R.string.open)));
4923 // Show the snackbar.
4924 saveWebpageArchiveSnackbar.show();
4927 private void clearAndExit() {
4928 // Get a handle for the shared preferences.
4929 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4931 // Close the bookmarks cursor and database.
4932 bookmarksCursor.close();
4933 bookmarksDatabaseHelper.close();
4935 // Get the status of the clear everything preference.
4936 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4938 // Get a handle for the runtime.
4939 Runtime runtime = Runtime.getRuntime();
4941 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4942 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4943 String privateDataDirectoryString = getApplicationInfo().dataDir;
4946 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4947 // The command to remove cookies changed slightly in API 21.
4948 if (Build.VERSION.SDK_INT >= 21) {
4949 CookieManager.getInstance().removeAllCookies(null);
4951 CookieManager.getInstance().removeAllCookie();
4954 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4956 // Two commands must be used because `Runtime.exec()` does not like `*`.
4957 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4958 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4960 // Wait until the processes have finished.
4961 deleteCookiesProcess.waitFor();
4962 deleteCookiesJournalProcess.waitFor();
4963 } catch (Exception exception) {
4964 // Do nothing if an error is thrown.
4968 // Clear DOM storage.
4969 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4970 // Ask `WebStorage` to clear the DOM storage.
4971 WebStorage webStorage = WebStorage.getInstance();
4972 webStorage.deleteAllData();
4974 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4976 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4977 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4979 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4980 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4981 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4982 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4983 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4985 // Wait until the processes have finished.
4986 deleteLocalStorageProcess.waitFor();
4987 deleteIndexProcess.waitFor();
4988 deleteQuotaManagerProcess.waitFor();
4989 deleteQuotaManagerJournalProcess.waitFor();
4990 deleteDatabaseProcess.waitFor();
4991 } catch (Exception exception) {
4992 // Do nothing if an error is thrown.
4996 // Clear form data if the API < 26.
4997 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4998 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4999 webViewDatabase.clearFormData();
5001 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
5003 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
5004 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
5005 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
5007 // Wait until the processes have finished.
5008 deleteWebDataProcess.waitFor();
5009 deleteWebDataJournalProcess.waitFor();
5010 } catch (Exception exception) {
5011 // Do nothing if an error is thrown.
5015 // Clear the logcat.
5016 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
5018 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5019 Process process = Runtime.getRuntime().exec("logcat -b all -c");
5021 // Wait for the process to finish.
5023 } catch (IOException|InterruptedException exception) {
5029 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
5030 // Clear the cache from each WebView.
5031 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
5032 // Get the WebView tab fragment.
5033 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
5035 // Get the fragment view.
5036 View fragmentView = webViewTabFragment.getView();
5038 // Only clear the cache if the WebView exists.
5039 if (fragmentView != null) {
5040 // Get the nested scroll WebView from the tab fragment.
5041 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
5043 // Clear the cache for this WebView.
5044 nestedScrollWebView.clearCache(true);
5048 // Manually delete the cache directories.
5050 // Delete the main cache directory.
5051 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
5053 // Delete the secondary `Service Worker` cache directory.
5054 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
5055 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
5057 // Wait until the processes have finished.
5058 deleteCacheProcess.waitFor();
5059 deleteServiceWorkerProcess.waitFor();
5060 } catch (Exception exception) {
5061 // Do nothing if an error is thrown.
5065 // Wipe out each WebView.
5066 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
5067 // Get the WebView tab fragment.
5068 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
5070 // Get the fragment view.
5071 View fragmentView = webViewTabFragment.getView();
5073 // Only wipe out the WebView if it exists.
5074 if (fragmentView != null) {
5075 // Get the nested scroll WebView from the tab fragment.
5076 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
5078 // Clear SSL certificate preferences for this WebView.
5079 nestedScrollWebView.clearSslPreferences();
5081 // Clear the back/forward history for this WebView.
5082 nestedScrollWebView.clearHistory();
5084 // Destroy the internal state of the WebView.
5085 nestedScrollWebView.destroy();
5089 // Clear the custom headers.
5090 customHeaders.clear();
5092 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
5093 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
5094 if (clearEverything) {
5096 // Delete the folder.
5097 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
5099 // Wait until the process has finished.
5100 deleteAppWebviewProcess.waitFor();
5101 } catch (Exception exception) {
5102 // Do nothing if an error is thrown.
5106 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
5107 if (Build.VERSION.SDK_INT >= 21) {
5108 finishAndRemoveTask();
5113 // Remove the terminated program from RAM. The status code is `0`.
5117 public void bookmarksBack(View view) {
5118 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
5119 // close the bookmarks drawer.
5120 drawerLayout.closeDrawer(GravityCompat.END);
5121 } else { // A subfolder is displayed.
5122 // Place the former parent folder in `currentFolder`.
5123 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
5125 // Load the new folder.
5126 loadBookmarksFolder();
5130 private void setCurrentWebView(int pageNumber) {
5131 // Get handles for the URL views.
5132 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
5133 EditText urlEditText = findViewById(R.id.url_edittext);
5134 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
5136 // Stop the swipe to refresh indicator if it is running
5137 swipeRefreshLayout.setRefreshing(false);
5139 // Get the WebView tab fragment.
5140 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
5142 // Get the fragment view.
5143 View fragmentView = webViewTabFragment.getView();
5145 // Set the current WebView if the fragment view is not null.
5146 if (fragmentView != null) { // The fragment has been populated.
5147 // Store the current WebView.
5148 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
5150 // Update the status of swipe to refresh.
5151 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
5152 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5153 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
5154 } else { // Swipe to refresh is disabled.
5155 // Disable the swipe refresh layout.
5156 swipeRefreshLayout.setEnabled(false);
5159 // Get a handle for the cookie manager.
5160 CookieManager cookieManager = CookieManager.getInstance();
5162 // Set the first-party cookie status.
5163 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
5165 // Update the privacy icons. `true` redraws the icons in the app bar.
5166 updatePrivacyIcons(true);
5168 // Get a handle for the input method manager.
5169 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5171 // Remove the lint warning below that the input method manager might be null.
5172 assert inputMethodManager != null;
5174 // Get the current URL.
5175 String url = currentWebView.getUrl();
5177 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5178 if (!loadingNewIntent) { // A new intent is not being loaded.
5179 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5180 // Display the hint in the URL edit text.
5181 urlEditText.setText("");
5183 // Request focus for the URL text box.
5184 urlEditText.requestFocus();
5186 // Display the keyboard.
5187 inputMethodManager.showSoftInput(urlEditText, 0);
5188 } else { // The WebView has a loaded URL.
5189 // Clear the focus from the URL text box.
5190 urlEditText.clearFocus();
5192 // Hide the soft keyboard.
5193 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5195 // Display the current URL in the URL text box.
5196 urlEditText.setText(url);
5198 // Highlight the URL text.
5201 } else { // A new intent is being loaded.
5202 // Reset the loading new intent tracker.
5203 loadingNewIntent = false;
5206 // Set the background to indicate the domain settings status.
5207 if (currentWebView.getDomainSettingsApplied()) {
5208 // Get the current theme status.
5209 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5211 // Set a green background on the URL relative layout to indicate that custom domain settings are being used.
5212 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
5213 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
5215 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
5218 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5220 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5221 // Create a handler to set the current WebView.
5222 Handler setCurrentWebViewHandler = new Handler();
5224 // Create a runnable to set the current WebView.
5225 Runnable setCurrentWebWebRunnable = () -> {
5226 // Set the current WebView.
5227 setCurrentWebView(pageNumber);
5230 // Try setting the current WebView again after 100 milliseconds.
5231 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5236 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5237 // Get a handle for the shared preferences.
5238 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5240 // Get the WebView theme.
5241 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5243 // Get the WebView theme entry values string array.
5244 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5246 // Apply the WebView theme if supported by the installed WebView.
5247 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5248 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5249 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5250 // Turn off the WebView dark mode.
5251 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5253 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5254 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5255 nestedScrollWebView.setVisibility(View.VISIBLE);
5256 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5257 // Turn on the WebView dark mode.
5258 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5259 } else { // The system default theme is selected.
5260 // Get the current system theme status.
5261 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5263 // Set the WebView theme according to the current system theme status.
5264 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5265 // Turn off the WebView dark mode.
5266 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5268 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5269 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5270 nestedScrollWebView.setVisibility(View.VISIBLE);
5271 } else { // The system is in night mode.
5272 // Turn on the WebView dark mode.
5273 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5278 // Get handles for the activity views.
5279 EditText urlEditText = findViewById(R.id.url_edittext);
5281 // Get a handle for the activity
5282 Activity activity = this;
5284 // Get a handle for the input method manager.
5285 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5287 // Instantiate the blocklist helper.
5288 BlocklistHelper blocklistHelper = new BlocklistHelper();
5290 // Remove the lint warning below that the input method manager might be null.
5291 assert inputMethodManager != null;
5293 // Initialize the favorite icon.
5294 nestedScrollWebView.initializeFavoriteIcon();
5296 // Set the app bar scrolling.
5297 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5299 // Allow pinch to zoom.
5300 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5302 // Hide zoom controls.
5303 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5305 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5306 if (Build.VERSION.SDK_INT >= 21) {
5307 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5310 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5311 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5313 // Explicitly disable geolocation.
5314 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5316 // Create a double-tap gesture detector to toggle full-screen mode.
5317 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5318 // Override `onDoubleTap()`. All other events are handled using the default settings.
5320 public boolean onDoubleTap(MotionEvent event) {
5321 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5322 // Toggle the full screen browsing mode tracker.
5323 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5325 // Toggle the full screen browsing mode.
5326 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5327 // Hide the app bar if specified.
5329 // Close the find on page bar if it is visible.
5330 closeFindOnPage(null);
5332 // Hide the tab linear layout.
5333 tabsLinearLayout.setVisibility(View.GONE);
5335 // Hide the action bar.
5338 // Check to see if the app bar is normally scrolled.
5339 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5340 // Get the swipe refresh layout parameters.
5341 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5343 // Remove the off-screen scrolling layout.
5344 swipeRefreshLayoutParams.setBehavior(null);
5345 } else { // The app bar is not scrolled when it is displayed.
5346 // Remove the padding from the top of the swipe refresh layout.
5347 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5349 // The swipe refresh circle must be moved above the now removed status bar location.
5350 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5354 // Hide the banner ad in the free flavor.
5355 if (BuildConfig.FLAVOR.contentEquals("free")) {
5356 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5357 View adView = findViewById(R.id.adview);
5359 // Hide the banner ad.
5360 AdHelper.hideAd(adView);
5363 /* Hide the system bars.
5364 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5365 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5366 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5367 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5369 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5370 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5371 } else { // Switch to normal viewing mode.
5372 // Show the app bar if it was hidden.
5374 // Show the tab linear layout.
5375 tabsLinearLayout.setVisibility(View.VISIBLE);
5377 // Show the action bar.
5380 // Check to see if the app bar is normally scrolled.
5381 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5382 // Get the swipe refresh layout parameters.
5383 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5385 // Add the off-screen scrolling layout.
5386 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5387 } else { // The app bar is not scrolled when it is displayed.
5388 // The swipe refresh layout must be manually moved below the app bar layout.
5389 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5391 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5392 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5396 // Show the banner ad in the free flavor.
5397 if (BuildConfig.FLAVOR.contentEquals("free")) {
5398 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5399 View adView = findViewById(R.id.adview);
5401 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5402 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5405 // Remove the `SYSTEM_UI` flags from the root frame layout.
5406 rootFrameLayout.setSystemUiVisibility(0);
5409 // Consume the double-tap.
5411 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5417 // Pass all touch events on the WebView through the double-tap gesture detector.
5418 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5419 // Call `performClick()` on the view, which is required for accessibility.
5420 view.performClick();
5422 // Send the event to the gesture detector.
5423 return doubleTapGestureDetector.onTouchEvent(event);
5426 // Register the WebView for a context menu. This is used to see link targets and download images.
5427 registerForContextMenu(nestedScrollWebView);
5429 // Allow the downloading of files.
5430 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5431 // Define a formatted file size string.
5432 String formattedFileSizeString;
5434 // Process the content length if it contains data.
5435 if (contentLength > 0) { // The content length is greater than 0.
5436 // Format the content length as a string.
5437 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5438 } else { // The content length is not greater than 0.
5439 // Set the formatted file size string to be `unknown size`.
5440 formattedFileSizeString = getString(R.string.unknown_size);
5443 // Get the file name from the content disposition.
5444 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5446 // Instantiate the save dialog.
5447 DialogFragment saveDialogFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_URL, downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5448 nestedScrollWebView.getAcceptFirstPartyCookies());
5450 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5451 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5454 // Update the find on page count.
5455 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5456 // Get a handle for `findOnPageCountTextView`.
5457 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5460 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5461 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5462 // Set `findOnPageCountTextView` to `0/0`.
5463 findOnPageCountTextView.setText(R.string.zero_of_zero);
5464 } else if (isDoneCounting) { // There are matches.
5465 // `activeMatchOrdinal` is zero-based.
5466 int activeMatch = activeMatchOrdinal + 1;
5468 // Build the match string.
5469 String matchString = activeMatch + "/" + numberOfMatches;
5471 // Set `findOnPageCountTextView`.
5472 findOnPageCountTextView.setText(matchString);
5477 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5478 // 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.
5479 if (Build.VERSION.SDK_INT >= 23) {
5480 nestedScrollWebView.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
5481 if (nestedScrollWebView.getSwipeToRefresh()) {
5482 // Only enable swipe to refresh if the WebView is scrolled to the top.
5483 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5485 // Disable swipe to refresh.
5486 swipeRefreshLayout.setEnabled(false);
5489 // Reinforce the system UI visibility flags if in full screen browsing mode.
5490 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5491 if (inFullScreenBrowsingMode) {
5492 /* Hide the system bars.
5493 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5494 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5495 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5496 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5498 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5499 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5503 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5504 if (nestedScrollWebView.getSwipeToRefresh()) {
5505 // Only enable swipe to refresh if the WebView is scrolled to the top.
5506 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5508 // Disable swipe to refresh.
5509 swipeRefreshLayout.setEnabled(false);
5513 // Reinforce the system UI visibility flags if in full screen browsing mode.
5514 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5515 if (inFullScreenBrowsingMode) {
5516 /* Hide the system bars.
5517 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5518 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5519 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5520 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5522 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5523 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5528 // Set the web chrome client.
5529 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5530 // Update the progress bar when a page is loading.
5532 public void onProgressChanged(WebView view, int progress) {
5533 // Update the progress bar.
5534 progressBar.setProgress(progress);
5536 // Set the visibility of the progress bar.
5537 if (progress < 100) {
5538 // Show the progress bar.
5539 progressBar.setVisibility(View.VISIBLE);
5541 // Hide the progress bar.
5542 progressBar.setVisibility(View.GONE);
5544 //Stop the swipe to refresh indicator if it is running
5545 swipeRefreshLayout.setRefreshing(false);
5547 // 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.
5548 nestedScrollWebView.setVisibility(View.VISIBLE);
5552 // Set the favorite icon when it changes.
5554 public void onReceivedIcon(WebView view, Bitmap icon) {
5555 // Only update the favorite icon if the website has finished loading.
5556 if (progressBar.getVisibility() == View.GONE) {
5557 // Store the new favorite icon.
5558 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5560 // Get the current page position.
5561 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5563 // Get the current tab.
5564 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5566 // Check to see if the tab has been populated.
5568 // Get the custom view from the tab.
5569 View tabView = tab.getCustomView();
5571 // Check to see if the custom tab view has been populated.
5572 if (tabView != null) {
5573 // Get the favorite icon image view from the tab.
5574 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5576 // Display the favorite icon in the tab.
5577 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5583 // Save a copy of the title when it changes.
5585 public void onReceivedTitle(WebView view, String title) {
5586 // Get the current page position.
5587 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5589 // Get the current tab.
5590 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5592 // Only populate the title text view if the tab has been fully created.
5594 // Get the custom view from the tab.
5595 View tabView = tab.getCustomView();
5597 // Only populate the title text view if the tab view has been fully populated.
5598 if (tabView != null) {
5599 // Get the title text view from the tab.
5600 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5602 // Set the title according to the URL.
5603 if (title.equals("about:blank")) {
5604 // Set the title to indicate a new tab.
5605 tabTitleTextView.setText(R.string.new_tab);
5607 // Set the title as the tab text.
5608 tabTitleTextView.setText(title);
5614 // Enter full screen video.
5616 public void onShowCustomView(View video, CustomViewCallback callback) {
5617 // Set the full screen video flag.
5618 displayingFullScreenVideo = true;
5620 // Pause the ad if this is the free flavor.
5621 if (BuildConfig.FLAVOR.contentEquals("free")) {
5622 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5623 View adView = findViewById(R.id.adview);
5625 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5626 AdHelper.pauseAd(adView);
5629 // Hide the keyboard.
5630 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5632 // Hide the main content relative layout.
5633 mainContentRelativeLayout.setVisibility(View.GONE);
5635 /* Hide the system bars.
5636 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5637 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5638 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5639 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5641 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5642 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5644 // Disable the sliding drawers.
5645 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5647 // Add the video view to the full screen video frame layout.
5648 fullScreenVideoFrameLayout.addView(video);
5650 // Show the full screen video frame layout.
5651 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5653 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5654 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5657 // Exit full screen video.
5659 public void onHideCustomView() {
5660 // Re-enable the screen timeout.
5661 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5663 // Unset the full screen video flag.
5664 displayingFullScreenVideo = false;
5666 // Remove all the views from the full screen video frame layout.
5667 fullScreenVideoFrameLayout.removeAllViews();
5669 // Hide the full screen video frame layout.
5670 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5672 // Enable the sliding drawers.
5673 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5675 // Show the main content relative layout.
5676 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5678 // Apply the appropriate full screen mode flags.
5679 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5680 // Hide the app bar if specified.
5682 // Hide the tab linear layout.
5683 tabsLinearLayout.setVisibility(View.GONE);
5685 // Hide the action bar.
5689 // Hide the banner ad in the free flavor.
5690 if (BuildConfig.FLAVOR.contentEquals("free")) {
5691 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5692 View adView = findViewById(R.id.adview);
5694 // Hide the banner ad.
5695 AdHelper.hideAd(adView);
5698 /* Hide the system bars.
5699 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5700 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5701 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5702 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5704 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5705 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5706 } else { // Switch to normal viewing mode.
5707 // Remove the `SYSTEM_UI` flags from the root frame layout.
5708 rootFrameLayout.setSystemUiVisibility(0);
5711 // Reload the ad for the free flavor if not in full screen mode.
5712 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5713 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5714 View adView = findViewById(R.id.adview);
5716 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5717 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5723 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5724 // Show the file chooser if the device is running API >= 21.
5725 if (Build.VERSION.SDK_INT >= 21) {
5726 // Store the file path callback.
5727 fileChooserCallback = filePathCallback;
5729 // Create an intent to open a chooser based on the file chooser parameters.
5730 Intent fileChooserIntent = fileChooserParams.createIntent();
5732 // Get a handle for the package manager.
5733 PackageManager packageManager = getPackageManager();
5735 // Check to see if the file chooser intent resolves to an installed package.
5736 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5737 // Start the file chooser intent.
5738 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5739 } else { // The file chooser intent will cause a crash.
5740 // Create a generic intent to open a chooser.
5741 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5743 // Request an openable file.
5744 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5746 // Set the file type to everything.
5747 genericFileChooserIntent.setType("*/*");
5749 // Start the generic file chooser intent.
5750 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5757 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5758 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5759 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5761 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5762 // Sanitize the url.
5763 url = sanitizeUrl(url);
5765 // Handle the URL according to the type.
5766 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5767 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5768 loadUrl(nestedScrollWebView, url);
5770 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5771 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5773 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5774 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5775 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5777 // Parse the url and set it as the data for the intent.
5778 emailIntent.setData(Uri.parse(url));
5780 // Open the email program in a new task instead of as part of Privacy Browser.
5781 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5785 startActivity(emailIntent);
5786 } catch (ActivityNotFoundException exception) {
5787 // Display a snackbar.
5788 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5792 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5794 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5795 // Open the dialer and load the phone number, but wait for the user to place the call.
5796 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5798 // Add the phone number to the intent.
5799 dialIntent.setData(Uri.parse(url));
5801 // Open the dialer in a new task instead of as part of Privacy Browser.
5802 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5806 startActivity(dialIntent);
5807 } catch (ActivityNotFoundException exception) {
5808 // Display a snackbar.
5809 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5812 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5814 } else { // Load a system chooser to select an app that can handle the URL.
5815 // Open an app that can handle the URL.
5816 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5818 // Add the URL to the intent.
5819 genericIntent.setData(Uri.parse(url));
5821 // List all apps that can handle the URL instead of just opening the first one.
5822 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5824 // Open the app in a new task instead of as part of Privacy Browser.
5825 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5827 // Start the app or display a snackbar if no app is available to handle the URL.
5829 startActivity(genericIntent);
5830 } catch (ActivityNotFoundException exception) {
5831 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5834 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5839 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5841 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5842 // Check to see if the resource request is for the main URL.
5843 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5844 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5848 // 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.
5849 while (ultraPrivacy == null) {
5850 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5851 synchronized (this) {
5853 // Check to see if the blocklists have been populated after 100 ms.
5855 } catch (InterruptedException exception) {
5861 // Sanitize the URL.
5862 url = sanitizeUrl(url);
5864 // Create an empty web resource response to be used if the resource request is blocked.
5865 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5867 // Reset the whitelist results tracker.
5868 String[] whitelistResultStringArray = null;
5870 // Initialize the third party request tracker.
5871 boolean isThirdPartyRequest = false;
5873 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5874 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5876 // Store a copy of the current domain for use in later requests.
5877 String currentDomain = currentBaseDomain;
5879 // Nobody is happy when comparing null strings.
5880 if ((currentBaseDomain != null) && (url != null)) {
5881 // Convert the request URL to a URI.
5882 Uri requestUri = Uri.parse(url);
5884 // Get the request host name.
5885 String requestBaseDomain = requestUri.getHost();
5887 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5888 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5889 // Determine the current base domain.
5890 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5891 // Remove the first subdomain.
5892 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5895 // Determine the request base domain.
5896 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5897 // Remove the first subdomain.
5898 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5901 // Update the third party request tracker.
5902 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5906 // Get the current WebView page position.
5907 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5909 // Determine if the WebView is currently displayed.
5910 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5912 // Block third-party requests if enabled.
5913 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5914 // Add the result to the resource requests.
5915 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5917 // Increment the blocked requests counters.
5918 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5919 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5921 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5922 if (webViewDisplayed) {
5923 // Updating the UI must be run from the UI thread.
5924 activity.runOnUiThread(() -> {
5925 // Update the menu item titles.
5926 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5928 // Update the options menu if it has been populated.
5929 if (optionsMenu != null) {
5930 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5931 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5932 getString(R.string.block_all_third_party_requests));
5937 // Return an empty web resource response.
5938 return emptyWebResourceResponse;
5941 // Check UltraList if it is enabled.
5942 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5943 // Check the URL against UltraList.
5944 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5946 // Process the UltraList results.
5947 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5948 // Add the result to the resource requests.
5949 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5951 // Increment the blocked requests counters.
5952 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5953 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5955 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5956 if (webViewDisplayed) {
5957 // Updating the UI must be run from the UI thread.
5958 activity.runOnUiThread(() -> {
5959 // Update the menu item titles.
5960 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5962 // Update the options menu if it has been populated.
5963 if (optionsMenu != null) {
5964 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5965 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5970 // The resource request was blocked. Return an empty web resource response.
5971 return emptyWebResourceResponse;
5972 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5973 // Add a whitelist entry to the resource requests array.
5974 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5976 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5981 // Check UltraPrivacy if it is enabled.
5982 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5983 // Check the URL against UltraPrivacy.
5984 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5986 // Process the UltraPrivacy results.
5987 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5988 // Add the result to the resource requests.
5989 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5990 ultraPrivacyResults[5]});
5992 // Increment the blocked requests counters.
5993 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5994 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5996 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5997 if (webViewDisplayed) {
5998 // Updating the UI must be run from the UI thread.
5999 activity.runOnUiThread(() -> {
6000 // Update the menu item titles.
6001 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6003 // Update the options menu if it has been populated.
6004 if (optionsMenu != null) {
6005 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6006 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
6011 // The resource request was blocked. Return an empty web resource response.
6012 return emptyWebResourceResponse;
6013 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
6014 // Add a whitelist entry to the resource requests array.
6015 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
6016 ultraPrivacyResults[5]});
6018 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
6023 // Check EasyList if it is enabled.
6024 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
6025 // Check the URL against EasyList.
6026 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
6028 // Process the EasyList results.
6029 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
6030 // Add the result to the resource requests.
6031 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
6033 // Increment the blocked requests counters.
6034 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6035 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
6037 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6038 if (webViewDisplayed) {
6039 // Updating the UI must be run from the UI thread.
6040 activity.runOnUiThread(() -> {
6041 // Update the menu item titles.
6042 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6044 // Update the options menu if it has been populated.
6045 if (optionsMenu != null) {
6046 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6047 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
6052 // The resource request was blocked. Return an empty web resource response.
6053 return emptyWebResourceResponse;
6054 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
6055 // Update the whitelist result string array tracker.
6056 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
6060 // Check EasyPrivacy if it is enabled.
6061 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
6062 // Check the URL against EasyPrivacy.
6063 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
6065 // Process the EasyPrivacy results.
6066 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
6067 // Add the result to the resource requests.
6068 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
6069 easyPrivacyResults[5]});
6071 // Increment the blocked requests counters.
6072 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6073 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
6075 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6076 if (webViewDisplayed) {
6077 // Updating the UI must be run from the UI thread.
6078 activity.runOnUiThread(() -> {
6079 // Update the menu item titles.
6080 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6082 // Update the options menu if it has been populated.
6083 if (optionsMenu != null) {
6084 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6085 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
6090 // The resource request was blocked. Return an empty web resource response.
6091 return emptyWebResourceResponse;
6092 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
6093 // Update the whitelist result string array tracker.
6094 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
6098 // Check Fanboy’s Annoyance List if it is enabled.
6099 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
6100 // Check the URL against Fanboy's Annoyance List.
6101 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
6103 // Process the Fanboy's Annoyance List results.
6104 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
6105 // Add the result to the resource requests.
6106 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
6107 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
6109 // Increment the blocked requests counters.
6110 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6111 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
6113 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6114 if (webViewDisplayed) {
6115 // Updating the UI must be run from the UI thread.
6116 activity.runOnUiThread(() -> {
6117 // Update the menu item titles.
6118 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6120 // Update the options menu if it has been populated.
6121 if (optionsMenu != null) {
6122 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6123 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
6124 getString(R.string.fanboys_annoyance_list));
6129 // The resource request was blocked. Return an empty web resource response.
6130 return emptyWebResourceResponse;
6131 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
6132 // Update the whitelist result string array tracker.
6133 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
6134 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
6136 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
6137 // Check the URL against Fanboy's Annoyance List.
6138 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
6140 // Process the Fanboy's Social Blocking List results.
6141 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
6142 // Add the result to the resource requests.
6143 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6144 fanboysSocialListResults[4], fanboysSocialListResults[5]});
6146 // Increment the blocked requests counters.
6147 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6148 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
6150 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6151 if (webViewDisplayed) {
6152 // Updating the UI must be run from the UI thread.
6153 activity.runOnUiThread(() -> {
6154 // Update the menu item titles.
6155 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6157 // Update the options menu if it has been populated.
6158 if (optionsMenu != null) {
6159 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6160 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
6161 getString(R.string.fanboys_social_blocking_list));
6166 // The resource request was blocked. Return an empty web resource response.
6167 return emptyWebResourceResponse;
6168 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
6169 // Update the whitelist result string array tracker.
6170 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6171 fanboysSocialListResults[4], fanboysSocialListResults[5]};
6175 // Add the request to the log because it hasn't been processed by any of the previous checks.
6176 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
6177 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
6178 } else { // The request didn't match any blocklist entry. Log it as a default request.
6179 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
6182 // The resource request has not been blocked. `return null` loads the requested resource.
6186 // Handle HTTP authentication requests.
6188 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
6189 // Store the handler.
6190 nestedScrollWebView.setHttpAuthHandler(handler);
6192 // Instantiate an HTTP authentication dialog.
6193 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
6195 // Show the HTTP authentication dialog.
6196 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
6200 public void onPageStarted(WebView view, String url, Bitmap favicon) {
6201 // Get the preferences.
6202 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
6204 // 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.
6205 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6206 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6207 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6209 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6210 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6212 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6213 appBarHeight = appBarLayout.getHeight();
6215 // The swipe refresh layout must be manually moved below the app bar layout.
6216 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6218 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6219 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6222 // Reset the list of resource requests.
6223 nestedScrollWebView.clearResourceRequests();
6225 // Reset the requests counters.
6226 nestedScrollWebView.resetRequestsCounters();
6228 // Get the current page position.
6229 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6231 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6232 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6233 // Display the formatted URL text.
6234 urlEditText.setText(url);
6236 // Apply text highlighting to `urlTextBox`.
6239 // Hide the keyboard.
6240 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6243 // Reset the list of host IP addresses.
6244 nestedScrollWebView.clearCurrentIpAddresses();
6246 // Get a URI for the current URL.
6247 Uri currentUri = Uri.parse(url);
6249 // Get the IP addresses for the host.
6250 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6252 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6253 if (optionsMenu != null) {
6255 optionsRefreshMenuItem.setTitle(R.string.stop);
6257 // Get the app bar and theme preferences.
6258 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6260 // If the icon is displayed in the AppBar, set it according to the theme.
6261 if (displayAdditionalAppBarIcons) {
6262 // Get the current theme status.
6263 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6265 // Set the stop icon according to the theme.
6266 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6267 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
6269 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
6276 public void onPageFinished(WebView view, String url) {
6277 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6278 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6279 CookieManager.getInstance().flush();
6282 // Update the Refresh menu item if the options menu has been created.
6283 if (optionsMenu != null) {
6284 // Reset the Refresh title.
6285 optionsRefreshMenuItem.setTitle(R.string.refresh);
6287 // Get the app bar and theme preferences.
6288 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6290 // If the icon is displayed in the app bar, reset it according to the theme.
6291 if (displayAdditionalAppBarIcons) {
6292 // Get the current theme status.
6293 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6295 // Set the icon according to the theme.
6296 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6297 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6299 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6304 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6305 if (incognitoModeEnabled) {
6306 // Clear the cache. `true` includes disk files.
6307 nestedScrollWebView.clearCache(true);
6309 // Clear the back/forward history.
6310 nestedScrollWebView.clearHistory();
6312 // Manually delete cache folders.
6314 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6315 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6316 String privateDataDirectoryString = getApplicationInfo().dataDir;
6318 // Delete the main cache directory.
6319 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6321 // Delete the secondary `Service Worker` cache directory.
6322 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6323 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6324 } catch (IOException exception) {
6325 // Do nothing if an error is thrown.
6328 // Clear the logcat.
6330 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6331 Runtime.getRuntime().exec("logcat -b all -c");
6332 } catch (IOException exception) {
6337 // Get the current page position.
6338 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6340 // 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.
6341 String currentUrl = nestedScrollWebView.getUrl();
6343 // Get the current tab.
6344 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6346 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6347 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6348 // Probably some sort of race condition when Privacy Browser is being resumed.
6349 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6350 // Check to see if the URL is `about:blank`.
6351 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6352 // Display the hint in the URL edit text.
6353 urlEditText.setText("");
6355 // Request focus for the URL text box.
6356 urlEditText.requestFocus();
6358 // Display the keyboard.
6359 inputMethodManager.showSoftInput(urlEditText, 0);
6361 // Apply the domain settings. This clears any settings from the previous domain.
6362 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6364 // Only populate the title text view if the tab has been fully created.
6366 // Get the custom view from the tab.
6367 View tabView = tab.getCustomView();
6369 // Remove the incorrect warning below that the current tab view might be null.
6370 assert tabView != null;
6372 // Get the title text view from the tab.
6373 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6375 // Set the title as the tab text.
6376 tabTitleTextView.setText(R.string.new_tab);
6378 } else { // The WebView has loaded a webpage.
6379 // Update the URL edit text if it is not currently being edited.
6380 if (!urlEditText.hasFocus()) {
6381 // 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.
6382 String sanitizedUrl = sanitizeUrl(currentUrl);
6384 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6385 urlEditText.setText(sanitizedUrl);
6387 // Apply text highlighting to the URL.
6391 // Only populate the title text view if the tab has been fully created.
6393 // Get the custom view from the tab.
6394 View tabView = tab.getCustomView();
6396 // Remove the incorrect warning below that the current tab view might be null.
6397 assert tabView != null;
6399 // Get the title text view from the tab.
6400 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6402 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6403 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6409 // Handle SSL Certificate errors.
6411 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6412 // Get the current website SSL certificate.
6413 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6415 // Extract the individual pieces of information from the current website SSL certificate.
6416 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6417 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6418 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6419 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6420 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6421 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6422 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6423 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6425 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6426 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6427 // Get the pinned SSL certificate.
6428 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6430 // Extract the arrays from the array list.
6431 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6432 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6434 // Check if the current SSL certificate matches the pinned certificate.
6435 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6436 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6437 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6438 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6440 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6443 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6444 // Store the SSL error handler.
6445 nestedScrollWebView.setSslErrorHandler(handler);
6447 // Instantiate an SSL certificate error alert dialog.
6448 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6450 // Show the SSL certificate error dialog.
6451 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6456 // Check to see if the state is being restored.
6457 if (restoringState) { // The state is being restored.
6458 // Resume the nested scroll WebView JavaScript timers.
6459 nestedScrollWebView.resumeTimers();
6460 } else if (pageNumber == 0) { // The first page is being loaded.
6461 // Set this nested scroll WebView as the current WebView.
6462 currentWebView = nestedScrollWebView;
6464 // Initialize the URL to load string.
6465 String urlToLoadString;
6467 // Get the intent that started the app.
6468 Intent launchingIntent = getIntent();
6470 // Reset the intent. This prevents a duplicate tab from being created on restart.
6471 setIntent(new Intent());
6473 // Get the information from the intent.
6474 String launchingIntentAction = launchingIntent.getAction();
6475 Uri launchingIntentUriData = launchingIntent.getData();
6476 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6478 // Parse the launching intent URL.
6479 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6480 // Create an encoded URL string.
6481 String encodedUrlString;
6483 // Sanitize the search input and convert it to a search.
6485 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6486 } catch (UnsupportedEncodingException exception) {
6487 encodedUrlString = "";
6490 // Store the web search as the URL to load.
6491 urlToLoadString = searchURL + encodedUrlString;
6492 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6493 // Store the URI as a URL.
6494 urlToLoadString = launchingIntentUriData.toString();
6495 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6497 urlToLoadString = launchingIntentStringExtra;
6498 } else if (!url.equals("")) { // The activity has been restarted.
6499 // Load the saved URL.
6500 urlToLoadString = url;
6501 } else { // The is no URL in the intent.
6502 // Store the homepage to be loaded.
6503 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6506 // Load the website if not waiting for the proxy.
6507 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6508 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6509 } else { // Load the URL.
6510 loadUrl(nestedScrollWebView, urlToLoadString);
6513 // 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.
6514 // 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.
6515 setIntent(new Intent());
6516 } else { // This is not the first tab.
6518 loadUrl(nestedScrollWebView, url);
6520 // Set the focus and display the keyboard if the URL is blank.
6521 if (url.equals("")) {
6522 // Request focus for the URL text box.
6523 urlEditText.requestFocus();
6525 // Create a display keyboard handler.
6526 Handler displayKeyboardHandler = new Handler();
6528 // Create a display keyboard runnable.
6529 Runnable displayKeyboardRunnable = () -> {
6530 // Display the keyboard.
6531 inputMethodManager.showSoftInput(urlEditText, 0);
6534 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6535 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);