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.annotation.SuppressLint;
25 import android.app.Activity;
26 import android.app.Dialog;
27 import android.app.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.AsyncTask;
49 import android.os.Build;
50 import android.os.Bundle;
51 import android.os.Environment;
52 import android.os.Handler;
53 import android.os.Message;
54 import android.preference.PreferenceManager;
55 import android.print.PrintDocumentAdapter;
56 import android.print.PrintManager;
57 import android.provider.DocumentsContract;
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.CheckBox;
88 import android.widget.CursorAdapter;
89 import android.widget.EditText;
90 import android.widget.FrameLayout;
91 import android.widget.ImageView;
92 import android.widget.LinearLayout;
93 import android.widget.ListView;
94 import android.widget.ProgressBar;
95 import android.widget.RadioButton;
96 import android.widget.RelativeLayout;
97 import android.widget.TextView;
99 import androidx.annotation.NonNull;
100 import androidx.appcompat.app.ActionBar;
101 import androidx.appcompat.app.ActionBarDrawerToggle;
102 import androidx.appcompat.app.AppCompatActivity;
103 import androidx.appcompat.app.AppCompatDelegate;
104 import androidx.appcompat.widget.Toolbar;
105 import androidx.coordinatorlayout.widget.CoordinatorLayout;
106 import androidx.core.content.res.ResourcesCompat;
107 import androidx.core.view.GravityCompat;
108 import androidx.drawerlayout.widget.DrawerLayout;
109 import androidx.fragment.app.DialogFragment;
110 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
111 import androidx.viewpager.widget.ViewPager;
112 import androidx.webkit.WebSettingsCompat;
113 import androidx.webkit.WebViewFeature;
115 import com.google.android.material.appbar.AppBarLayout;
116 import com.google.android.material.floatingactionbutton.FloatingActionButton;
117 import com.google.android.material.navigation.NavigationView;
118 import com.google.android.material.snackbar.Snackbar;
119 import com.google.android.material.tabs.TabLayout;
121 import com.stoutner.privacybrowser.BuildConfig;
122 import com.stoutner.privacybrowser.R;
123 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
124 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
125 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
126 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
127 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
128 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
129 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
130 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
131 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
132 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
133 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
134 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
135 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
136 import com.stoutner.privacybrowser.dialogs.OpenDialog;
137 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
138 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
139 import com.stoutner.privacybrowser.dialogs.SaveWebpageDialog;
140 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
141 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
142 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
143 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
144 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
145 import com.stoutner.privacybrowser.helpers.AdHelper;
146 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
147 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
148 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
149 import com.stoutner.privacybrowser.helpers.ProxyHelper;
150 import com.stoutner.privacybrowser.views.NestedScrollWebView;
152 import java.io.ByteArrayInputStream;
153 import java.io.ByteArrayOutputStream;
155 import java.io.FileInputStream;
156 import java.io.FileOutputStream;
157 import java.io.IOException;
158 import java.io.InputStream;
159 import java.io.OutputStream;
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, UrlHistoryDialog.NavigateHistoryListener,
180 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 // Define the start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
207 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
208 public final static int BROWSE_OPEN_REQUEST_CODE = 1;
209 public final static int BROWSE_SAVE_WEBPAGE_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 // Declare the class variables
251 private BroadcastReceiver orbotStatusBroadcastReceiver;
252 private String webViewDefaultUserAgent;
253 private boolean incognitoModeEnabled;
254 private boolean fullScreenBrowsingModeEnabled;
255 private boolean inFullScreenBrowsingMode;
256 private boolean downloadWithExternalApp;
257 private boolean hideAppBar;
258 private boolean scrollAppBar;
259 private boolean loadingNewIntent;
260 private boolean reapplyDomainSettingsOnRestart;
261 private boolean reapplyAppSettingsOnRestart;
262 private boolean displayingFullScreenVideo;
263 private boolean waitingForProxy;
265 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
266 private ActionBarDrawerToggle actionBarDrawerToggle;
268 // The color spans are used in `onCreate()` and `highlightUrlText()`.
269 private ForegroundColorSpan redColorSpan;
270 private ForegroundColorSpan initialGrayColorSpan;
271 private ForegroundColorSpan finalGrayColorSpan;
273 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
274 // and `loadBookmarksFolder()`.
275 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
277 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
278 private Cursor bookmarksCursor;
280 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
281 private CursorAdapter bookmarksCursorAdapter;
283 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
284 private String oldFolderNameString;
286 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
287 private ValueCallback<Uri[]> fileChooserCallback;
289 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
290 private int appBarHeight;
291 private int defaultProgressViewStartOffset;
292 private int defaultProgressViewEndOffset;
294 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
295 private boolean sanitizeGoogleAnalytics;
296 private boolean sanitizeFacebookClickIds;
297 private boolean sanitizeTwitterAmpRedirects;
299 // Declare the class views.
300 private FrameLayout rootFrameLayout;
301 private DrawerLayout drawerLayout;
302 private RelativeLayout mainContentRelativeLayout;
303 private AppBarLayout appBarLayout;
304 private Toolbar toolbar;
305 private RelativeLayout urlRelativeLayout;
306 private EditText urlEditText;
307 private ActionBar actionBar;
308 private LinearLayout findOnPageLinearLayout;
309 private LinearLayout tabsLinearLayout;
310 private TabLayout tabLayout;
311 private SwipeRefreshLayout swipeRefreshLayout;
312 private ViewPager webViewPager;
313 private FrameLayout fullScreenVideoFrameLayout;
315 // Declare the class menus.
316 private Menu optionsMenu;
318 // Declare the class menu items.
319 private MenuItem navigationBackMenuItem;
320 private MenuItem navigationForwardMenuItem;
321 private MenuItem navigationHistoryMenuItem;
322 private MenuItem navigationRequestsMenuItem;
323 private MenuItem optionsPrivacyMenuItem;
324 private MenuItem optionsRefreshMenuItem;
325 private MenuItem optionsCookiesMenuItem;
326 private MenuItem optionsDomStorageMenuItem;
327 private MenuItem optionsSaveFormDataMenuItem;
328 private MenuItem optionsClearDataMenuItem;
329 private MenuItem optionsClearCookiesMenuItem;
330 private MenuItem optionsClearDomStorageMenuItem;
331 private MenuItem optionsClearFormDataMenuItem;
332 private MenuItem optionsBlocklistsMenuItem;
333 private MenuItem optionsEasyListMenuItem;
334 private MenuItem optionsEasyPrivacyMenuItem;
335 private MenuItem optionsFanboysAnnoyanceListMenuItem;
336 private MenuItem optionsFanboysSocialBlockingListMenuItem;
337 private MenuItem optionsUltraListMenuItem;
338 private MenuItem optionsUltraPrivacyMenuItem;
339 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
340 private MenuItem optionsProxyMenuItem;
341 private MenuItem optionsProxyNoneMenuItem;
342 private MenuItem optionsProxyTorMenuItem;
343 private MenuItem optionsProxyI2pMenuItem;
344 private MenuItem optionsProxyCustomMenuItem;
345 private MenuItem optionsUserAgentMenuItem;
346 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
347 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
348 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
349 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
350 private MenuItem optionsUserAgentSafariOnIosMenuItem;
351 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
352 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
353 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
354 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
355 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
356 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
357 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
358 private MenuItem optionsUserAgentCustomMenuItem;
359 private MenuItem optionsSwipeToRefreshMenuItem;
360 private MenuItem optionsWideViewportMenuItem;
361 private MenuItem optionsDisplayImagesMenuItem;
362 private MenuItem optionsDarkWebViewMenuItem;
363 private MenuItem optionsFontSizeMenuItem;
364 private MenuItem optionsAddOrEditDomainMenuItem;
367 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
368 @SuppressLint("ClickableViewAccessibility")
369 protected void onCreate(Bundle savedInstanceState) {
370 // Run the default commands.
371 super.onCreate(savedInstanceState);
373 // Check to see if the activity has been restarted.
374 if (savedInstanceState != null) {
375 // Store the saved instance state variables.
376 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
377 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
378 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
379 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
382 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
383 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
385 // Get a handle for the shared preferences.
386 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
388 // Get the screenshot preference.
389 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
390 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
392 // Get the theme entry values string array.
393 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
395 // 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.
396 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
397 // Apply the light theme.
398 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
399 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
400 // Apply the dark theme.
401 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
402 } else { // The system default theme is selected.
403 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
404 // Follow the system default theme.
405 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
406 } else { // The system default theme is not supported.
407 // Follow the battery saver mode.
408 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
412 // Disable screenshots if not allowed.
413 if (!allowScreenshots) {
414 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
417 // 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.
418 if (Build.VERSION.SDK_INT >= 21) {
419 WebView.enableSlowWholeDocumentDraw();
423 setTheme(R.style.PrivacyBrowser);
425 // Set the content view.
426 setContentView(R.layout.main_framelayout);
428 // Get handles for the views.
429 rootFrameLayout = findViewById(R.id.root_framelayout);
430 drawerLayout = findViewById(R.id.drawerlayout);
431 mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
432 appBarLayout = findViewById(R.id.appbar_layout);
433 toolbar = findViewById(R.id.toolbar);
434 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
435 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
436 tabLayout = findViewById(R.id.tablayout);
437 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
438 webViewPager = findViewById(R.id.webviewpager);
439 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
441 // Get a handle for the navigation view.
442 NavigationView navigationView = findViewById(R.id.navigationview);
444 // Get a handle for the navigation menu.
445 Menu navigationMenu = navigationView.getMenu();
447 // Get handles for the navigation menu items.
448 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
449 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
450 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
451 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
453 // Listen for touches on the navigation menu.
454 navigationView.setNavigationItemSelectedListener(this);
456 // Get a handle for the app compat delegate.
457 AppCompatDelegate appCompatDelegate = getDelegate();
459 // Set the support action bar.
460 appCompatDelegate.setSupportActionBar(toolbar);
462 // Get a handle for the action bar.
463 actionBar = appCompatDelegate.getSupportActionBar();
465 // Remove the incorrect lint warning below that the action bar might be null.
466 assert actionBar != null;
468 // Add the custom layout, which shows the URL text bar.
469 actionBar.setCustomView(R.layout.url_app_bar);
470 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
472 // Get handles for the views in the URL app bar.
473 urlRelativeLayout = findViewById(R.id.url_relativelayout);
474 urlEditText = findViewById(R.id.url_edittext);
476 // Create the hamburger icon at the start of the AppBar.
477 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
479 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
480 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
482 // Initialize the web view pager adapter.
483 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
485 // Set the pager adapter on the web view pager.
486 webViewPager.setAdapter(webViewPagerAdapter);
488 // Store up to 100 tabs in memory.
489 webViewPager.setOffscreenPageLimit(100);
491 // Initialize the app.
494 // Apply the app settings from the shared preferences.
497 // Populate the blocklists.
498 populateBlocklists = new PopulateBlocklists(this, this).execute();
502 protected void onNewIntent(Intent intent) {
503 // Run the default commands.
504 super.onNewIntent(intent);
506 // Replace the intent that started the app with this one.
509 // Check to see if the app is being restarted from a saved state.
510 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
511 // Get the information from the intent.
512 String intentAction = intent.getAction();
513 Uri intentUriData = intent.getData();
514 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
516 // Determine if this is a web search.
517 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
519 // 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.
520 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
521 // Exit the full screen video if it is displayed.
522 if (displayingFullScreenVideo) {
523 // Exit full screen video mode.
524 exitFullScreenVideo();
526 // Reload the current WebView. Otherwise, it can display entirely black.
527 currentWebView.reload();
530 // Get the shared preferences.
531 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
533 // Create a URL string.
536 // If the intent action is a web search, perform the search.
537 if (isWebSearch) { // The intent is a web search.
538 // Create an encoded URL string.
539 String encodedUrlString;
541 // Sanitize the search input and convert it to a search.
543 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
544 } catch (UnsupportedEncodingException exception) {
545 encodedUrlString = "";
548 // Add the base search URL.
549 url = searchURL + encodedUrlString;
550 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
551 // Set the intent data as the URL.
552 url = intentUriData.toString();
553 } else { // The intent contains a string, which might be a URL.
554 // Set the intent string as the URL.
555 url = intentStringExtra;
558 // Add a new tab if specified in the preferences.
559 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
560 // Set the loading new intent flag.
561 loadingNewIntent = true;
564 addNewTab(url, true);
565 } else { // Load the URL in the current tab.
567 loadUrl(currentWebView, url);
570 // Close the navigation drawer if it is open.
571 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
572 drawerLayout.closeDrawer(GravityCompat.START);
575 // Close the bookmarks drawer if it is open.
576 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
577 drawerLayout.closeDrawer(GravityCompat.END);
584 public void onRestart() {
585 // Run the default commands.
588 // Apply the app settings if returning from the Settings activity.
589 if (reapplyAppSettingsOnRestart) {
590 // Reset the reapply app settings on restart tracker.
591 reapplyAppSettingsOnRestart = false;
593 // Apply the app settings.
597 // Apply the domain settings if returning from the settings or domains activity.
598 if (reapplyDomainSettingsOnRestart) {
599 // Reset the reapply domain settings on restart tracker.
600 reapplyDomainSettingsOnRestart = false;
602 // Reapply the domain settings for each tab.
603 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
604 // Get the WebView tab fragment.
605 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
607 // Get the fragment view.
608 View fragmentView = webViewTabFragment.getView();
610 // Only reload the WebViews if they exist.
611 if (fragmentView != null) {
612 // Get the nested scroll WebView from the tab fragment.
613 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
615 // Reset the current domain name so the domain settings will be reapplied.
616 nestedScrollWebView.resetCurrentDomainName();
618 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
619 if (nestedScrollWebView.getUrl() != null) {
620 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
626 // Update the bookmarks drawer if returning from the Bookmarks activity.
627 if (restartFromBookmarksActivity) {
628 // Close the bookmarks drawer.
629 drawerLayout.closeDrawer(GravityCompat.END);
631 // Reload the bookmarks drawer.
632 loadBookmarksFolder();
634 // Reset `restartFromBookmarksActivity`.
635 restartFromBookmarksActivity = false;
638 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
639 updatePrivacyIcons(true);
642 // `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.
644 public void onStart() {
645 // Run the default commands.
648 // Resume any WebViews.
649 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
650 // Get the WebView tab fragment.
651 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
653 // Get the fragment view.
654 View fragmentView = webViewTabFragment.getView();
656 // Only resume the WebViews if they exist (they won't when the app is first created).
657 if (fragmentView != null) {
658 // Get the nested scroll WebView from the tab fragment.
659 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
661 // Resume the nested scroll WebView.
662 nestedScrollWebView.onResume();
666 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
667 if (currentWebView != null) {
668 currentWebView.resumeTimers();
671 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
672 if (!proxyMode.equals(ProxyHelper.NONE)) {
676 // Reapply any system UI flags and the ad in the free flavor.
677 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
678 /* Hide the system bars.
679 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
680 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
681 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
682 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
684 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
685 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
686 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
687 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
688 View adView = findViewById(R.id.adview);
691 AdHelper.resumeAd(adView);
695 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
697 public void onStop() {
698 // Run the default commands.
701 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
702 // Get the WebView tab fragment.
703 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
705 // Get the fragment view.
706 View fragmentView = webViewTabFragment.getView();
708 // Only pause the WebViews if they exist (they won't when the app is first created).
709 if (fragmentView != null) {
710 // Get the nested scroll WebView from the tab fragment.
711 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
713 // Pause the nested scroll WebView.
714 nestedScrollWebView.onPause();
718 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
719 if (currentWebView != null) {
720 currentWebView.pauseTimers();
723 // Pause the ad or it will continue to consume resources in the background on the free flavor.
724 if (BuildConfig.FLAVOR.contentEquals("free")) {
725 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
726 View adView = findViewById(R.id.adview);
729 AdHelper.pauseAd(adView);
734 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
735 // Run the default commands.
736 super.onSaveInstanceState(savedInstanceState);
738 // Create the saved state array lists.
739 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
740 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
742 // Get the URLs from each tab.
743 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
744 // Get the WebView tab fragment.
745 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
747 // Get the fragment view.
748 View fragmentView = webViewTabFragment.getView();
750 if (fragmentView != null) {
751 // Get the nested scroll WebView from the tab fragment.
752 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
754 // Create saved state bundle.
755 Bundle savedStateBundle = new Bundle();
757 // Get the current states.
758 nestedScrollWebView.saveState(savedStateBundle);
759 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
761 // Store the saved states in the array lists.
762 savedStateArrayList.add(savedStateBundle);
763 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
767 // Get the current tab position.
768 int currentTabPosition = tabLayout.getSelectedTabPosition();
770 // Store the saved states in the bundle.
771 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
772 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
773 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
774 savedInstanceState.putString(PROXY_MODE, proxyMode);
778 public void onDestroy() {
779 // Unregister the orbot status broadcast receiver if it exists.
780 if (orbotStatusBroadcastReceiver != null) {
781 this.unregisterReceiver(orbotStatusBroadcastReceiver);
784 // Close the bookmarks cursor if it exists.
785 if (bookmarksCursor != null) {
786 bookmarksCursor.close();
789 // Close the bookmarks database if it exists.
790 if (bookmarksDatabaseHelper != null) {
791 bookmarksDatabaseHelper.close();
794 // Stop populating the blocklists if the AsyncTask is running in the background.
795 if (populateBlocklists != null) {
796 populateBlocklists.cancel(true);
799 // Run the default commands.
804 public boolean onCreateOptionsMenu(Menu menu) {
805 // Inflate the menu. This adds items to the action bar if it is present.
806 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
808 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
811 // Get handles for the class menu items.
812 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
813 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
814 optionsCookiesMenuItem = menu.findItem(R.id.cookies);
815 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
816 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
817 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
818 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
819 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
820 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
821 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
822 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
823 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
824 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
825 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
826 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
827 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
828 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
829 optionsProxyMenuItem = menu.findItem(R.id.proxy);
830 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
831 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
832 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
833 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
834 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
835 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
836 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
837 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
838 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
839 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
840 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
841 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
842 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
843 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
844 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
845 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
846 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
847 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
848 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
849 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
850 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
851 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
852 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
853 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
855 // Get handles for the method menu items.
856 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
857 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
859 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
860 updatePrivacyIcons(false);
862 // Only display the form data menu items if the API < 26.
863 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
864 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
866 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
867 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
869 // Only display the dark WebView menu item if API >= 21.
870 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
872 // Only show Ad Consent if this is the free flavor.
873 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
875 // Get the shared preferences.
876 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
878 // Get the dark theme and app bar preferences.
879 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
881 // 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.
882 if (displayAdditionalAppBarIcons) {
883 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
884 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
885 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
886 } else { //Do not display the additional icons.
887 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
888 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
889 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
892 // Replace Refresh with Stop if a URL is already loading.
893 if (currentWebView != null && currentWebView.getProgress() != 100) {
895 optionsRefreshMenuItem.setTitle(R.string.stop);
897 // Set the icon if it is displayed in the app bar.
898 if (displayAdditionalAppBarIcons) {
899 // Get the current theme status.
900 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
902 // Set the icon according to the current theme status.
903 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
904 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
906 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
916 public boolean onPrepareOptionsMenu(Menu menu) {
917 // Get a handle for the cookie manager.
918 CookieManager cookieManager = CookieManager.getInstance();
920 // Initialize the current user agent string and the font size.
921 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
924 // 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.
925 if (currentWebView != null) {
926 // Set the add or edit domain text.
927 if (currentWebView.getDomainSettingsApplied()) {
928 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
930 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
933 // Get the current user agent from the WebView.
934 currentUserAgent = currentWebView.getSettings().getUserAgentString();
936 // Get the current font size from the
937 fontSize = currentWebView.getSettings().getTextZoom();
939 // Set the status of the menu item checkboxes.
940 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
941 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
942 optionsEasyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
943 optionsEasyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
944 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
945 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
946 optionsUltraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
947 optionsUltraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
948 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
949 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
950 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
951 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
953 // Initialize the display names for the blocklists with the number of blocked requests.
954 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
955 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
956 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
957 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
958 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
959 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
960 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
961 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
963 // Enable DOM Storage if JavaScript is enabled.
964 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
966 // Set the checkbox status for dark WebView if the WebView supports it.
967 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
968 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
972 // Set the cookies menu item checked status.
973 optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
975 // Enable Clear Cookies if there are any.
976 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
978 // 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`.
979 String privateDataDirectoryString = getApplicationInfo().dataDir;
981 // Get a count of the number of files in the Local Storage directory.
982 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
983 int localStorageDirectoryNumberOfFiles = 0;
984 if (localStorageDirectory.exists()) {
985 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
986 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
989 // Get a count of the number of files in the IndexedDB directory.
990 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
991 int indexedDBDirectoryNumberOfFiles = 0;
992 if (indexedDBDirectory.exists()) {
993 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
994 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
997 // Enable Clear DOM Storage if there is any.
998 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1000 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1001 if (Build.VERSION.SDK_INT < 26) {
1002 // Get the WebView database.
1003 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1005 // Enable the clear form data menu item if there is anything to clear.
1006 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1009 // Enable Clear Data if any of the submenu items are enabled.
1010 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1012 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1013 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1015 // Set the proxy title and check the applied proxy.
1016 switch (proxyMode) {
1017 case ProxyHelper.NONE:
1018 // Set the proxy title.
1019 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1021 // Check the proxy None radio button.
1022 optionsProxyNoneMenuItem.setChecked(true);
1025 case ProxyHelper.TOR:
1026 // Set the proxy title.
1027 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1029 // Check the proxy Tor radio button.
1030 optionsProxyTorMenuItem.setChecked(true);
1033 case ProxyHelper.I2P:
1034 // Set the proxy title.
1035 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1037 // Check the proxy I2P radio button.
1038 optionsProxyI2pMenuItem.setChecked(true);
1041 case ProxyHelper.CUSTOM:
1042 // Set the proxy title.
1043 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1045 // Check the proxy Custom radio button.
1046 optionsProxyCustomMenuItem.setChecked(true);
1050 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1051 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1052 // Update the user agent menu item title.
1053 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1055 // Select the Privacy Browser radio box.
1056 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1057 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1058 // Update the user agent menu item title.
1059 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1061 // Select the WebView Default radio box.
1062 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1063 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1064 // Update the user agent menu item title.
1065 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1067 // Select the Firefox on Android radio box.
1068 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1069 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1070 // Update the user agent menu item title.
1071 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1073 // Select the Chrome on Android radio box.
1074 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1075 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1076 // Update the user agent menu item title.
1077 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1079 // Select the Safari on iOS radio box.
1080 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1081 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1082 // Update the user agent menu item title.
1083 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1085 // Select the Firefox on Linux radio box.
1086 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1087 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1088 // Update the user agent menu item title.
1089 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1091 // Select the Chromium on Linux radio box.
1092 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1093 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1094 // Update the user agent menu item title.
1095 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1097 // Select the Firefox on Windows radio box.
1098 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1099 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1100 // Update the user agent menu item title.
1101 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1103 // Select the Chrome on Windows radio box.
1104 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1105 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1106 // Update the user agent menu item title.
1107 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1109 // Select the Edge on Windows radio box.
1110 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1111 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1112 // Update the user agent menu item title.
1113 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1115 // Select the Internet on Windows radio box.
1116 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1117 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1118 // Update the user agent menu item title.
1119 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1121 // Select the Safari on macOS radio box.
1122 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1123 } else { // Custom user agent.
1124 // Update the user agent menu item title.
1125 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1127 // Select the Custom radio box.
1128 optionsUserAgentCustomMenuItem.setChecked(true);
1131 // Set the font size title.
1132 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1134 // Run all the other default commands.
1135 super.onPrepareOptionsMenu(menu);
1137 // Display the menu.
1142 public boolean onOptionsItemSelected(MenuItem menuItem) {
1143 // Get a handle for the shared preferences.
1144 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1146 // Get a handle for the cookie manager.
1147 CookieManager cookieManager = CookieManager.getInstance();
1149 // Get the selected menu item ID.
1150 int menuItemId = menuItem.getItemId();
1152 // Run the commands that correlate to the selected menu item.
1153 if (menuItemId == R.id.javascript) { // JavaScript.
1154 // Toggle the JavaScript status.
1155 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1157 // Update the privacy icon.
1158 updatePrivacyIcons(true);
1160 // Display a `Snackbar`.
1161 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1162 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1163 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1164 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1165 } else { // Privacy mode.
1166 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1169 // Reload the current WebView.
1170 currentWebView.reload();
1172 // Consume the event.
1174 } else if (menuItemId == R.id.refresh) { // Refresh.
1175 // Run the command that correlates to the current status of the menu item.
1176 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1177 // Reload the current WebView.
1178 currentWebView.reload();
1179 } else { // The stop button was pushed.
1180 // Stop the loading of the WebView.
1181 currentWebView.stopLoading();
1184 // Consume the event.
1186 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1187 // Open the bookmarks drawer.
1188 drawerLayout.openDrawer(GravityCompat.END);
1190 // Consume the event.
1192 } else if (menuItemId == R.id.cookies) { // Cookies.
1193 // Switch the first-party cookie status.
1194 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1196 // Store the cookie status.
1197 currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1199 // Update the menu checkbox.
1200 menuItem.setChecked(cookieManager.acceptCookie());
1202 // Update the privacy icon.
1203 updatePrivacyIcons(true);
1205 // Display a snackbar.
1206 if (cookieManager.acceptCookie()) { // Cookies are enabled.
1207 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1208 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1209 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1210 } else { // Privacy mode.
1211 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1214 // Reload the current WebView.
1215 currentWebView.reload();
1217 // Consume the event.
1219 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1220 // Toggle the status of domStorageEnabled.
1221 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1223 // Update the menu checkbox.
1224 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1226 // Update the privacy icon.
1227 updatePrivacyIcons(true);
1229 // Display a snackbar.
1230 if (currentWebView.getSettings().getDomStorageEnabled()) {
1231 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1233 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1236 // Reload the current WebView.
1237 currentWebView.reload();
1239 // Consume the event.
1241 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1242 // Switch the status of saveFormDataEnabled.
1243 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1245 // Update the menu checkbox.
1246 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1248 // Display a snackbar.
1249 if (currentWebView.getSettings().getSaveFormData()) {
1250 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1252 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1255 // Update the privacy icon.
1256 updatePrivacyIcons(true);
1258 // Reload the current WebView.
1259 currentWebView.reload();
1261 // Consume the event.
1263 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1264 // Create a snackbar.
1265 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1266 .setAction(R.string.undo, v -> {
1267 // Do nothing because everything will be handled by `onDismissed()` below.
1269 .addCallback(new Snackbar.Callback() {
1271 public void onDismissed(Snackbar snackbar, int event) {
1272 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1273 // Delete the cookies, which command varies by SDK.
1274 if (Build.VERSION.SDK_INT < 21) {
1275 cookieManager.removeAllCookie();
1277 cookieManager.removeAllCookies(null);
1284 // Consume the event.
1286 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1287 // Create a snackbar.
1288 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1289 .setAction(R.string.undo, v -> {
1290 // Do nothing because everything will be handled by `onDismissed()` below.
1292 .addCallback(new Snackbar.Callback() {
1294 public void onDismissed(Snackbar snackbar, int event) {
1295 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1296 // Delete the DOM Storage.
1297 WebStorage webStorage = WebStorage.getInstance();
1298 webStorage.deleteAllData();
1300 // Initialize a handler to manually delete the DOM storage files and directories.
1301 Handler deleteDomStorageHandler = new Handler();
1303 // Setup a runnable to manually delete the DOM storage files and directories.
1304 Runnable deleteDomStorageRunnable = () -> {
1306 // Get a handle for the runtime.
1307 Runtime runtime = Runtime.getRuntime();
1309 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1310 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1311 String privateDataDirectoryString = getApplicationInfo().dataDir;
1313 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1314 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1316 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1317 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1318 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1319 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1320 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1322 // Wait for the processes to finish.
1323 deleteLocalStorageProcess.waitFor();
1324 deleteIndexProcess.waitFor();
1325 deleteQuotaManagerProcess.waitFor();
1326 deleteQuotaManagerJournalProcess.waitFor();
1327 deleteDatabasesProcess.waitFor();
1328 } catch (Exception exception) {
1329 // Do nothing if an error is thrown.
1333 // Manually delete the DOM storage files after 200 milliseconds.
1334 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1340 // Consume the event.
1342 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1343 // Create a snackbar.
1344 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1345 .setAction(R.string.undo, v -> {
1346 // Do nothing because everything will be handled by `onDismissed()` below.
1348 .addCallback(new Snackbar.Callback() {
1350 public void onDismissed(Snackbar snackbar, int event) {
1351 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1352 // Get a handle for the webView database.
1353 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1355 // Delete the form data.
1356 webViewDatabase.clearFormData();
1362 // Consume the event.
1364 } else if (menuItemId == R.id.easylist) { // EasyList.
1365 // Toggle the EasyList status.
1366 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1368 // Update the menu checkbox.
1369 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1371 // Reload the current WebView.
1372 currentWebView.reload();
1374 // Consume the event.
1376 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1377 // Toggle the EasyPrivacy status.
1378 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1380 // Update the menu checkbox.
1381 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1383 // Reload the current WebView.
1384 currentWebView.reload();
1386 // Consume the event.
1388 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1389 // Toggle Fanboy's Annoyance List status.
1390 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1392 // Update the menu checkbox.
1393 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1395 // Update the status of Fanboy's Social Blocking List.
1396 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1398 // Reload the current WebView.
1399 currentWebView.reload();
1401 // Consume the event.
1403 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1404 // Toggle Fanboy's Social Blocking List status.
1405 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1407 // Update the menu checkbox.
1408 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1410 // Reload the current WebView.
1411 currentWebView.reload();
1413 // Consume the event.
1415 } else if (menuItemId == R.id.ultralist) { // UltraList.
1416 // Toggle the UltraList status.
1417 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1419 // Update the menu checkbox.
1420 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1422 // Reload the current WebView.
1423 currentWebView.reload();
1425 // Consume the event.
1427 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1428 // Toggle the UltraPrivacy status.
1429 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1431 // Update the menu checkbox.
1432 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1434 // Reload the current WebView.
1435 currentWebView.reload();
1437 // Consume the event.
1439 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1440 //Toggle the third-party requests blocker status.
1441 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1443 // Update the menu checkbox.
1444 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1446 // Reload the current WebView.
1447 currentWebView.reload();
1449 // Consume the event.
1451 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1452 // Update the proxy mode.
1453 proxyMode = ProxyHelper.NONE;
1455 // Apply the proxy mode.
1458 // Consume the event.
1460 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1461 // Update the proxy mode.
1462 proxyMode = ProxyHelper.TOR;
1464 // Apply the proxy mode.
1467 // Consume the event.
1469 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1470 // Update the proxy mode.
1471 proxyMode = ProxyHelper.I2P;
1473 // Apply the proxy mode.
1476 // Consume the event.
1478 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1479 // Update the proxy mode.
1480 proxyMode = ProxyHelper.CUSTOM;
1482 // Apply the proxy mode.
1485 // Consume the event.
1487 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1488 // Update the user agent.
1489 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1491 // Reload the current WebView.
1492 currentWebView.reload();
1494 // Consume the event.
1496 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1497 // Update the user agent.
1498 currentWebView.getSettings().setUserAgentString("");
1500 // Reload the current WebView.
1501 currentWebView.reload();
1503 // Consume the event.
1505 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1506 // Update the user agent.
1507 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1509 // Reload the current WebView.
1510 currentWebView.reload();
1512 // Consume the event.
1514 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1515 // Update the user agent.
1516 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1518 // Reload the current WebView.
1519 currentWebView.reload();
1521 // Consume the event.
1523 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1524 // Update the user agent.
1525 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1527 // Reload the current WebView.
1528 currentWebView.reload();
1530 // Consume the event.
1532 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1533 // Update the user agent.
1534 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1536 // Reload the current WebView.
1537 currentWebView.reload();
1539 // Consume the event.
1541 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1542 // Update the user agent.
1543 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1545 // Reload the current WebView.
1546 currentWebView.reload();
1548 // Consume the event.
1550 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1551 // Update the user agent.
1552 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1554 // Reload the current WebView.
1555 currentWebView.reload();
1557 // Consume the event.
1559 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1560 // Update the user agent.
1561 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1563 // Reload the current WebView.
1564 currentWebView.reload();
1566 // Consume the event.
1568 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1569 // Update the user agent.
1570 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1572 // Reload the current WebView.
1573 currentWebView.reload();
1575 // Consume the event.
1577 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1578 // Update the user agent.
1579 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1581 // Reload the current WebView.
1582 currentWebView.reload();
1584 // Consume the event.
1586 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1587 // Update the user agent.
1588 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1590 // Reload the current WebView.
1591 currentWebView.reload();
1593 // Consume the event.
1595 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1596 // Update the user agent.
1597 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1599 // Reload the current WebView.
1600 currentWebView.reload();
1602 // Consume the event.
1604 } else if (menuItemId == R.id.font_size) { // Font size.
1605 // Instantiate the font size dialog.
1606 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1608 // Show the font size dialog.
1609 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1611 // Consume the event.
1613 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1614 // Toggle the stored status of swipe to refresh.
1615 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1617 // Update the swipe refresh layout.
1618 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1619 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1620 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1621 } else { // Swipe to refresh is disabled.
1622 // Disable the swipe refresh layout.
1623 swipeRefreshLayout.setEnabled(false);
1626 // Consume the event.
1628 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1629 // Toggle the viewport.
1630 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1632 // Consume the event.
1634 } else if (menuItemId == R.id.display_images) { // Display images.
1635 // Toggle the displaying of images.
1636 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1637 // Disable loading of images.
1638 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1640 // Reload the website to remove existing images.
1641 currentWebView.reload();
1642 } else { // Images are not currently loaded automatically.
1643 // Enable loading of images. Missing images will be loaded without the need for a reload.
1644 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1647 // Consume the event.
1649 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1650 // Check to see if dark WebView is supported by this WebView.
1651 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1652 // Toggle the dark WebView setting.
1653 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1654 // Turn off dark WebView.
1655 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1656 } else { // Dark WebView is currently disabled.
1657 // Turn on dark WebView.
1658 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1662 // Consume the event.
1664 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1665 // Get a handle for the views.
1666 Toolbar toolbar = findViewById(R.id.toolbar);
1667 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1668 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1670 // Set the minimum height of the find on page linear layout to match the toolbar.
1671 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1673 // Hide the toolbar.
1674 toolbar.setVisibility(View.GONE);
1676 // Show the find on page linear layout.
1677 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1679 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1680 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1681 findOnPageEditText.postDelayed(() -> {
1682 // Set the focus on the find on page edit text.
1683 findOnPageEditText.requestFocus();
1685 // Get a handle for the input method manager.
1686 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1688 // Remove the lint warning below that the input method manager might be null.
1689 assert inputMethodManager != null;
1691 // Display the keyboard. `0` sets no input flags.
1692 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1695 // Consume the event.
1697 } else if (menuItemId == R.id.print) { // Print.
1698 // Get a print manager instance.
1699 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1701 // Remove the lint error below that print manager might be null.
1702 assert printManager != null;
1704 // Create a print document adapter from the current WebView.
1705 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1707 // Print the document.
1708 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1710 // Consume the event.
1712 } else if (menuItemId == R.id.save_url) { // Save URL.
1713 // Check the download preference.
1714 if (downloadWithExternalApp) { // Download with an external app.
1715 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1716 } else { // Handle the download inside of Privacy Browser.
1717 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1718 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1719 currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1722 // Consume the event.
1724 } else if (menuItemId == R.id.save_archive) {
1725 // Instantiate the save dialog.
1726 DialogFragment saveArchiveFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_ARCHIVE, currentWebView.getCurrentUrl(), null, null, null,
1729 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1730 saveArchiveFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1733 } else if (menuItemId == R.id.save_image) { // Save image.
1734 // Instantiate the save dialog.
1735 DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_IMAGE, currentWebView.getCurrentUrl(), null, null, null,
1738 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1739 saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1741 // Consume the event.
1743 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1744 // Instantiate the create home screen shortcut dialog.
1745 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1746 currentWebView.getFavoriteOrDefaultIcon());
1748 // Show the create home screen shortcut dialog.
1749 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1751 // Consume the event.
1753 } else if (menuItemId == R.id.view_source) { // View source.
1754 // Create an intent to launch the view source activity.
1755 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1757 // Add the variables to the intent.
1758 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1759 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1762 startActivity(viewSourceIntent);
1764 // Consume the event.
1766 } else if (menuItemId == R.id.share_url) { // Share URL.
1767 // Setup the share string.
1768 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1770 // Create the share intent.
1771 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1773 // Add the share string to the intent.
1774 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1776 // Set the MIME type.
1777 shareIntent.setType("text/plain");
1779 // Set the intent to open in a new task.
1780 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1783 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1785 // Consume the event.
1787 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1788 // Open the URL with an outside app.
1789 openWithApp(currentWebView.getUrl());
1791 // Consume the event.
1793 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1794 // Open the URL with an outside browser.
1795 openWithBrowser(currentWebView.getUrl());
1797 // Consume the event.
1799 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1800 // Check if domain settings currently exist.
1801 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1802 // Reapply the domain settings on returning to `MainWebViewActivity`.
1803 reapplyDomainSettingsOnRestart = true;
1805 // Create an intent to launch the domains activity.
1806 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1808 // Add the extra information to the intent.
1809 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1810 domainsIntent.putExtra("close_on_back", true);
1811 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1813 // Get the current certificate.
1814 SslCertificate sslCertificate = currentWebView.getCertificate();
1816 // Check to see if the SSL certificate is populated.
1817 if (sslCertificate != null) {
1818 // Extract the certificate to strings.
1819 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1820 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1821 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1822 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1823 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1824 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1825 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1826 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1828 // Add the certificate to the intent.
1829 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1830 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1831 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1832 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1833 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1834 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1835 domainsIntent.putExtra("ssl_start_date", startDateLong);
1836 domainsIntent.putExtra("ssl_end_date", endDateLong);
1839 // Check to see if the current IP addresses have been received.
1840 if (currentWebView.hasCurrentIpAddresses()) {
1841 // Add the current IP addresses to the intent.
1842 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1846 startActivity(domainsIntent);
1847 } else { // Add a new domain.
1848 // Apply the new domain settings on returning to `MainWebViewActivity`.
1849 reapplyDomainSettingsOnRestart = true;
1851 // Get the current domain
1852 Uri currentUri = Uri.parse(currentWebView.getUrl());
1853 String currentDomain = currentUri.getHost();
1855 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1856 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1858 // Create the domain and store the database ID.
1859 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1861 // Create an intent to launch the domains activity.
1862 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1864 // Add the extra information to the intent.
1865 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1866 domainsIntent.putExtra("close_on_back", true);
1867 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1869 // Get the current certificate.
1870 SslCertificate sslCertificate = currentWebView.getCertificate();
1872 // Check to see if the SSL certificate is populated.
1873 if (sslCertificate != null) {
1874 // Extract the certificate to strings.
1875 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1876 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1877 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1878 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1879 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1880 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1881 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1882 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1884 // Add the certificate to the intent.
1885 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1886 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1887 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1888 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1889 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1890 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1891 domainsIntent.putExtra("ssl_start_date", startDateLong);
1892 domainsIntent.putExtra("ssl_end_date", endDateLong);
1895 // Check to see if the current IP addresses have been received.
1896 if (currentWebView.hasCurrentIpAddresses()) {
1897 // Add the current IP addresses to the intent.
1898 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1902 startActivity(domainsIntent);
1905 // Consume the event.
1907 } else if (menuItemId == R.id.ad_consent) { // Ad consent.
1908 // Instantiate the ad consent dialog.
1909 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1911 // Display the ad consent dialog.
1912 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1914 // Consume the event.
1916 } else { // There is no match with the options menu. Pass the event up to the parent method.
1917 // Don't consume the event.
1918 return super.onOptionsItemSelected(menuItem);
1922 // removeAllCookies is deprecated, but it is required for API < 21.
1924 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1925 // Get a handle for the shared preferences.
1926 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1928 // Get the menu item ID.
1929 int menuItemId = menuItem.getItemId();
1931 // Run the commands that correspond to the selected menu item.
1932 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
1933 // Clear and exit Privacy Browser.
1935 } else if (menuItemId == R.id.home) { // Home.
1936 // Load the homepage.
1937 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1938 } else if (menuItemId == R.id.back) { // Back.
1939 // Check if the WebView can go back.
1940 if (currentWebView.canGoBack()) {
1941 // Get the current web back forward list.
1942 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1944 // Get the previous entry URL.
1945 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1947 // Apply the domain settings.
1948 applyDomainSettings(currentWebView, previousUrl, false, false, false);
1950 // Load the previous website in the history.
1951 currentWebView.goBack();
1953 } else if (menuItemId == R.id.forward) { // Forward.
1954 // Check if the WebView can go forward.
1955 if (currentWebView.canGoForward()) {
1956 // Get the current web back forward list.
1957 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1959 // Get the next entry URL.
1960 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1962 // Apply the domain settings.
1963 applyDomainSettings(currentWebView, nextUrl, false, false, false);
1965 // Load the next website in the history.
1966 currentWebView.goForward();
1968 } else if (menuItemId == R.id.history) { // History.
1969 // Instantiate the URL history dialog.
1970 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1972 // Show the URL history dialog.
1973 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1974 } else if (menuItemId == R.id.open) { // Open.
1975 // Instantiate the open file dialog.
1976 DialogFragment openDialogFragment = new OpenDialog();
1978 // Show the open file dialog.
1979 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1980 } else if (menuItemId == R.id.requests) { // Requests.
1981 // Populate the resource requests.
1982 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1984 // Create an intent to launch the Requests activity.
1985 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1987 // Add the block third-party requests status to the intent.
1988 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1991 startActivity(requestsIntent);
1992 } else if (menuItemId == R.id.downloads) { // Downloads.
1993 // Try the default system download manager.
1995 // Launch the default system Download Manager.
1996 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1998 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
1999 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2002 startActivity(defaultDownloadManagerIntent);
2003 } catch (Exception defaultDownloadManagerException) {
2004 // Try a generic file manager.
2006 // Create a generic file manager intent.
2007 Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2009 // Open the download directory.
2010 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2012 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2013 genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2016 startActivity(genericFileManagerIntent);
2017 } catch (Exception genericFileManagerException) {
2018 // Try an alternate file manager.
2020 // Create an alternate file manager intent.
2021 Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2023 // Open the download directory.
2024 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2026 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2027 alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2029 // Open the alternate file manager.
2030 startActivity(alternateFileManagerIntent);
2031 } catch (Exception alternateFileManagerException) {
2032 // Display a snackbar.
2033 Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2037 } else if (menuItemId == R.id.domains) { // Domains.
2038 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2039 reapplyDomainSettingsOnRestart = true;
2041 // Launch the domains activity.
2042 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2044 // Add the extra information to the intent.
2045 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2047 // Get the current certificate.
2048 SslCertificate sslCertificate = currentWebView.getCertificate();
2050 // Check to see if the SSL certificate is populated.
2051 if (sslCertificate != null) {
2052 // Extract the certificate to strings.
2053 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2054 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2055 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2056 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2057 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2058 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2059 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2060 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2062 // Add the certificate to the intent.
2063 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2064 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2065 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2066 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2067 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2068 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2069 domainsIntent.putExtra("ssl_start_date", startDateLong);
2070 domainsIntent.putExtra("ssl_end_date", endDateLong);
2073 // Check to see if the current IP addresses have been received.
2074 if (currentWebView.hasCurrentIpAddresses()) {
2075 // Add the current IP addresses to the intent.
2076 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2080 startActivity(domainsIntent);
2081 } else if (menuItemId == R.id.settings) { // Settings.
2082 // Set the flag to reapply app settings on restart when returning from Settings.
2083 reapplyAppSettingsOnRestart = true;
2085 // Set the flag to reapply the domain settings on restart when returning from Settings.
2086 reapplyDomainSettingsOnRestart = true;
2088 // Launch the settings activity.
2089 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2090 startActivity(settingsIntent);
2091 } else if (menuItemId == R.id.import_export) { // Import/Export.
2092 // Create an intent to launch the import/export activity.
2093 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2096 startActivity(importExportIntent);
2097 } else if (menuItemId == R.id.logcat) { // Logcat.
2098 // Create an intent to launch the logcat activity.
2099 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2102 startActivity(logcatIntent);
2103 } else if (menuItemId == R.id.guide) { // Guide.
2104 // Create an intent to launch the guide activity.
2105 Intent guideIntent = new Intent(this, GuideActivity.class);
2108 startActivity(guideIntent);
2109 } else if (menuItemId == R.id.about) { // About
2110 // Create an intent to launch the about activity.
2111 Intent aboutIntent = new Intent(this, AboutActivity.class);
2113 // Create a string array for the blocklist versions.
2114 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],
2115 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2117 // Add the blocklist versions to the intent.
2118 aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2121 startActivity(aboutIntent);
2124 // Close the navigation drawer.
2125 drawerLayout.closeDrawer(GravityCompat.START);
2130 public void onPostCreate(Bundle savedInstanceState) {
2131 // Run the default commands.
2132 super.onPostCreate(savedInstanceState);
2134 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2135 actionBarDrawerToggle.syncState();
2139 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2140 // Run the default commands.
2141 super.onConfigurationChanged(newConfig);
2143 // Reload the ad for the free flavor if not in full screen mode.
2144 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2145 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2146 View adView = findViewById(R.id.adview);
2148 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2149 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2150 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2153 // `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:
2154 // https://code.google.com/p/android/issues/detail?id=20493#c8
2155 // ActivityCompat.invalidateOptionsMenu(this);
2159 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2160 // Get the hit test result.
2161 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2163 // Define the URL strings.
2164 final String imageUrl;
2165 final String linkUrl;
2167 // Get handles for the system managers.
2168 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2170 // Remove the lint errors below that the clipboard manager might be null.
2171 assert clipboardManager != null;
2173 // Process the link according to the type.
2174 switch (hitTestResult.getType()) {
2175 // `SRC_ANCHOR_TYPE` is a link.
2176 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2177 // Get the target URL.
2178 linkUrl = hitTestResult.getExtra();
2180 // Set the target URL as the title of the `ContextMenu`.
2181 menu.setHeaderTitle(linkUrl);
2183 // Add an Open in New Tab entry.
2184 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2185 // Load the link URL in a new tab and move to it.
2186 addNewTab(linkUrl, true);
2188 // Consume the event.
2192 // Add an Open in Background entry.
2193 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2194 // Load the link URL in a new tab but do not move to it.
2195 addNewTab(linkUrl, false);
2197 // Consume the event.
2201 // Add an Open with App entry.
2202 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2203 openWithApp(linkUrl);
2205 // Consume the event.
2209 // Add an Open with Browser entry.
2210 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2211 openWithBrowser(linkUrl);
2213 // Consume the event.
2217 // Add a Copy URL entry.
2218 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2219 // Save the link URL in a `ClipData`.
2220 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2222 // Set the `ClipData` as the clipboard's primary clip.
2223 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2225 // Consume the event.
2229 // Add a Save URL entry.
2230 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2231 // Check the download preference.
2232 if (downloadWithExternalApp) { // Download with an external app.
2233 downloadUrlWithExternalApp(linkUrl);
2234 } else { // Handle the download inside of Privacy Browser.
2235 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2236 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2237 currentWebView.getAcceptCookies()).execute(linkUrl);
2240 // Consume the event.
2244 // Add an empty Cancel entry, which by default closes the context menu.
2245 menu.add(R.string.cancel);
2248 // `IMAGE_TYPE` is an image.
2249 case WebView.HitTestResult.IMAGE_TYPE:
2250 // Get the image URL.
2251 imageUrl = hitTestResult.getExtra();
2253 // Remove the incorrect lint warning below that the image URL might be null.
2254 assert imageUrl != null;
2256 // Set the context menu title.
2257 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2258 // Truncate the image URL before making it the title.
2259 menu.setHeaderTitle(imageUrl.substring(0, 100));
2260 } else { // The image URL does not contain the full image data.
2261 // Set the image URL as the title of the context menu.
2262 menu.setHeaderTitle(imageUrl);
2265 // Add an Open in New Tab entry.
2266 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2267 // Load the image in a new tab.
2268 addNewTab(imageUrl, true);
2270 // Consume the event.
2274 // Add an Open with App entry.
2275 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2276 // Open the image URL with an external app.
2277 openWithApp(imageUrl);
2279 // Consume the event.
2283 // Add an Open with Browser entry.
2284 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2285 // Open the image URL with an external browser.
2286 openWithBrowser(imageUrl);
2288 // Consume the event.
2292 // Add a View Image entry.
2293 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2294 // Load the image in the current tab.
2295 loadUrl(currentWebView, imageUrl);
2297 // Consume the event.
2301 // Add a Save Image entry.
2302 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2303 // Check the download preference.
2304 if (downloadWithExternalApp) { // Download with an external app.
2305 downloadUrlWithExternalApp(imageUrl);
2306 } else { // Handle the download inside of Privacy Browser.
2307 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2308 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2309 currentWebView.getAcceptCookies()).execute(imageUrl);
2312 // Consume the event.
2316 // Add a Copy URL entry.
2317 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2318 // Save the image URL in a clip data.
2319 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2321 // Set the clip data as the clipboard's primary clip.
2322 clipboardManager.setPrimaryClip(imageTypeClipData);
2324 // Consume the event.
2328 // Add an empty Cancel entry, which by default closes the context menu.
2329 menu.add(R.string.cancel);
2332 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2333 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2334 // Get the image URL.
2335 imageUrl = hitTestResult.getExtra();
2337 // Instantiate a handler.
2338 Handler handler = new Handler();
2340 // Get a message from the handler.
2341 Message message = handler.obtainMessage();
2343 // Request the image details from the last touched node be returned in the message.
2344 currentWebView.requestFocusNodeHref(message);
2346 // Get the link URL from the message data.
2347 linkUrl = message.getData().getString("url");
2349 // Set the link URL as the title of the context menu.
2350 menu.setHeaderTitle(linkUrl);
2352 // Add an Open in New Tab entry.
2353 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2354 // Load the link URL in a new tab and move to it.
2355 addNewTab(linkUrl, true);
2357 // Consume the event.
2361 // Add an Open in Background entry.
2362 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2363 // Lod the link URL in a new tab but do not move to it.
2364 addNewTab(linkUrl, false);
2366 // Consume the event.
2370 // Add an Open Image in New Tab entry.
2371 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2372 // Load the image in a new tab and move to it.
2373 addNewTab(imageUrl, true);
2375 // Consume the event.
2379 // Add an Open with App entry.
2380 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2381 // Open the link URL with an external app.
2382 openWithApp(linkUrl);
2384 // Consume the event.
2388 // Add an Open with Browser entry.
2389 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2390 // Open the link URL with an external browser.
2391 openWithBrowser(linkUrl);
2393 // Consume the event.
2397 // Add a View Image entry.
2398 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2399 // View the image in the current tab.
2400 loadUrl(currentWebView, imageUrl);
2402 // Consume the event.
2406 // Add a Save Image entry.
2407 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2408 // Check the download preference.
2409 if (downloadWithExternalApp) { // Download with an external app.
2410 downloadUrlWithExternalApp(imageUrl);
2411 } else { // Handle the download inside of Privacy Browser.
2412 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2413 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2414 currentWebView.getAcceptCookies()).execute(imageUrl);
2417 // Consume the event.
2421 // Add a Copy URL entry.
2422 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2423 // Save the link URL in a clip data.
2424 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2426 // Set the clip data as the clipboard's primary clip.
2427 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2429 // Consume the event.
2433 // Add a Save URL entry.
2434 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2435 // Check the download preference.
2436 if (downloadWithExternalApp) { // Download with an external app.
2437 downloadUrlWithExternalApp(linkUrl);
2438 } else { // Handle the download inside of Privacy Browser.
2439 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2440 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2441 currentWebView.getAcceptCookies()).execute(linkUrl);
2444 // Consume the event.
2448 // Add an empty Cancel entry, which by default closes the context menu.
2449 menu.add(R.string.cancel);
2452 case WebView.HitTestResult.EMAIL_TYPE:
2453 // Get the target URL.
2454 linkUrl = hitTestResult.getExtra();
2456 // Set the target URL as the title of the `ContextMenu`.
2457 menu.setHeaderTitle(linkUrl);
2459 // Add a Write Email entry.
2460 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2461 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2462 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2464 // Parse the url and set it as the data for the `Intent`.
2465 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2467 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2468 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2472 startActivity(emailIntent);
2473 } catch (ActivityNotFoundException exception) {
2474 // Display a snackbar.
2475 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2478 // Consume the event.
2482 // Add a Copy Email Address entry.
2483 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2484 // Save the email address in a `ClipData`.
2485 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2487 // Set the `ClipData` as the clipboard's primary clip.
2488 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2490 // Consume the event.
2494 // Add an empty Cancel entry, which by default closes the context menu.
2495 menu.add(R.string.cancel);
2501 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2502 // Get a handle for the bookmarks list view.
2503 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2506 Dialog dialog = dialogFragment.getDialog();
2508 // Remove the incorrect lint warning below that the dialog might be null.
2509 assert dialog != null;
2511 // Get the views from the dialog fragment.
2512 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2513 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2515 // Extract the strings from the edit texts.
2516 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2517 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2519 // Create a favorite icon byte array output stream.
2520 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2522 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2523 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2525 // Convert the favorite icon byte array stream to a byte array.
2526 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2528 // Display the new bookmark below the current items in the (0 indexed) list.
2529 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2531 // Create the bookmark.
2532 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2534 // Update the bookmarks cursor with the current contents of this folder.
2535 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2537 // Update the list view.
2538 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2540 // Scroll to the new bookmark.
2541 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2545 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2546 // Get a handle for the bookmarks list view.
2547 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2550 Dialog dialog = dialogFragment.getDialog();
2552 // Remove the incorrect lint warning below that the dialog might be null.
2553 assert dialog != null;
2555 // Get handles for the views in the dialog fragment.
2556 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2557 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2558 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2560 // Get new folder name string.
2561 String folderNameString = folderNameEditText.getText().toString();
2563 // Create a folder icon bitmap.
2564 Bitmap folderIconBitmap;
2566 // Set the folder icon bitmap according to the dialog.
2567 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2568 // Get the default folder icon drawable.
2569 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2571 // Convert the folder icon drawable to a bitmap drawable.
2572 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2574 // Convert the folder icon bitmap drawable to a bitmap.
2575 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2576 } else { // Use the WebView favorite icon.
2577 // Copy the favorite icon bitmap to the folder icon bitmap.
2578 folderIconBitmap = favoriteIconBitmap;
2581 // Create a folder icon byte array output stream.
2582 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2584 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2585 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2587 // Convert the folder icon byte array stream to a byte array.
2588 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2590 // Move all the bookmarks down one in the display order.
2591 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2592 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2593 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2596 // Create the folder, which will be placed at the top of the `ListView`.
2597 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2599 // Update the bookmarks cursor with the current contents of this folder.
2600 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2602 // Update the `ListView`.
2603 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2605 // Scroll to the new folder.
2606 bookmarksListView.setSelection(0);
2610 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2611 // Remove the incorrect lint warning below that the dialog fragment might be null.
2612 assert dialogFragment != null;
2615 Dialog dialog = dialogFragment.getDialog();
2617 // Remove the incorrect lint warning below that the dialog might be null.
2618 assert dialog != null;
2620 // Get handles for the views from the dialog.
2621 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2622 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2623 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2624 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2626 // Get the new folder name.
2627 String newFolderNameString = editFolderNameEditText.getText().toString();
2629 // Check if the favorite icon has changed.
2630 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2631 // Update the name in the database.
2632 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2633 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2634 // Create the new folder icon Bitmap.
2635 Bitmap folderIconBitmap;
2637 // Populate the new folder icon bitmap.
2638 if (defaultFolderIconRadioButton.isChecked()) {
2639 // Get the default folder icon drawable.
2640 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2642 // Convert the folder icon drawable to a bitmap drawable.
2643 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2645 // Convert the folder icon bitmap drawable to a bitmap.
2646 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2647 } else { // Use the `WebView` favorite icon.
2648 // Copy the favorite icon bitmap to the folder icon bitmap.
2649 folderIconBitmap = favoriteIconBitmap;
2652 // Create a folder icon byte array output stream.
2653 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2655 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2656 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2658 // Convert the folder icon byte array stream to a byte array.
2659 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2661 // Update the folder icon in the database.
2662 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2663 } else { // The folder icon and the name have changed.
2664 // Get the new folder icon bitmap.
2665 Bitmap folderIconBitmap;
2666 if (defaultFolderIconRadioButton.isChecked()) {
2667 // Get the default folder icon drawable.
2668 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2670 // Convert the folder icon drawable to a bitmap drawable.
2671 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2673 // Convert the folder icon bitmap drawable to a bitmap.
2674 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2675 } else { // Use the `WebView` favorite icon.
2676 // Copy the favorite icon bitmap to the folder icon bitmap.
2677 folderIconBitmap = favoriteIconBitmap;
2680 // Create a folder icon byte array output stream.
2681 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2683 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2684 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2686 // Convert the folder icon byte array stream to a byte array.
2687 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2689 // Update the folder name and icon in the database.
2690 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2693 // Update the bookmarks cursor with the current contents of this folder.
2694 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2696 // Update the `ListView`.
2697 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2700 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2702 public void onBackPressed() {
2703 // Check the different options for processing `back`.
2704 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2705 // Close the navigation drawer.
2706 drawerLayout.closeDrawer(GravityCompat.START);
2707 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2708 // close the bookmarks drawer.
2709 drawerLayout.closeDrawer(GravityCompat.END);
2710 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2711 // Exit the full screen video.
2712 exitFullScreenVideo();
2713 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2714 // Get the current web back forward list.
2715 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2717 // Get the previous entry URL.
2718 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2720 // Apply the domain settings.
2721 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2724 currentWebView.goBack();
2725 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2726 // Close the current tab.
2728 } else { // There isn't anything to do in Privacy Browser.
2729 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2730 if (Build.VERSION.SDK_INT >= 21) {
2731 finishAndRemoveTask();
2736 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2741 // Process the results of a file browse.
2743 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2744 // Run the default commands.
2745 super.onActivityResult(requestCode, resultCode, returnedIntent);
2747 // Run the commands that correlate to the specified request code.
2748 switch (requestCode) {
2749 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2750 // File uploads only work on API >= 21.
2751 if (Build.VERSION.SDK_INT >= 21) {
2752 // Pass the file to the WebView.
2753 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2757 case BROWSE_OPEN_REQUEST_CODE:
2758 // Don't do anything if the user pressed back from the file picker.
2759 if (resultCode == Activity.RESULT_OK) {
2760 // Get a handle for the open dialog fragment.
2761 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2763 // Only update the file name if the dialog still exists.
2764 if (openDialogFragment != null) {
2765 // Get a handle for the open dialog.
2766 Dialog openDialog = openDialogFragment.getDialog();
2768 // Remove the incorrect lint warning below that the dialog might be null.
2769 assert openDialog != null;
2771 // Get a handle for the file name edit text.
2772 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2774 // Get the file name URI from the intent.
2775 Uri fileNameUri = returnedIntent.getData();
2777 // Get the file name string from the URI.
2778 String fileNameString = fileNameUri.toString();
2780 // Set the file name text.
2781 fileNameEditText.setText(fileNameString);
2783 // Move the cursor to the end of the file name edit text.
2784 fileNameEditText.setSelection(fileNameString.length());
2789 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2790 // Don't do anything if the user pressed back from the file picker.
2791 if (resultCode == Activity.RESULT_OK) {
2792 // Get a handle for the save dialog fragment.
2793 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2795 // Only update the file name if the dialog still exists.
2796 if (saveWebpageDialogFragment != null) {
2797 // Get a handle for the save webpage dialog.
2798 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2800 // Remove the incorrect lint warning below that the dialog might be null.
2801 assert saveWebpageDialog != null;
2803 // Get a handle for the file name edit text.
2804 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2806 // Get the file name URI from the intent.
2807 Uri fileNameUri = returnedIntent.getData();
2809 // Get the file name string from the URI.
2810 String fileNameString = fileNameUri.toString();
2812 // Set the file name text.
2813 fileNameEditText.setText(fileNameString);
2815 // Move the cursor to the end of the file name edit text.
2816 fileNameEditText.setSelection(fileNameString.length());
2823 private void loadUrlFromTextBox() {
2824 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2825 String unformattedUrlString = urlEditText.getText().toString().trim();
2827 // Initialize the formatted URL string.
2830 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2831 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2832 // Load the entire content URL.
2833 url = unformattedUrlString;
2834 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2835 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2836 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2837 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2838 unformattedUrlString = "https://" + unformattedUrlString;
2841 // Initialize `unformattedUrl`.
2842 URL unformattedUrl = null;
2844 // 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.
2846 unformattedUrl = new URL(unformattedUrlString);
2847 } catch (MalformedURLException e) {
2848 e.printStackTrace();
2851 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2852 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2853 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2854 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2855 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2856 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2859 Uri.Builder uri = new Uri.Builder();
2860 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2862 // Decode the URI as a UTF-8 string in.
2864 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2865 } catch (UnsupportedEncodingException exception) {
2866 // Do nothing. The formatted URL string will remain blank.
2868 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2869 // Create an encoded URL String.
2870 String encodedUrlString;
2872 // Sanitize the search input.
2874 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2875 } catch (UnsupportedEncodingException exception) {
2876 encodedUrlString = "";
2879 // Add the base search URL.
2880 url = searchURL + encodedUrlString;
2883 // 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.
2884 urlEditText.clearFocus();
2887 loadUrl(currentWebView, url);
2890 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2891 // Sanitize the URL.
2892 url = sanitizeUrl(url);
2894 // Apply the domain settings and load the URL.
2895 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2898 public void findPreviousOnPage(View view) {
2899 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2900 currentWebView.findNext(false);
2903 public void findNextOnPage(View view) {
2904 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2905 currentWebView.findNext(true);
2908 public void closeFindOnPage(View view) {
2909 // Get a handle for the views.
2910 Toolbar toolbar = findViewById(R.id.toolbar);
2911 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2912 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2914 // Delete the contents of `find_on_page_edittext`.
2915 findOnPageEditText.setText(null);
2917 // Clear the highlighted phrases if the WebView is not null.
2918 if (currentWebView != null) {
2919 currentWebView.clearMatches();
2922 // Hide the find on page linear layout.
2923 findOnPageLinearLayout.setVisibility(View.GONE);
2925 // Show the toolbar.
2926 toolbar.setVisibility(View.VISIBLE);
2928 // Get a handle for the input method manager.
2929 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2931 // Remove the lint warning below that the input method manager might be null.
2932 assert inputMethodManager != null;
2934 // Hide the keyboard.
2935 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2939 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2940 // Remove the incorrect lint warning below that the dialog fragment might be null.
2941 assert dialogFragment != null;
2944 Dialog dialog = dialogFragment.getDialog();
2946 // Remove the incorrect lint warning below tha the dialog might be null.
2947 assert dialog != null;
2949 // Get a handle for the font size edit text.
2950 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2952 // Initialize the new font size variable with the current font size.
2953 int newFontSize = currentWebView.getSettings().getTextZoom();
2955 // Get the font size from the edit text.
2957 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2958 } catch (Exception exception) {
2959 // If the edit text does not contain a valid font size do nothing.
2962 // Apply the new font size.
2963 currentWebView.getSettings().setTextZoom(newFontSize);
2967 public void onOpen(DialogFragment dialogFragment) {
2969 Dialog dialog = dialogFragment.getDialog();
2971 // Remove the incorrect lint warning below that the dialog might be null.
2972 assert dialog != null;
2974 // Get handles for the views.
2975 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2976 CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
2978 // Get the file path string.
2979 String openFilePath = fileNameEditText.getText().toString();
2981 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
2982 applyDomainSettings(currentWebView, openFilePath, true, false, false);
2984 // Open the file according to the type.
2985 if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
2987 // Get the MHT file input stream.
2988 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
2990 // Create a temporary MHT file.
2991 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
2993 // Get a file output stream for the temporary MHT file.
2994 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
2996 // Create a transfer byte array.
2997 byte[] transferByteArray = new byte[1024];
2999 // Create an integer to track the number of bytes read.
3002 // Copy the temporary MHT file input stream to the MHT output stream.
3003 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3004 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3007 // Flush the temporary MHT file output stream.
3008 temporaryMhtFileOutputStream.flush();
3010 // Close the streams.
3011 temporaryMhtFileOutputStream.close();
3012 mhtFileInputStream.close();
3014 // Load the temporary MHT file.
3015 currentWebView.loadUrl(temporaryMhtFile.toString());
3016 } catch (Exception exception) {
3017 // Display a snackbar.
3018 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
3020 } else { // Let the WebView handle opening of the file.
3022 currentWebView.loadUrl(openFilePath);
3026 private void downloadUrlWithExternalApp(String url) {
3027 // Create a download intent. Not specifying the action type will display the maximum number of options.
3028 Intent downloadIntent = new Intent();
3030 // Set the URI and the mime type.
3031 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3033 // Flag the intent to open in a new task.
3034 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3036 // Show the chooser.
3037 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3040 public void onSaveWebpage(int saveType, @NonNull String originalUrlString, DialogFragment dialogFragment) {
3042 Dialog dialog = dialogFragment.getDialog();
3044 // Remove the incorrect lint warning below that the dialog might be null.
3045 assert dialog != null;
3047 // Get a handle for the file name edit text.
3048 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3050 // Get the file path from the edit text.
3051 String saveWebpageFilePath = fileNameEditText.getText().toString();
3053 //Save the webpage according to the save type.
3055 case SaveWebpageDialog.SAVE_URL:
3056 // Get a handle for the dialog URL edit text.
3057 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3059 // Define the save webpage URL.
3060 String saveWebpageUrl;
3063 if (originalUrlString.startsWith("data:")) {
3064 // Save the original URL.
3065 saveWebpageUrl = originalUrlString;
3067 // Get the URL from the edit text, which may have been modified.
3068 saveWebpageUrl = dialogUrlEditText.getText().toString();
3072 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveWebpageUrl);
3075 case SaveWebpageDialog.SAVE_ARCHIVE:
3077 // Create a temporary MHT file.
3078 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3080 // Save the temporary MHT file.
3081 currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
3082 if (callbackValue != null) { // The temporary MHT file was saved successfully.
3084 // Create a temporary MHT file input stream.
3085 FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
3087 // Get an output stream for the save webpage file path.
3088 OutputStream mhtOutputStream = getContentResolver().openOutputStream(Uri.parse(saveWebpageFilePath));
3090 // Create a transfer byte array.
3091 byte[] transferByteArray = new byte[1024];
3093 // Create an integer to track the number of bytes read.
3096 // Copy the temporary MHT file input stream to the MHT output stream.
3097 while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
3098 mhtOutputStream.write(transferByteArray, 0, bytesRead);
3101 // Close the streams.
3102 mhtOutputStream.close();
3103 temporaryMhtFileInputStream.close();
3105 // Display a snackbar.
3106 Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + currentWebView.getCurrentUrl(), Snackbar.LENGTH_SHORT).show();
3107 } catch (Exception exception) {
3108 // Display a snackbar with the exception.
3109 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
3111 // Delete the temporary MHT file.
3112 //noinspection ResultOfMethodCallIgnored
3113 temporaryMhtFile.delete();
3115 } else { // There was an unspecified error while saving the temporary MHT file.
3116 // Display an error snackbar.
3117 Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
3120 } catch (IOException ioException) {
3121 // Display a snackbar with the IO exception.
3122 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + ioException.toString(), Snackbar.LENGTH_INDEFINITE).show();
3126 case SaveWebpageDialog.SAVE_IMAGE:
3127 // Save the webpage image.
3128 new SaveWebpageImage(this, saveWebpageFilePath, currentWebView).execute();
3133 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3134 @SuppressLint("ClickableViewAccessibility")
3135 private void initializeApp() {
3136 // Get a handle for the input method.
3137 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3139 // Remove the lint warning below that the input method manager might be null.
3140 assert inputMethodManager != null;
3142 // Initialize the gray foreground color spans for highlighting the URLs. The deprecated `getResources()` must be used until API >= 23.
3143 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3144 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3146 // Get the current theme status.
3147 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3149 // Set the red color span according to the theme.
3150 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3151 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3153 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
3156 // Remove the formatting from the URL edit text when the user is editing the text.
3157 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3158 if (hasFocus) { // The user is editing the URL text box.
3159 // Remove the highlighting.
3160 urlEditText.getText().removeSpan(redColorSpan);
3161 urlEditText.getText().removeSpan(initialGrayColorSpan);
3162 urlEditText.getText().removeSpan(finalGrayColorSpan);
3163 } else { // The user has stopped editing the URL text box.
3164 // Move to the beginning of the string.
3165 urlEditText.setSelection(0);
3167 // Reapply the highlighting.
3172 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3173 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3174 // If the event is a key-down event on the `enter` button, load the URL.
3175 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3176 // Load the URL into the mainWebView and consume the event.
3177 loadUrlFromTextBox();
3179 // If the enter key was pressed, consume the event.
3182 // If any other key was pressed, do not consume the event.
3187 // Create an Orbot status broadcast receiver.
3188 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3190 public void onReceive(Context context, Intent intent) {
3191 // Store the content of the status message in `orbotStatus`.
3192 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3194 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3195 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3196 // Reset the waiting for proxy status.
3197 waitingForProxy = false;
3199 // Get a handle for the waiting for proxy dialog.
3200 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3202 // Dismiss the waiting for proxy dialog if it is displayed.
3203 if (waitingForProxyDialogFragment != null) {
3204 waitingForProxyDialogFragment.dismiss();
3207 // Reload existing URLs and load any URLs that are waiting for the proxy.
3208 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3209 // Get the WebView tab fragment.
3210 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3212 // Get the fragment view.
3213 View fragmentView = webViewTabFragment.getView();
3215 // Only process the WebViews if they exist.
3216 if (fragmentView != null) {
3217 // Get the nested scroll WebView from the tab fragment.
3218 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3220 // Get the waiting for proxy URL string.
3221 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3223 // Load the pending URL if it exists.
3224 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3226 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3228 // Reset the waiting for proxy URL string.
3229 nestedScrollWebView.resetWaitingForProxyUrlString();
3230 } else { // No URL is waiting to be loaded.
3231 // Reload the existing URL.
3232 nestedScrollWebView.reload();
3240 // Register the Orbot status broadcast receiver on `this` context.
3241 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3243 // Get handles for views that need to be modified.
3244 LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3245 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3246 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3247 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3248 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3249 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3251 // Update the web view pager every time a tab is modified.
3252 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3254 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3259 public void onPageSelected(int position) {
3260 // Close the find on page bar if it is open.
3261 closeFindOnPage(null);
3263 // Set the current WebView.
3264 setCurrentWebView(position);
3266 // 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.
3267 if (tabLayout.getSelectedTabPosition() != position) {
3268 // Wait until the new tab has been created.
3269 tabLayout.post(() -> {
3270 // Get a handle for the tab.
3271 TabLayout.Tab tab = tabLayout.getTabAt(position);
3273 // Assert that the tab is not null.
3283 public void onPageScrollStateChanged(int state) {
3288 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3289 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3291 public void onTabSelected(TabLayout.Tab tab) {
3292 // Select the same page in the view pager.
3293 webViewPager.setCurrentItem(tab.getPosition());
3297 public void onTabUnselected(TabLayout.Tab tab) {
3302 public void onTabReselected(TabLayout.Tab tab) {
3303 // Instantiate the View SSL Certificate dialog.
3304 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3306 // Display the View SSL Certificate dialog.
3307 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3311 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3312 bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3313 // Consume the touch.
3317 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3318 launchBookmarksActivityFab.setOnClickListener(v -> {
3319 // Get a copy of the favorite icon bitmap.
3320 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3322 // Create a favorite icon byte array output stream.
3323 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3325 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3326 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3328 // Convert the favorite icon byte array stream to a byte array.
3329 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3331 // Create an intent to launch the bookmarks activity.
3332 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3334 // Add the extra information to the intent.
3335 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3336 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3337 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3338 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3341 startActivity(bookmarksIntent);
3344 // Set the create new bookmark folder FAB to display an alert dialog.
3345 createBookmarkFolderFab.setOnClickListener(v -> {
3346 // Create a create bookmark folder dialog.
3347 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3349 // Show the create bookmark folder dialog.
3350 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3353 // Set the create new bookmark FAB to display an alert dialog.
3354 createBookmarkFab.setOnClickListener(view -> {
3355 // Instantiate the create bookmark dialog.
3356 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3358 // Display the create bookmark dialog.
3359 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3362 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3363 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3365 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3370 public void onTextChanged(CharSequence s, int start, int before, int count) {
3375 public void afterTextChanged(Editable s) {
3376 // 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.
3377 if (currentWebView != null) {
3378 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3383 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3384 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3385 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3386 // Hide the soft keyboard.
3387 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3389 // Consume the event.
3391 } else { // A different key was pressed.
3392 // Do not consume the event.
3397 // Implement swipe to refresh.
3398 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3400 // Store the default progress view offsets for use later in `initializeWebView()`.
3401 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3402 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3404 // Set the refresh color scheme according to the theme.
3405 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3406 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
3408 swipeRefreshLayout.setColorSchemeResources(R.color.violet_500);
3411 // Initialize a color background typed value.
3412 TypedValue colorBackgroundTypedValue = new TypedValue();
3414 // Get the color background from the theme.
3415 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3417 // Get the color background int from the typed value.
3418 int colorBackgroundInt = colorBackgroundTypedValue.data;
3420 // Set the swipe refresh background color.
3421 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3423 // The drawer titles identify the drawer layouts in accessibility mode.
3424 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3425 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3427 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3428 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3430 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3431 currentBookmarksFolder = "";
3433 // Load the home folder, which is `""` in the database.
3434 loadBookmarksFolder();
3436 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3437 // Convert the id from long to int to match the format of the bookmarks database.
3438 int databaseId = (int) id;
3440 // Get the bookmark cursor for this ID.
3441 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3443 // Move the bookmark cursor to the first row.
3444 bookmarkCursor.moveToFirst();
3446 // Act upon the bookmark according to the type.
3447 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3448 // Store the new folder name in `currentBookmarksFolder`.
3449 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3451 // Load the new folder.
3452 loadBookmarksFolder();
3453 } else { // The selected bookmark is not a folder.
3454 // Load the bookmark URL.
3455 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3457 // Close the bookmarks drawer.
3458 drawerLayout.closeDrawer(GravityCompat.END);
3461 // Close the `Cursor`.
3462 bookmarkCursor.close();
3465 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3466 // Convert the database ID from `long` to `int`.
3467 int databaseId = (int) id;
3469 // Find out if the selected bookmark is a folder.
3470 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3472 // Check to see if the bookmark is a folder.
3473 if (isFolder) { // The bookmark is a folder.
3474 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3475 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3477 // Instantiate the edit folder bookmark dialog.
3478 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3480 // Show the edit folder bookmark dialog.
3481 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3482 } else { // The bookmark is not a folder.
3483 // Get the bookmark cursor for this ID.
3484 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3486 // Move the bookmark cursor to the first row.
3487 bookmarkCursor.moveToFirst();
3489 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3490 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3492 // Display a snackbar.
3493 Snackbar.make(currentWebView, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3496 // Consume the event.
3500 // The drawer listener is used to update the navigation menu.
3501 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3503 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3507 public void onDrawerOpened(@NonNull View drawerView) {
3511 public void onDrawerClosed(@NonNull View drawerView) {
3512 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3513 actionBarDrawerToggle.syncState();
3517 public void onDrawerStateChanged(int newState) {
3518 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3519 // Update the navigation menu items if the WebView is not null.
3520 if (currentWebView != null) {
3521 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3522 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3523 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3524 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3526 // Hide the keyboard (if displayed).
3527 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3530 // 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.
3531 urlEditText.clearFocus();
3532 currentWebView.clearFocus();
3537 // 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).
3538 customHeaders.put("X-Requested-With", "");
3540 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3541 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3543 // Get a handle for the WebView.
3544 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3546 // Store the default user agent.
3547 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3549 // Destroy the bare WebView.
3550 bareWebView.destroy();
3553 private void applyAppSettings() {
3554 // Get a handle for the shared preferences.
3555 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3557 // Store the values from the shared preferences in variables.
3558 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3559 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3560 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3561 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3562 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3563 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3564 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3565 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3566 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3568 // Apply the saved proxy mode if the app has been restarted.
3569 if (savedProxyMode != null) {
3570 // Apply the saved proxy mode.
3571 proxyMode = savedProxyMode;
3573 // Reset the saved proxy mode.
3574 savedProxyMode = null;
3577 // Get the search string.
3578 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3580 // Set the search string.
3581 if (searchString.equals("Custom URL")) { // A custom search string is used.
3582 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3583 } else { // A custom search string is not used.
3584 searchURL = searchString;
3590 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3591 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3592 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3593 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3594 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3596 // Add the scrolling behavior to the layout parameters.
3598 // Enable scrolling of the app bar.
3599 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3600 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3601 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3602 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3604 // Disable scrolling of the app bar.
3605 swipeRefreshLayoutParams.setBehavior(null);
3606 toolbarLayoutParams.setScrollFlags(0);
3607 findOnPageLayoutParams.setScrollFlags(0);
3608 tabsLayoutParams.setScrollFlags(0);
3610 // Expand the app bar if it is currently collapsed.
3611 appBarLayout.setExpanded(true);
3614 // Apply the modified layout parameters.
3615 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3616 toolbar.setLayoutParams(toolbarLayoutParams);
3617 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3618 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3620 // Set the app bar scrolling for each WebView.
3621 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3622 // Get the WebView tab fragment.
3623 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3625 // Get the fragment view.
3626 View fragmentView = webViewTabFragment.getView();
3628 // Only modify the WebViews if they exist.
3629 if (fragmentView != null) {
3630 // Get the nested scroll WebView from the tab fragment.
3631 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3633 // Set the app bar scrolling.
3634 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3638 // Update the full screen browsing mode settings.
3639 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3640 // Update the visibility of the app bar, which might have changed in the settings.
3642 // Hide the tab linear layout.
3643 tabsLinearLayout.setVisibility(View.GONE);
3645 // Hide the action bar.
3648 // Show the tab linear layout.
3649 tabsLinearLayout.setVisibility(View.VISIBLE);
3651 // Show the action bar.
3655 // Hide the banner ad in the free flavor.
3656 if (BuildConfig.FLAVOR.contentEquals("free")) {
3657 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3658 View adView = findViewById(R.id.adview);
3660 // Hide the banner ad.
3661 AdHelper.hideAd(adView);
3664 /* Hide the system bars.
3665 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3666 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3667 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3668 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3670 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3671 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3672 } else { // Privacy Browser is not in full screen browsing mode.
3673 // 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.
3674 inFullScreenBrowsingMode = false;
3676 // Show the tab linear layout.
3677 tabsLinearLayout.setVisibility(View.VISIBLE);
3679 // Show the action bar.
3682 // Show the banner ad in the free flavor.
3683 if (BuildConfig.FLAVOR.contentEquals("free")) {
3684 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3685 View adView = findViewById(R.id.adview);
3687 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3688 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
3689 AdHelper.initializeAds(adView, getApplicationContext(), this, getSupportFragmentManager(), getString(R.string.ad_unit_id));
3692 // Remove the `SYSTEM_UI` flags from the root frame layout.
3693 rootFrameLayout.setSystemUiVisibility(0);
3698 public void navigateHistory(@NonNull String url, int steps) {
3699 // Apply the domain settings.
3700 applyDomainSettings(currentWebView, url, false, false, false);
3702 // Load the history entry.
3703 currentWebView.goBackOrForward(steps);
3707 public void pinnedErrorGoBack() {
3708 // Get the current web back forward list.
3709 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3711 // Get the previous entry URL.
3712 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3714 // Apply the domain settings.
3715 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3718 currentWebView.goBack();
3721 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3722 @SuppressLint("SetJavaScriptEnabled")
3723 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3724 // Store the current URL.
3725 nestedScrollWebView.setCurrentUrl(url);
3727 // Parse the URL into a URI.
3728 Uri uri = Uri.parse(url);
3730 // Extract the domain from `uri`.
3731 String newHostName = uri.getHost();
3733 // Strings don't like to be null.
3734 if (newHostName == null) {
3738 // 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.
3739 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3740 // Set the new host name as the current domain name.
3741 nestedScrollWebView.setCurrentDomainName(newHostName);
3743 // Reset the ignoring of pinned domain information.
3744 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3746 // Clear any pinned SSL certificate or IP addresses.
3747 nestedScrollWebView.clearPinnedSslCertificate();
3748 nestedScrollWebView.clearPinnedIpAddresses();
3750 // Reset the favorite icon if specified.
3752 // Initialize the favorite icon.
3753 nestedScrollWebView.initializeFavoriteIcon();
3755 // Get the current page position.
3756 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3758 // Get the corresponding tab.
3759 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3761 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3763 // Get the tab custom view.
3764 View tabCustomView = tab.getCustomView();
3766 // Remove the warning below that the tab custom view might be null.
3767 assert tabCustomView != null;
3769 // Get the tab views.
3770 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3771 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3773 // Set the default favorite icon as the favorite icon for this tab.
3774 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3776 // Set the loading title text.
3777 tabTitleTextView.setText(R.string.loading);
3781 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3782 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3784 // Get a full cursor from `domainsDatabaseHelper`.
3785 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3787 // Initialize `domainSettingsSet`.
3788 Set<String> domainSettingsSet = new HashSet<>();
3790 // Get the domain name column index.
3791 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3793 // Populate `domainSettingsSet`.
3794 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3795 // Move `domainsCursor` to the current row.
3796 domainNameCursor.moveToPosition(i);
3798 // Store the domain name in `domainSettingsSet`.
3799 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3802 // Close `domainNameCursor.
3803 domainNameCursor.close();
3805 // Initialize the domain name in database variable.
3806 String domainNameInDatabase = null;
3808 // Check the hostname against the domain settings set.
3809 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3810 // Record the domain name in the database.
3811 domainNameInDatabase = newHostName;
3813 // Set the domain settings applied tracker to true.
3814 nestedScrollWebView.setDomainSettingsApplied(true);
3815 } else { // The hostname is not contained in the domain settings set.
3816 // Set the domain settings applied tracker to false.
3817 nestedScrollWebView.setDomainSettingsApplied(false);
3820 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3821 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3822 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3823 // Set the domain settings applied tracker to true.
3824 nestedScrollWebView.setDomainSettingsApplied(true);
3826 // Store the applied domain names as it appears in the database.
3827 domainNameInDatabase = "*." + newHostName;
3830 // Strip out the lowest subdomain of of the host name.
3831 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3835 // Get a handle for the shared preferences.
3836 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3838 // Store the general preference information.
3839 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3840 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3841 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3842 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3843 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3844 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3846 // Get the WebView theme entry values string array.
3847 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3849 // Get a handle for the cookie manager.
3850 CookieManager cookieManager = CookieManager.getInstance();
3852 // Initialize the user agent array adapter and string array.
3853 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3854 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3856 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3857 // Get a cursor for the current host and move it to the first position.
3858 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3859 currentDomainSettingsCursor.moveToFirst();
3861 // Get the settings from the cursor.
3862 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3863 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3864 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.COOKIES)) == 1);
3865 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3866 // Form data can be removed once the minimum API >= 26.
3867 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3868 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3869 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3870 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3871 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3872 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3873 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3874 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3875 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3876 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3877 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3878 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3879 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3880 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3881 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3882 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3883 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3884 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WEBVIEW_THEME));
3885 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3886 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3887 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3888 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3889 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3890 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3891 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3892 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3893 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3894 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3895 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3897 // Get the pinned SSL date longs.
3898 long pinnedSslStartDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE));
3899 long pinnedSslEndDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE));
3901 // Define the pinned SSL date variables.
3902 Date pinnedSslStartDate;
3903 Date pinnedSslEndDate;
3905 // 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.
3906 if (pinnedSslStartDateLong == 0) {
3907 pinnedSslStartDate = null;
3909 pinnedSslStartDate = new Date(pinnedSslStartDateLong);
3912 // 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.
3913 if (pinnedSslEndDateLong == 0) {
3914 pinnedSslEndDate = null;
3916 pinnedSslEndDate = new Date(pinnedSslEndDateLong);
3919 // Close the current host domain settings cursor.
3920 currentDomainSettingsCursor.close();
3922 // If there is a pinned SSL certificate, store it in the WebView.
3923 if (pinnedSslCertificate) {
3924 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3925 pinnedSslStartDate, pinnedSslEndDate);
3928 // If there is a pinned IP address, store it in the WebView.
3929 if (pinnedIpAddresses) {
3930 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3933 // Apply the cookie domain settings.
3934 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3936 // Apply the form data setting if the API < 26.
3937 if (Build.VERSION.SDK_INT < 26) {
3938 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3941 // Apply the font size.
3942 try { // Try the specified font size to see if it is valid.
3943 if (fontSize == 0) { // Apply the default font size.
3944 // Try to set the font size from the value in the app settings.
3945 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3946 } else { // Apply the font size from domain settings.
3947 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3949 } catch (Exception exception) { // The specified font size is invalid
3950 // Set the font size to be 100%
3951 nestedScrollWebView.getSettings().setTextZoom(100);
3954 // Set the user agent.
3955 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3956 // Get the array position of the default user agent name.
3957 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3959 // Set the user agent according to the system default.
3960 switch (defaultUserAgentArrayPosition) {
3961 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3962 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3963 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3966 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3967 // Set the user agent to `""`, which uses the default value.
3968 nestedScrollWebView.getSettings().setUserAgentString("");
3971 case SETTINGS_CUSTOM_USER_AGENT:
3972 // Set the default custom user agent.
3973 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3977 // Get the user agent string from the user agent data array
3978 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3980 } else { // Set the user agent according to the stored name.
3981 // Get the array position of the user agent name.
3982 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3984 switch (userAgentArrayPosition) {
3985 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3986 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3989 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3990 // Set the user agent to `""`, which uses the default value.
3991 nestedScrollWebView.getSettings().setUserAgentString("");
3995 // Get the user agent string from the user agent data array.
3996 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4000 // Set swipe to refresh.
4001 switch (swipeToRefreshInt) {
4002 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4003 // Store the swipe to refresh status in the nested scroll WebView.
4004 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4006 // Update the swipe refresh layout.
4007 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4008 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4009 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4010 } else { // Swipe to refresh is disabled.
4011 // Disable the swipe refresh layout.
4012 swipeRefreshLayout.setEnabled(false);
4016 case DomainsDatabaseHelper.ENABLED:
4017 // Store the swipe to refresh status in the nested scroll WebView.
4018 nestedScrollWebView.setSwipeToRefresh(true);
4020 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4021 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4024 case DomainsDatabaseHelper.DISABLED:
4025 // Store the swipe to refresh status in the nested scroll WebView.
4026 nestedScrollWebView.setSwipeToRefresh(false);
4028 // Disable swipe to refresh.
4029 swipeRefreshLayout.setEnabled(false);
4032 // Check to see if WebView themes are supported.
4033 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4034 // Set the WebView theme.
4035 switch (webViewThemeInt) {
4036 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4037 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4038 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4039 // Turn off the WebView dark mode.
4040 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4041 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4042 // Turn on the WebView dark mode.
4043 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4044 } else { // The system default theme is selected.
4045 // Get the current system theme status.
4046 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4048 // Set the WebView theme according to the current system theme status.
4049 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4050 // Turn off the WebView dark mode.
4051 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4052 } else { // The system is in night mode.
4053 // Turn on the WebView dark mode.
4054 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4059 case DomainsDatabaseHelper.LIGHT_THEME:
4060 // Turn off the WebView dark mode.
4061 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4064 case DomainsDatabaseHelper.DARK_THEME:
4065 // Turn on the WebView dark mode.
4066 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4071 // Set the viewport.
4072 switch (wideViewportInt) {
4073 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4074 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4077 case DomainsDatabaseHelper.ENABLED:
4078 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4081 case DomainsDatabaseHelper.DISABLED:
4082 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4086 // Set the loading of webpage images.
4087 switch (displayWebpageImagesInt) {
4088 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4089 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4092 case DomainsDatabaseHelper.ENABLED:
4093 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4096 case DomainsDatabaseHelper.DISABLED:
4097 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4101 // Get the current theme status.
4102 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4104 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4105 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4106 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
4108 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
4110 } else { // The new URL does not have custom domain settings. Load the defaults.
4111 // Store the values from the shared preferences.
4112 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4113 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4114 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4115 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4116 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4117 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4118 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4119 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4120 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4121 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4122 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4124 // Apply the default cookie setting.
4125 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4127 // Apply the default font size setting.
4129 // Try to set the font size from the value in the app settings.
4130 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4131 } catch (Exception exception) {
4132 // If the app settings value is invalid, set the font size to 100%.
4133 nestedScrollWebView.getSettings().setTextZoom(100);
4136 // Apply the form data setting if the API < 26.
4137 if (Build.VERSION.SDK_INT < 26) {
4138 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4141 // Store the swipe to refresh status in the nested scroll WebView.
4142 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4144 // Update the swipe refresh layout.
4145 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4146 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4147 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4148 } else { // Swipe to refresh is disabled.
4149 // Disable the swipe refresh layout.
4150 swipeRefreshLayout.setEnabled(false);
4153 // Reset the pinned variables.
4154 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4156 // Get the array position of the user agent name.
4157 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4159 // Set the user agent.
4160 switch (userAgentArrayPosition) {
4161 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4162 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4163 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4166 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4167 // Set the user agent to `""`, which uses the default value.
4168 nestedScrollWebView.getSettings().setUserAgentString("");
4171 case SETTINGS_CUSTOM_USER_AGENT:
4172 // Set the default custom user agent.
4173 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4177 // Get the user agent string from the user agent data array
4178 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4181 // Apply the WebView theme if supported by the installed WebView.
4182 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4183 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4184 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4185 // Turn off the WebView dark mode.
4186 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4187 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4188 // Turn on the WebView dark mode.
4189 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4190 } else { // The system default theme is selected.
4191 // Get the current system theme status.
4192 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4194 // Set the WebView theme according to the current system theme status.
4195 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4196 // Turn off the WebView dark mode.
4197 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4198 } else { // The system is in night mode.
4199 // Turn on the WebView dark mode.
4200 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4205 // Set the viewport.
4206 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4208 // Set the loading of webpage images.
4209 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4211 // Set a transparent background on the URL relative layout.
4212 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4215 // Close the domains database helper.
4216 domainsDatabaseHelper.close();
4218 // Update the privacy icons.
4219 updatePrivacyIcons(true);
4222 // Reload the website if returning from the Domains activity.
4223 if (reloadWebsite) {
4224 nestedScrollWebView.reload();
4227 // 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.
4229 nestedScrollWebView.loadUrl(url, customHeaders);
4233 private void applyProxy(boolean reloadWebViews) {
4234 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4235 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4237 // Reset the waiting for proxy tracker.
4238 waitingForProxy = false;
4240 // Get the current theme status.
4241 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4243 // Update the user interface and reload the WebViews if requested.
4244 switch (proxyMode) {
4245 case ProxyHelper.NONE:
4246 // Initialize a color background typed value.
4247 TypedValue colorBackgroundTypedValue = new TypedValue();
4249 // Get the color background from the theme.
4250 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4252 // Get the color background int from the typed value.
4253 int colorBackgroundInt = colorBackgroundTypedValue.data;
4255 // Set the default app bar layout background.
4256 appBarLayout.setBackgroundColor(colorBackgroundInt);
4259 case ProxyHelper.TOR:
4260 // Set the app bar background to indicate proxying through Orbot is enabled.
4261 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4262 appBarLayout.setBackgroundResource(R.color.blue_50);
4264 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4267 // Check to see if Orbot is installed.
4269 // Get the package manager.
4270 PackageManager packageManager = getPackageManager();
4272 // 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.
4273 packageManager.getPackageInfo("org.torproject.android", 0);
4275 // Check to see if the proxy is ready.
4276 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4277 // Set the waiting for proxy status.
4278 waitingForProxy = true;
4280 // Show the waiting for proxy dialog if it isn't already displayed.
4281 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4282 // Get a handle for the waiting for proxy alert dialog.
4283 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4285 // Display the waiting for proxy alert dialog.
4286 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4289 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4290 // Show the Orbot not installed dialog if it is not already displayed.
4291 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4292 // Get a handle for the Orbot not installed alert dialog.
4293 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4295 // Display the Orbot not installed alert dialog.
4296 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4301 case ProxyHelper.I2P:
4302 // Set the app bar background to indicate proxying through Orbot is enabled.
4303 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4304 appBarLayout.setBackgroundResource(R.color.blue_50);
4306 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4309 // Check to see if I2P is installed.
4311 // Get the package manager.
4312 PackageManager packageManager = getPackageManager();
4314 // 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.
4315 packageManager.getPackageInfo("net.i2p.android.router", 0);
4316 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4317 // Sow the I2P not installed dialog if it is not already displayed.
4318 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4319 // Get a handle for the waiting for proxy alert dialog.
4320 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4322 // Display the I2P not installed alert dialog.
4323 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4328 case ProxyHelper.CUSTOM:
4329 // Set the app bar background to indicate proxying through Orbot is enabled.
4330 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4331 appBarLayout.setBackgroundResource(R.color.blue_50);
4333 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4338 // Reload the WebViews if requested and not waiting for the proxy.
4339 if (reloadWebViews && !waitingForProxy) {
4340 // Reload the WebViews.
4341 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4342 // Get the WebView tab fragment.
4343 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4345 // Get the fragment view.
4346 View fragmentView = webViewTabFragment.getView();
4348 // Only reload the WebViews if they exist.
4349 if (fragmentView != null) {
4350 // Get the nested scroll WebView from the tab fragment.
4351 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4353 // Reload the WebView.
4354 nestedScrollWebView.reload();
4360 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4361 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4362 if ((optionsMenu != null) && (currentWebView != null)) {
4363 // Update the privacy icon.
4364 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4365 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4366 } else if (currentWebView.getAcceptCookies()) { // JavaScript is disabled but cookies are enabled.
4367 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4368 } else { // All the dangerous features are disabled.
4369 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4372 // Get the current theme status.
4373 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4375 // Update the cookies icon.
4376 if (currentWebView.getAcceptCookies()) { // Cookies are enabled.
4377 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4378 } else { // Cookies are disabled.
4379 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4380 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4382 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4386 // Update the refresh icon.
4387 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4388 // Set the icon according to the theme.
4389 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4390 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4392 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4394 } else { // The stop icon is displayed.
4395 // Set the icon according to the theme.
4396 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4397 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
4399 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
4403 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4404 if (runInvalidateOptionsMenu) {
4405 invalidateOptionsMenu();
4410 private void highlightUrlText() {
4411 // Only highlight the URL text if the box is not currently selected.
4412 if (!urlEditText.hasFocus()) {
4413 // Get the URL string.
4414 String urlString = urlEditText.getText().toString();
4416 // Highlight the URL according to the protocol.
4417 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4418 // De-emphasize everything before the file name.
4419 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4420 } else { // This is a web URL.
4421 // Get the index of the `/` immediately after the domain name.
4422 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4424 // Create a base URL string.
4427 // Get the base URL.
4428 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4429 // Get the base URL.
4430 baseUrl = urlString.substring(0, endOfDomainName);
4431 } else { // There are no characters after the base URL.
4432 // Set the base URL to be the entire URL string.
4433 baseUrl = urlString;
4436 // Get the index of the last `.` in the domain.
4437 int lastDotIndex = baseUrl.lastIndexOf(".");
4439 // Get the index of the penultimate `.` in the domain.
4440 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4442 // Markup the beginning of the URL.
4443 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4444 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4446 // De-emphasize subdomains.
4447 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4448 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4450 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4451 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4452 // De-emphasize the protocol and the additional subdomains.
4453 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4454 } else { // There is only one subdomain in the domain name.
4455 // De-emphasize only the protocol.
4456 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4460 // De-emphasize the text after the domain name.
4461 if (endOfDomainName > 0) {
4462 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4468 private void loadBookmarksFolder() {
4469 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4470 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4472 // Populate the bookmarks cursor adapter.
4473 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4475 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4476 // Inflate the individual item layout.
4477 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4481 public void bindView(View view, Context context, Cursor cursor) {
4482 // Get handles for the views.
4483 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4484 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4486 // Get the favorite icon byte array from the cursor.
4487 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4489 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4490 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4492 // Display the bitmap in `bookmarkFavoriteIcon`.
4493 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4495 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4496 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4497 bookmarkNameTextView.setText(bookmarkNameString);
4499 // Make the font bold for folders.
4500 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4501 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4502 } else { // Reset the font to default for normal bookmarks.
4503 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4508 // Get a handle for the bookmarks list view.
4509 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4511 // Populate the list view with the adapter.
4512 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4514 // Get a handle for the bookmarks title text view.
4515 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4517 // Set the bookmarks drawer title.
4518 if (currentBookmarksFolder.isEmpty()) {
4519 bookmarksTitleTextView.setText(R.string.bookmarks);
4521 bookmarksTitleTextView.setText(currentBookmarksFolder);
4525 private void openWithApp(String url) {
4526 // Create an open with app intent with `ACTION_VIEW`.
4527 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4529 // Set the URI but not the MIME type. This should open all available apps.
4530 openWithAppIntent.setData(Uri.parse(url));
4532 // Flag the intent to open in a new task.
4533 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4537 // Show the chooser.
4538 startActivity(openWithAppIntent);
4539 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4540 // Show a snackbar with the error.
4541 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4545 private void openWithBrowser(String url) {
4546 // Create an open with browser intent with `ACTION_VIEW`.
4547 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4549 // Set the URI and the MIME type. `"text/html"` should load browser options.
4550 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4552 // Flag the intent to open in a new task.
4553 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4557 // Show the chooser.
4558 startActivity(openWithBrowserIntent);
4559 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4560 // Show a snackbar with the error.
4561 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4565 private String sanitizeUrl(String url) {
4566 // Sanitize Google Analytics.
4567 if (sanitizeGoogleAnalytics) {
4569 if (url.contains("?utm_")) {
4570 url = url.substring(0, url.indexOf("?utm_"));
4574 if (url.contains("&utm_")) {
4575 url = url.substring(0, url.indexOf("&utm_"));
4579 // Sanitize Facebook Click IDs.
4580 if (sanitizeFacebookClickIds) {
4581 // Remove `?fbclid=`.
4582 if (url.contains("?fbclid=")) {
4583 url = url.substring(0, url.indexOf("?fbclid="));
4586 // Remove `&fbclid=`.
4587 if (url.contains("&fbclid=")) {
4588 url = url.substring(0, url.indexOf("&fbclid="));
4591 // Remove `?fbadid=`.
4592 if (url.contains("?fbadid=")) {
4593 url = url.substring(0, url.indexOf("?fbadid="));
4596 // Remove `&fbadid=`.
4597 if (url.contains("&fbadid=")) {
4598 url = url.substring(0, url.indexOf("&fbadid="));
4602 // Sanitize Twitter AMP redirects.
4603 if (sanitizeTwitterAmpRedirects) {
4605 if (url.contains("?amp=1")) {
4606 url = url.substring(0, url.indexOf("?amp=1"));
4610 // Return the sanitized URL.
4614 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4615 // Store the blocklists.
4616 easyList = combinedBlocklists.get(0);
4617 easyPrivacy = combinedBlocklists.get(1);
4618 fanboysAnnoyanceList = combinedBlocklists.get(2);
4619 fanboysSocialList = combinedBlocklists.get(3);
4620 ultraList = combinedBlocklists.get(4);
4621 ultraPrivacy = combinedBlocklists.get(5);
4623 // Check to see if the activity has been restarted with a saved state.
4624 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4625 // Add the first tab.
4626 addNewTab("", true);
4627 } else { // The activity has been restarted.
4628 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4629 for (int i = 0; i < savedStateArrayList.size(); i++) {
4631 tabLayout.addTab(tabLayout.newTab());
4634 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4636 // Remove the lint warning below that the current tab might be null.
4637 assert newTab != null;
4639 // Set a custom view on the new tab.
4640 newTab.setCustomView(R.layout.tab_custom_view);
4642 // Add the new page.
4643 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4646 // Reset the saved state variables.
4647 savedStateArrayList = null;
4648 savedNestedScrollWebViewStateArrayList = null;
4650 // Restore the selected tab position.
4651 if (savedTabPosition == 0) { // The first tab is selected.
4652 // Set the first page as the current WebView.
4653 setCurrentWebView(0);
4654 } else { // the first tab is not selected.
4655 // Move to the selected tab.
4656 webViewPager.setCurrentItem(savedTabPosition);
4659 // Get the intent that started the app.
4660 Intent intent = getIntent();
4662 // Reset the intent. This prevents a duplicate tab from being created on restart.
4663 setIntent(new Intent());
4665 // Get the information from the intent.
4666 String intentAction = intent.getAction();
4667 Uri intentUriData = intent.getData();
4668 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4670 // Determine if this is a web search.
4671 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4673 // 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.
4674 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4675 // Get the shared preferences.
4676 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4678 // Create a URL string.
4681 // If the intent action is a web search, perform the search.
4682 if (isWebSearch) { // The intent is a web search.
4683 // Create an encoded URL string.
4684 String encodedUrlString;
4686 // Sanitize the search input and convert it to a search.
4688 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4689 } catch (UnsupportedEncodingException exception) {
4690 encodedUrlString = "";
4693 // Add the base search URL.
4694 url = searchURL + encodedUrlString;
4695 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4696 // Set the intent data as the URL.
4697 url = intentUriData.toString();
4698 } else { // The intent contains a string, which might be a URL.
4699 // Set the intent string as the URL.
4700 url = intentStringExtra;
4703 // Add a new tab if specified in the preferences.
4704 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4705 // Set the loading new intent flag.
4706 loadingNewIntent = true;
4709 addNewTab(url, true);
4710 } else { // Load the URL in the current tab.
4712 loadUrl(currentWebView, url);
4718 public void addTab(View view) {
4719 // Add a new tab with a blank URL.
4720 addNewTab("", true);
4723 private void addNewTab(String url, boolean moveToTab) {
4724 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4725 urlEditText.clearFocus();
4727 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4728 int newTabNumber = tabLayout.getTabCount();
4731 tabLayout.addTab(tabLayout.newTab());
4734 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4736 // Remove the lint warning below that the current tab might be null.
4737 assert newTab != null;
4739 // Set a custom view on the new tab.
4740 newTab.setCustomView(R.layout.tab_custom_view);
4742 // Add the new WebView page.
4743 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4746 public void closeTab(View view) {
4747 // Run the command according to the number of tabs.
4748 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4749 // Close the current tab.
4751 } else { // There is only one tab open.
4756 private void closeCurrentTab() {
4757 // Get the current tab number.
4758 int currentTabNumber = tabLayout.getSelectedTabPosition();
4760 // Delete the current tab.
4761 tabLayout.removeTabAt(currentTabNumber);
4763 // Delete the current page. If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
4764 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4765 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4766 setCurrentWebView(currentTabNumber);
4770 private void exitFullScreenVideo() {
4771 // Re-enable the screen timeout.
4772 fullScreenVideoFrameLayout.setKeepScreenOn(false);
4774 // Unset the full screen video flag.
4775 displayingFullScreenVideo = false;
4777 // Remove all the views from the full screen video frame layout.
4778 fullScreenVideoFrameLayout.removeAllViews();
4780 // Hide the full screen video frame layout.
4781 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4783 // Enable the sliding drawers.
4784 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4786 // Show the main content relative layout.
4787 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4789 // Apply the appropriate full screen mode flags.
4790 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4791 // Hide the app bar if specified.
4793 // Hide the tab linear layout.
4794 tabsLinearLayout.setVisibility(View.GONE);
4796 // Hide the action bar.
4800 // Hide the banner ad in the free flavor.
4801 if (BuildConfig.FLAVOR.contentEquals("free")) {
4802 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
4803 View adView = findViewById(R.id.adview);
4805 // Hide the banner ad.
4806 AdHelper.hideAd(adView);
4809 /* Hide the system bars.
4810 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4811 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4812 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4813 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4815 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4816 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4817 } else { // Switch to normal viewing mode.
4818 // Remove the `SYSTEM_UI` flags from the root frame layout.
4819 rootFrameLayout.setSystemUiVisibility(0);
4822 // Reload the ad for the free flavor if not in full screen mode.
4823 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4824 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
4825 View adView = findViewById(R.id.adview);
4828 AdHelper.loadAd(adView, this, this, getString(R.string.ad_unit_id));
4832 private void clearAndExit() {
4833 // Get a handle for the shared preferences.
4834 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4836 // Close the bookmarks cursor and database.
4837 bookmarksCursor.close();
4838 bookmarksDatabaseHelper.close();
4840 // Get the status of the clear everything preference.
4841 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4843 // Get a handle for the runtime.
4844 Runtime runtime = Runtime.getRuntime();
4846 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4847 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4848 String privateDataDirectoryString = getApplicationInfo().dataDir;
4851 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4852 // The command to remove cookies changed slightly in API 21.
4853 if (Build.VERSION.SDK_INT >= 21) {
4854 CookieManager.getInstance().removeAllCookies(null);
4856 CookieManager.getInstance().removeAllCookie();
4859 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4861 // Two commands must be used because `Runtime.exec()` does not like `*`.
4862 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4863 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4865 // Wait until the processes have finished.
4866 deleteCookiesProcess.waitFor();
4867 deleteCookiesJournalProcess.waitFor();
4868 } catch (Exception exception) {
4869 // Do nothing if an error is thrown.
4873 // Clear DOM storage.
4874 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4875 // Ask `WebStorage` to clear the DOM storage.
4876 WebStorage webStorage = WebStorage.getInstance();
4877 webStorage.deleteAllData();
4879 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4881 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4882 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4884 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4885 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4886 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4887 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4888 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4890 // Wait until the processes have finished.
4891 deleteLocalStorageProcess.waitFor();
4892 deleteIndexProcess.waitFor();
4893 deleteQuotaManagerProcess.waitFor();
4894 deleteQuotaManagerJournalProcess.waitFor();
4895 deleteDatabaseProcess.waitFor();
4896 } catch (Exception exception) {
4897 // Do nothing if an error is thrown.
4901 // Clear form data if the API < 26.
4902 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4903 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4904 webViewDatabase.clearFormData();
4906 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4908 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4909 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4910 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4912 // Wait until the processes have finished.
4913 deleteWebDataProcess.waitFor();
4914 deleteWebDataJournalProcess.waitFor();
4915 } catch (Exception exception) {
4916 // Do nothing if an error is thrown.
4920 // Clear the logcat.
4921 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4923 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
4924 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4926 // Wait for the process to finish.
4928 } catch (IOException|InterruptedException exception) {
4934 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4935 // Clear the cache from each WebView.
4936 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4937 // Get the WebView tab fragment.
4938 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4940 // Get the WebView fragment view.
4941 View webViewFragmentView = webViewTabFragment.getView();
4943 // Only clear the cache if the WebView exists.
4944 if (webViewFragmentView != null) {
4945 // Get the nested scroll WebView from the tab fragment.
4946 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4948 // Clear the cache for this WebView.
4949 nestedScrollWebView.clearCache(true);
4953 // Manually delete the cache directories.
4955 // Delete the main cache directory.
4956 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4958 // Delete the secondary `Service Worker` cache directory.
4959 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4960 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4962 // Wait until the processes have finished.
4963 deleteCacheProcess.waitFor();
4964 deleteServiceWorkerProcess.waitFor();
4965 } catch (Exception exception) {
4966 // Do nothing if an error is thrown.
4970 // Wipe out each WebView.
4971 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4972 // Get the WebView tab fragment.
4973 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4975 // Get the WebView frame layout.
4976 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4978 // Only wipe out the WebView if it exists.
4979 if (webViewFrameLayout != null) {
4980 // Get the nested scroll WebView from the tab fragment.
4981 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4983 // Clear SSL certificate preferences for this WebView.
4984 nestedScrollWebView.clearSslPreferences();
4986 // Clear the back/forward history for this WebView.
4987 nestedScrollWebView.clearHistory();
4989 // Remove all the views from the frame layout.
4990 webViewFrameLayout.removeAllViews();
4992 // Destroy the internal state of the WebView.
4993 nestedScrollWebView.destroy();
4997 // Clear the custom headers.
4998 customHeaders.clear();
5000 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
5001 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
5002 if (clearEverything) {
5004 // Delete the folder.
5005 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
5007 // Wait until the process has finished.
5008 deleteAppWebviewProcess.waitFor();
5009 } catch (Exception exception) {
5010 // Do nothing if an error is thrown.
5014 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
5015 if (Build.VERSION.SDK_INT >= 21) {
5016 finishAndRemoveTask();
5021 // Remove the terminated program from RAM. The status code is `0`.
5025 public void bookmarksBack(View view) {
5026 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
5027 // close the bookmarks drawer.
5028 drawerLayout.closeDrawer(GravityCompat.END);
5029 } else { // A subfolder is displayed.
5030 // Place the former parent folder in `currentFolder`.
5031 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
5033 // Load the new folder.
5034 loadBookmarksFolder();
5038 private void setCurrentWebView(int pageNumber) {
5039 // Stop the swipe to refresh indicator if it is running
5040 swipeRefreshLayout.setRefreshing(false);
5042 // Get the WebView tab fragment.
5043 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
5045 // Get the fragment view.
5046 View webViewFragmentView = webViewTabFragment.getView();
5048 // Set the current WebView if the fragment view is not null.
5049 if (webViewFragmentView != null) { // The fragment has been populated.
5050 // Store the current WebView.
5051 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
5053 // Update the status of swipe to refresh.
5054 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
5055 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5056 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
5057 } else { // Swipe to refresh is disabled.
5058 // Disable the swipe refresh layout.
5059 swipeRefreshLayout.setEnabled(false);
5062 // Get a handle for the cookie manager.
5063 CookieManager cookieManager = CookieManager.getInstance();
5065 // Set the cookie status.
5066 cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
5068 // Update the privacy icons. `true` redraws the icons in the app bar.
5069 updatePrivacyIcons(true);
5071 // Get a handle for the input method manager.
5072 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5074 // Remove the lint warning below that the input method manager might be null.
5075 assert inputMethodManager != null;
5077 // Get the current URL.
5078 String url = currentWebView.getUrl();
5080 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5081 if (!loadingNewIntent) { // A new intent is not being loaded.
5082 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5083 // Display the hint in the URL edit text.
5084 urlEditText.setText("");
5086 // Request focus for the URL text box.
5087 urlEditText.requestFocus();
5089 // Display the keyboard.
5090 inputMethodManager.showSoftInput(urlEditText, 0);
5091 } else { // The WebView has a loaded URL.
5092 // Clear the focus from the URL text box.
5093 urlEditText.clearFocus();
5095 // Hide the soft keyboard.
5096 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5098 // Display the current URL in the URL text box.
5099 urlEditText.setText(url);
5101 // Highlight the URL text.
5104 } else { // A new intent is being loaded.
5105 // Reset the loading new intent tracker.
5106 loadingNewIntent = false;
5109 // Set the background to indicate the domain settings status.
5110 if (currentWebView.getDomainSettingsApplied()) {
5111 // Get the current theme status.
5112 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5114 // Set a green background on the URL relative layout to indicate that custom domain settings are being used.
5115 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
5116 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
5118 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
5121 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5123 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5124 // Create a handler to set the current WebView.
5125 Handler setCurrentWebViewHandler = new Handler();
5127 // Create a runnable to set the current WebView.
5128 Runnable setCurrentWebWebRunnable = () -> {
5129 // Set the current WebView.
5130 setCurrentWebView(pageNumber);
5133 // Try setting the current WebView again after 100 milliseconds.
5134 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5139 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5140 // Get a handle for the shared preferences.
5141 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5143 // Get the WebView theme.
5144 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5146 // Get the WebView theme entry values string array.
5147 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5149 // Apply the WebView theme if supported by the installed WebView.
5150 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5151 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5152 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5153 // Turn off the WebView dark mode.
5154 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5156 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5157 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5158 nestedScrollWebView.setVisibility(View.VISIBLE);
5159 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5160 // Turn on the WebView dark mode.
5161 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5162 } else { // The system default theme is selected.
5163 // Get the current system theme status.
5164 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5166 // Set the WebView theme according to the current system theme status.
5167 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5168 // Turn off the WebView dark mode.
5169 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5171 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5172 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5173 nestedScrollWebView.setVisibility(View.VISIBLE);
5174 } else { // The system is in night mode.
5175 // Turn on the WebView dark mode.
5176 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5181 // Get a handle for the activity
5182 Activity activity = this;
5184 // Get a handle for the input method manager.
5185 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5187 // Instantiate the blocklist helper.
5188 BlocklistHelper blocklistHelper = new BlocklistHelper();
5190 // Remove the lint warning below that the input method manager might be null.
5191 assert inputMethodManager != null;
5193 // Initialize the favorite icon.
5194 nestedScrollWebView.initializeFavoriteIcon();
5196 // Set the app bar scrolling.
5197 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5199 // Allow pinch to zoom.
5200 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5202 // Hide zoom controls.
5203 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5205 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5206 if (Build.VERSION.SDK_INT >= 21) {
5207 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5210 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5211 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5213 // Explicitly disable geolocation.
5214 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5216 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5217 nestedScrollWebView.getSettings().setAllowFileAccess(true);
5219 // Create a double-tap gesture detector to toggle full-screen mode.
5220 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5221 // Override `onDoubleTap()`. All other events are handled using the default settings.
5223 public boolean onDoubleTap(MotionEvent event) {
5224 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5225 // Toggle the full screen browsing mode tracker.
5226 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5228 // Toggle the full screen browsing mode.
5229 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5230 // Hide the app bar if specified.
5232 // Close the find on page bar if it is visible.
5233 closeFindOnPage(null);
5235 // Hide the tab linear layout.
5236 tabsLinearLayout.setVisibility(View.GONE);
5238 // Hide the action bar.
5241 // Check to see if the app bar is normally scrolled.
5242 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5243 // Get the swipe refresh layout parameters.
5244 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5246 // Remove the off-screen scrolling layout.
5247 swipeRefreshLayoutParams.setBehavior(null);
5248 } else { // The app bar is not scrolled when it is displayed.
5249 // Remove the padding from the top of the swipe refresh layout.
5250 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5252 // The swipe refresh circle must be moved above the now removed status bar location.
5253 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5257 // Hide the banner ad in the free flavor.
5258 if (BuildConfig.FLAVOR.contentEquals("free")) {
5259 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5260 View adView = findViewById(R.id.adview);
5262 // Hide the banner ad.
5263 AdHelper.hideAd(adView);
5266 /* Hide the system bars.
5267 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5268 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5269 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5270 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5272 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5273 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5274 } else { // Switch to normal viewing mode.
5275 // Show the app bar if it was hidden.
5277 // Show the tab linear layout.
5278 tabsLinearLayout.setVisibility(View.VISIBLE);
5280 // Show the action bar.
5283 // Check to see if the app bar is normally scrolled.
5284 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5285 // Get the swipe refresh layout parameters.
5286 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5288 // Add the off-screen scrolling layout.
5289 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5290 } else { // The app bar is not scrolled when it is displayed.
5291 // The swipe refresh layout must be manually moved below the app bar layout.
5292 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5294 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5295 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5299 // Show the banner ad in the free flavor.
5300 if (BuildConfig.FLAVOR.contentEquals("free")) {
5301 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5302 View adView = findViewById(R.id.adview);
5304 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5305 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5308 // Remove the `SYSTEM_UI` flags from the root frame layout.
5309 rootFrameLayout.setSystemUiVisibility(0);
5312 // Consume the double-tap.
5314 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5320 // Pass all touch events on the WebView through the double-tap gesture detector.
5321 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5322 // Call `performClick()` on the view, which is required for accessibility.
5323 view.performClick();
5325 // Send the event to the gesture detector.
5326 return doubleTapGestureDetector.onTouchEvent(event);
5329 // Register the WebView for a context menu. This is used to see link targets and download images.
5330 registerForContextMenu(nestedScrollWebView);
5332 // Allow the downloading of files.
5333 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5334 // Check the download preference.
5335 if (downloadWithExternalApp) { // Download with an external app.
5336 downloadUrlWithExternalApp(downloadUrl);
5337 } else { // Handle the download inside of Privacy Browser.
5338 // Define a formatted file size string.
5339 String formattedFileSizeString;
5341 // Process the content length if it contains data.
5342 if (contentLength > 0) { // The content length is greater than 0.
5343 // Format the content length as a string.
5344 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5345 } else { // The content length is not greater than 0.
5346 // Set the formatted file size string to be `unknown size`.
5347 formattedFileSizeString = getString(R.string.unknown_size);
5350 // Get the file name from the content disposition.
5351 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5353 // Prevent the dialog from displaying if the app window is not visible.
5354 // The download listener continues to function even when the WebView is paused. Attempting to display a dialog in that state leads to a crash.
5355 while (!activity.getWindow().isActive()) {
5357 // The window is not active. Wait 1 second.
5359 } catch (InterruptedException e) {
5364 // Instantiate the save dialog.
5365 DialogFragment saveDialogFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_URL, downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5366 nestedScrollWebView.getAcceptCookies());
5368 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5369 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5373 // Update the find on page count.
5374 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5375 // Get a handle for `findOnPageCountTextView`.
5376 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5379 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5380 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5381 // Set `findOnPageCountTextView` to `0/0`.
5382 findOnPageCountTextView.setText(R.string.zero_of_zero);
5383 } else if (isDoneCounting) { // There are matches.
5384 // `activeMatchOrdinal` is zero-based.
5385 int activeMatch = activeMatchOrdinal + 1;
5387 // Build the match string.
5388 String matchString = activeMatch + "/" + numberOfMatches;
5390 // Set `findOnPageCountTextView`.
5391 findOnPageCountTextView.setText(matchString);
5396 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5397 // 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.
5398 if (Build.VERSION.SDK_INT >= 23) {
5399 nestedScrollWebView.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
5400 if (nestedScrollWebView.getSwipeToRefresh()) {
5401 // Only enable swipe to refresh if the WebView is scrolled to the top.
5402 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5404 // Disable swipe to refresh.
5405 swipeRefreshLayout.setEnabled(false);
5408 // Reinforce the system UI visibility flags if in full screen browsing mode.
5409 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5410 if (inFullScreenBrowsingMode) {
5411 /* Hide the system bars.
5412 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5413 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5414 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5415 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5417 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5418 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5422 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5423 if (nestedScrollWebView.getSwipeToRefresh()) {
5424 // Only enable swipe to refresh if the WebView is scrolled to the top.
5425 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5427 // Disable swipe to refresh.
5428 swipeRefreshLayout.setEnabled(false);
5432 // Reinforce the system UI visibility flags if in full screen browsing mode.
5433 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5434 if (inFullScreenBrowsingMode) {
5435 /* Hide the system bars.
5436 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5437 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5438 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5439 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5441 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5442 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5447 // Set the web chrome client.
5448 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5449 // Update the progress bar when a page is loading.
5451 public void onProgressChanged(WebView view, int progress) {
5452 // Update the progress bar.
5453 progressBar.setProgress(progress);
5455 // Set the visibility of the progress bar.
5456 if (progress < 100) {
5457 // Show the progress bar.
5458 progressBar.setVisibility(View.VISIBLE);
5460 // Hide the progress bar.
5461 progressBar.setVisibility(View.GONE);
5463 //Stop the swipe to refresh indicator if it is running
5464 swipeRefreshLayout.setRefreshing(false);
5466 // 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.
5467 nestedScrollWebView.setVisibility(View.VISIBLE);
5471 // Set the favorite icon when it changes.
5473 public void onReceivedIcon(WebView view, Bitmap icon) {
5474 // Only update the favorite icon if the website has finished loading.
5475 if (progressBar.getVisibility() == View.GONE) {
5476 // Store the new favorite icon.
5477 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5479 // Get the current page position.
5480 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5482 // Get the current tab.
5483 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5485 // Check to see if the tab has been populated.
5487 // Get the custom view from the tab.
5488 View tabView = tab.getCustomView();
5490 // Check to see if the custom tab view has been populated.
5491 if (tabView != null) {
5492 // Get the favorite icon image view from the tab.
5493 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5495 // Display the favorite icon in the tab.
5496 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5502 // Save a copy of the title when it changes.
5504 public void onReceivedTitle(WebView view, String title) {
5505 // Get the current page position.
5506 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5508 // Get the current tab.
5509 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5511 // Only populate the title text view if the tab has been fully created.
5513 // Get the custom view from the tab.
5514 View tabView = tab.getCustomView();
5516 // Only populate the title text view if the tab view has been fully populated.
5517 if (tabView != null) {
5518 // Get the title text view from the tab.
5519 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5521 // Set the title according to the URL.
5522 if (title.equals("about:blank")) {
5523 // Set the title to indicate a new tab.
5524 tabTitleTextView.setText(R.string.new_tab);
5526 // Set the title as the tab text.
5527 tabTitleTextView.setText(title);
5533 // Enter full screen video.
5535 public void onShowCustomView(View video, CustomViewCallback callback) {
5536 // Set the full screen video flag.
5537 displayingFullScreenVideo = true;
5539 // Pause the ad if this is the free flavor.
5540 if (BuildConfig.FLAVOR.contentEquals("free")) {
5541 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5542 View adView = findViewById(R.id.adview);
5544 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5545 AdHelper.pauseAd(adView);
5548 // Hide the keyboard.
5549 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5551 // Hide the main content relative layout.
5552 mainContentRelativeLayout.setVisibility(View.GONE);
5554 /* Hide the system bars.
5555 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5556 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5557 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5558 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5560 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5561 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5563 // Disable the sliding drawers.
5564 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5566 // Add the video view to the full screen video frame layout.
5567 fullScreenVideoFrameLayout.addView(video);
5569 // Show the full screen video frame layout.
5570 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5572 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5573 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5576 // Exit full screen video.
5578 public void onHideCustomView() {
5579 // Exit the full screen video.
5580 exitFullScreenVideo();
5585 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5586 // Show the file chooser if the device is running API >= 21.
5587 if (Build.VERSION.SDK_INT >= 21) {
5588 // Store the file path callback.
5589 fileChooserCallback = filePathCallback;
5591 // Create an intent to open a chooser based on the file chooser parameters.
5592 Intent fileChooserIntent = fileChooserParams.createIntent();
5594 // Get a handle for the package manager.
5595 PackageManager packageManager = getPackageManager();
5597 // Check to see if the file chooser intent resolves to an installed package.
5598 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5599 // Start the file chooser intent.
5600 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5601 } else { // The file chooser intent will cause a crash.
5602 // Create a generic intent to open a chooser.
5603 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5605 // Request an openable file.
5606 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5608 // Set the file type to everything.
5609 genericFileChooserIntent.setType("*/*");
5611 // Start the generic file chooser intent.
5612 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5619 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5620 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5621 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5623 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5624 // Sanitize the url.
5625 url = sanitizeUrl(url);
5627 // Handle the URL according to the type.
5628 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5629 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5630 loadUrl(nestedScrollWebView, url);
5632 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5633 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5635 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5636 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5637 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5639 // Parse the url and set it as the data for the intent.
5640 emailIntent.setData(Uri.parse(url));
5642 // Open the email program in a new task instead of as part of Privacy Browser.
5643 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5647 startActivity(emailIntent);
5648 } catch (ActivityNotFoundException exception) {
5649 // Display a snackbar.
5650 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5654 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5656 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5657 // Open the dialer and load the phone number, but wait for the user to place the call.
5658 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5660 // Add the phone number to the intent.
5661 dialIntent.setData(Uri.parse(url));
5663 // Open the dialer in a new task instead of as part of Privacy Browser.
5664 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5668 startActivity(dialIntent);
5669 } catch (ActivityNotFoundException exception) {
5670 // Display a snackbar.
5671 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5674 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5676 } else { // Load a system chooser to select an app that can handle the URL.
5677 // Open an app that can handle the URL.
5678 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5680 // Add the URL to the intent.
5681 genericIntent.setData(Uri.parse(url));
5683 // List all apps that can handle the URL instead of just opening the first one.
5684 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5686 // Open the app in a new task instead of as part of Privacy Browser.
5687 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5689 // Start the app or display a snackbar if no app is available to handle the URL.
5691 startActivity(genericIntent);
5692 } catch (ActivityNotFoundException exception) {
5693 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5696 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5701 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5703 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5704 // Check to see if the resource request is for the main URL.
5705 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5706 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5710 // 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.
5711 while (ultraPrivacy == null) {
5712 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5713 synchronized (this) {
5715 // Check to see if the blocklists have been populated after 100 ms.
5717 } catch (InterruptedException exception) {
5723 // Sanitize the URL.
5724 url = sanitizeUrl(url);
5726 // Create an empty web resource response to be used if the resource request is blocked.
5727 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5729 // Reset the whitelist results tracker.
5730 String[] whitelistResultStringArray = null;
5732 // Initialize the third party request tracker.
5733 boolean isThirdPartyRequest = false;
5735 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5736 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5738 // Store a copy of the current domain for use in later requests.
5739 String currentDomain = currentBaseDomain;
5741 // Nobody is happy when comparing null strings.
5742 if ((currentBaseDomain != null) && (url != null)) {
5743 // Convert the request URL to a URI.
5744 Uri requestUri = Uri.parse(url);
5746 // Get the request host name.
5747 String requestBaseDomain = requestUri.getHost();
5749 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5750 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5751 // Determine the current base domain.
5752 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5753 // Remove the first subdomain.
5754 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5757 // Determine the request base domain.
5758 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5759 // Remove the first subdomain.
5760 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5763 // Update the third party request tracker.
5764 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5768 // Get the current WebView page position.
5769 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5771 // Determine if the WebView is currently displayed.
5772 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5774 // Block third-party requests if enabled.
5775 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5776 // Add the result to the resource requests.
5777 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5779 // Increment the blocked requests counters.
5780 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5781 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5783 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5784 if (webViewDisplayed) {
5785 // Updating the UI must be run from the UI thread.
5786 activity.runOnUiThread(() -> {
5787 // Update the menu item titles.
5788 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5790 // Update the options menu if it has been populated.
5791 if (optionsMenu != null) {
5792 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5793 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5794 getString(R.string.block_all_third_party_requests));
5799 // Return an empty web resource response.
5800 return emptyWebResourceResponse;
5803 // Check UltraList if it is enabled.
5804 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5805 // Check the URL against UltraList.
5806 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5808 // Process the UltraList results.
5809 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraList's blacklist.
5810 // Add the result to the resource requests.
5811 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5813 // Increment the blocked requests counters.
5814 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5815 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5817 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5818 if (webViewDisplayed) {
5819 // Updating the UI must be run from the UI thread.
5820 activity.runOnUiThread(() -> {
5821 // Update the menu item titles.
5822 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5824 // Update the options menu if it has been populated.
5825 if (optionsMenu != null) {
5826 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5827 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5832 // The resource request was blocked. Return an empty web resource response.
5833 return emptyWebResourceResponse;
5834 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5835 // Add a whitelist entry to the resource requests array.
5836 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5838 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5843 // Check UltraPrivacy if it is enabled.
5844 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5845 // Check the URL against UltraPrivacy.
5846 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5848 // Process the UltraPrivacy results.
5849 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5850 // Add the result to the resource requests.
5851 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5852 ultraPrivacyResults[5]});
5854 // Increment the blocked requests counters.
5855 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5856 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5858 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5859 if (webViewDisplayed) {
5860 // Updating the UI must be run from the UI thread.
5861 activity.runOnUiThread(() -> {
5862 // Update the menu item titles.
5863 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5865 // Update the options menu if it has been populated.
5866 if (optionsMenu != null) {
5867 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5868 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5873 // The resource request was blocked. Return an empty web resource response.
5874 return emptyWebResourceResponse;
5875 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5876 // Add a whitelist entry to the resource requests array.
5877 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5878 ultraPrivacyResults[5]});
5880 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5885 // Check EasyList if it is enabled.
5886 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
5887 // Check the URL against EasyList.
5888 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5890 // Process the EasyList results.
5891 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5892 // Add the result to the resource requests.
5893 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5895 // Increment the blocked requests counters.
5896 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5897 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5899 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5900 if (webViewDisplayed) {
5901 // Updating the UI must be run from the UI thread.
5902 activity.runOnUiThread(() -> {
5903 // Update the menu item titles.
5904 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5906 // Update the options menu if it has been populated.
5907 if (optionsMenu != null) {
5908 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5909 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5914 // The resource request was blocked. Return an empty web resource response.
5915 return emptyWebResourceResponse;
5916 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5917 // Update the whitelist result string array tracker.
5918 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5922 // Check EasyPrivacy if it is enabled.
5923 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
5924 // Check the URL against EasyPrivacy.
5925 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5927 // Process the EasyPrivacy results.
5928 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5929 // Add the result to the resource requests.
5930 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5931 easyPrivacyResults[5]});
5933 // Increment the blocked requests counters.
5934 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5935 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5937 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5938 if (webViewDisplayed) {
5939 // Updating the UI must be run from the UI thread.
5940 activity.runOnUiThread(() -> {
5941 // Update the menu item titles.
5942 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5944 // Update the options menu if it has been populated.
5945 if (optionsMenu != null) {
5946 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5947 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5952 // The resource request was blocked. Return an empty web resource response.
5953 return emptyWebResourceResponse;
5954 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5955 // Update the whitelist result string array tracker.
5956 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5960 // Check Fanboy’s Annoyance List if it is enabled.
5961 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5962 // Check the URL against Fanboy's Annoyance List.
5963 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5965 // Process the Fanboy's Annoyance List results.
5966 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5967 // Add the result to the resource requests.
5968 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5969 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5971 // Increment the blocked requests counters.
5972 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5973 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5975 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5976 if (webViewDisplayed) {
5977 // Updating the UI must be run from the UI thread.
5978 activity.runOnUiThread(() -> {
5979 // Update the menu item titles.
5980 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5982 // Update the options menu if it has been populated.
5983 if (optionsMenu != null) {
5984 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5985 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5986 getString(R.string.fanboys_annoyance_list));
5991 // The resource request was blocked. Return an empty web resource response.
5992 return emptyWebResourceResponse;
5993 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5994 // Update the whitelist result string array tracker.
5995 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5996 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5998 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5999 // Check the URL against Fanboy's Annoyance List.
6000 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
6002 // Process the Fanboy's Social Blocking List results.
6003 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
6004 // Add the result to the resource requests.
6005 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6006 fanboysSocialListResults[4], fanboysSocialListResults[5]});
6008 // Increment the blocked requests counters.
6009 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
6010 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
6012 // Update the titles of the blocklist menu items if the WebView is currently displayed.
6013 if (webViewDisplayed) {
6014 // Updating the UI must be run from the UI thread.
6015 activity.runOnUiThread(() -> {
6016 // Update the menu item titles.
6017 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6019 // Update the options menu if it has been populated.
6020 if (optionsMenu != null) {
6021 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
6022 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
6023 getString(R.string.fanboys_social_blocking_list));
6028 // The resource request was blocked. Return an empty web resource response.
6029 return emptyWebResourceResponse;
6030 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
6031 // Update the whitelist result string array tracker.
6032 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6033 fanboysSocialListResults[4], fanboysSocialListResults[5]};
6037 // Add the request to the log because it hasn't been processed by any of the previous checks.
6038 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
6039 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
6040 } else { // The request didn't match any blocklist entry. Log it as a default request.
6041 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
6044 // The resource request has not been blocked. `return null` loads the requested resource.
6048 // Handle HTTP authentication requests.
6050 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
6051 // Store the handler.
6052 nestedScrollWebView.setHttpAuthHandler(handler);
6054 // Instantiate an HTTP authentication dialog.
6055 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
6057 // Show the HTTP authentication dialog.
6058 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
6062 public void onPageStarted(WebView view, String url, Bitmap favicon) {
6063 // Get the preferences.
6064 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
6066 // 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.
6067 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6068 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6069 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6071 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6072 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6074 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6075 appBarHeight = appBarLayout.getHeight();
6077 // The swipe refresh layout must be manually moved below the app bar layout.
6078 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6080 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6081 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6084 // Reset the list of resource requests.
6085 nestedScrollWebView.clearResourceRequests();
6087 // Reset the requests counters.
6088 nestedScrollWebView.resetRequestsCounters();
6090 // Get the current page position.
6091 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6093 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6094 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6095 // Display the formatted URL text.
6096 urlEditText.setText(url);
6098 // Apply text highlighting to `urlTextBox`.
6101 // Hide the keyboard.
6102 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6105 // Reset the list of host IP addresses.
6106 nestedScrollWebView.clearCurrentIpAddresses();
6108 // Get a URI for the current URL.
6109 Uri currentUri = Uri.parse(url);
6111 // Get the IP addresses for the host.
6112 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6114 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6115 if (optionsMenu != null) {
6117 optionsRefreshMenuItem.setTitle(R.string.stop);
6119 // Get the app bar and theme preferences.
6120 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6122 // If the icon is displayed in the AppBar, set it according to the theme.
6123 if (displayAdditionalAppBarIcons) {
6124 // Get the current theme status.
6125 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6127 // Set the stop icon according to the theme.
6128 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6129 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
6131 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
6138 public void onPageFinished(WebView view, String url) {
6139 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6140 if (nestedScrollWebView.getAcceptCookies() && Build.VERSION.SDK_INT >= 21) {
6141 CookieManager.getInstance().flush();
6144 // Update the Refresh menu item if the options menu has been created.
6145 if (optionsMenu != null) {
6146 // Reset the Refresh title.
6147 optionsRefreshMenuItem.setTitle(R.string.refresh);
6149 // Get the app bar and theme preferences.
6150 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6152 // If the icon is displayed in the app bar, reset it according to the theme.
6153 if (displayAdditionalAppBarIcons) {
6154 // Get the current theme status.
6155 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6157 // Set the icon according to the theme.
6158 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6159 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6161 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6166 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6167 if (incognitoModeEnabled) {
6168 // Clear the cache. `true` includes disk files.
6169 nestedScrollWebView.clearCache(true);
6171 // Clear the back/forward history.
6172 nestedScrollWebView.clearHistory();
6174 // Manually delete cache folders.
6176 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6177 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6178 String privateDataDirectoryString = getApplicationInfo().dataDir;
6180 // Delete the main cache directory.
6181 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6183 // Delete the secondary `Service Worker` cache directory.
6184 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6185 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6186 } catch (IOException exception) {
6187 // Do nothing if an error is thrown.
6190 // Clear the logcat.
6192 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6193 Runtime.getRuntime().exec("logcat -b all -c");
6194 } catch (IOException exception) {
6199 // Get the current page position.
6200 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6202 // 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.
6203 String currentUrl = nestedScrollWebView.getUrl();
6205 // Get the current tab.
6206 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6208 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6209 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6210 // Probably some sort of race condition when Privacy Browser is being resumed.
6211 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6212 // Check to see if the URL is `about:blank`.
6213 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6214 // Display the hint in the URL edit text.
6215 urlEditText.setText("");
6217 // Request focus for the URL text box.
6218 urlEditText.requestFocus();
6220 // Display the keyboard.
6221 inputMethodManager.showSoftInput(urlEditText, 0);
6223 // Apply the domain settings. This clears any settings from the previous domain.
6224 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6226 // Only populate the title text view if the tab has been fully created.
6228 // Get the custom view from the tab.
6229 View tabView = tab.getCustomView();
6231 // Remove the incorrect warning below that the current tab view might be null.
6232 assert tabView != null;
6234 // Get the title text view from the tab.
6235 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6237 // Set the title as the tab text.
6238 tabTitleTextView.setText(R.string.new_tab);
6240 } else { // The WebView has loaded a webpage.
6241 // Update the URL edit text if it is not currently being edited.
6242 if (!urlEditText.hasFocus()) {
6243 // 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.
6244 String sanitizedUrl = sanitizeUrl(currentUrl);
6246 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6247 urlEditText.setText(sanitizedUrl);
6249 // Apply text highlighting to the URL.
6253 // Only populate the title text view if the tab has been fully created.
6255 // Get the custom view from the tab.
6256 View tabView = tab.getCustomView();
6258 // Remove the incorrect warning below that the current tab view might be null.
6259 assert tabView != null;
6261 // Get the title text view from the tab.
6262 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6264 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6265 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6271 // Handle SSL Certificate errors.
6273 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6274 // Get the current website SSL certificate.
6275 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6277 // Extract the individual pieces of information from the current website SSL certificate.
6278 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6279 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6280 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6281 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6282 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6283 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6284 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6285 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6287 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6288 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6289 // Get the pinned SSL certificate.
6290 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6292 // Extract the arrays from the array list.
6293 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6294 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6296 // Check if the current SSL certificate matches the pinned certificate.
6297 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6298 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6299 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6300 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6302 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6305 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6306 // Store the SSL error handler.
6307 nestedScrollWebView.setSslErrorHandler(handler);
6309 // Prevent the dialog from displaying if the app window is not visible.
6310 // The SSL error handler continues to function even when the WebView is paused. Attempting to display a dialog in that state leads to a crash.
6311 while (!activity.getWindow().isActive()) {
6313 // The window is not active. Wait 1 second.
6315 } catch (InterruptedException e) {
6320 // Instantiate an SSL certificate error alert dialog.
6321 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6323 // Show the SSL certificate error dialog.
6324 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6329 // Check to see if the state is being restored.
6330 if (restoringState) { // The state is being restored.
6331 // Resume the nested scroll WebView JavaScript timers.
6332 nestedScrollWebView.resumeTimers();
6333 } else if (pageNumber == 0) { // The first page is being loaded.
6334 // Set this nested scroll WebView as the current WebView.
6335 currentWebView = nestedScrollWebView;
6337 // Initialize the URL to load string.
6338 String urlToLoadString;
6340 // Get the intent that started the app.
6341 Intent launchingIntent = getIntent();
6343 // Reset the intent. This prevents a duplicate tab from being created on restart.
6344 setIntent(new Intent());
6346 // Get the information from the intent.
6347 String launchingIntentAction = launchingIntent.getAction();
6348 Uri launchingIntentUriData = launchingIntent.getData();
6349 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6351 // Parse the launching intent URL.
6352 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6353 // Create an encoded URL string.
6354 String encodedUrlString;
6356 // Sanitize the search input and convert it to a search.
6358 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6359 } catch (UnsupportedEncodingException exception) {
6360 encodedUrlString = "";
6363 // Store the web search as the URL to load.
6364 urlToLoadString = searchURL + encodedUrlString;
6365 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6366 // Store the URI as a URL.
6367 urlToLoadString = launchingIntentUriData.toString();
6368 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6370 urlToLoadString = launchingIntentStringExtra;
6371 } else if (!url.equals("")) { // The activity has been restarted.
6372 // Load the saved URL.
6373 urlToLoadString = url;
6374 } else { // The is no URL in the intent.
6375 // Store the homepage to be loaded.
6376 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6379 // Load the website if not waiting for the proxy.
6380 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6381 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6382 } else { // Load the URL.
6383 loadUrl(nestedScrollWebView, urlToLoadString);
6386 // 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.
6387 // 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.
6388 setIntent(new Intent());
6389 } else { // This is not the first tab.
6391 loadUrl(nestedScrollWebView, url);
6393 // Set the focus and display the keyboard if the URL is blank.
6394 if (url.equals("")) {
6395 // Request focus for the URL text box.
6396 urlEditText.requestFocus();
6398 // Create a display keyboard handler.
6399 Handler displayKeyboardHandler = new Handler();
6401 // Create a display keyboard runnable.
6402 Runnable displayKeyboardRunnable = () -> {
6403 // Display the keyboard.
6404 inputMethodManager.showSoftInput(urlEditText, 0);
6407 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6408 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);