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.Handler;
52 import android.os.Message;
53 import android.preference.PreferenceManager;
54 import android.print.PrintDocumentAdapter;
55 import android.print.PrintManager;
56 import android.text.Editable;
57 import android.text.Spanned;
58 import android.text.TextWatcher;
59 import android.text.style.ForegroundColorSpan;
60 import android.util.Patterns;
61 import android.util.TypedValue;
62 import android.view.ContextMenu;
63 import android.view.GestureDetector;
64 import android.view.KeyEvent;
65 import android.view.Menu;
66 import android.view.MenuItem;
67 import android.view.MotionEvent;
68 import android.view.View;
69 import android.view.ViewGroup;
70 import android.view.WindowManager;
71 import android.view.inputmethod.InputMethodManager;
72 import android.webkit.CookieManager;
73 import android.webkit.HttpAuthHandler;
74 import android.webkit.SslErrorHandler;
75 import android.webkit.ValueCallback;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebSettings;
80 import android.webkit.WebStorage;
81 import android.webkit.WebView;
82 import android.webkit.WebViewClient;
83 import android.webkit.WebViewDatabase;
84 import android.widget.ArrayAdapter;
85 import android.widget.CursorAdapter;
86 import android.widget.EditText;
87 import android.widget.FrameLayout;
88 import android.widget.ImageView;
89 import android.widget.LinearLayout;
90 import android.widget.ListView;
91 import android.widget.ProgressBar;
92 import android.widget.RadioButton;
93 import android.widget.RelativeLayout;
94 import android.widget.TextView;
96 import androidx.annotation.NonNull;
97 import androidx.annotation.Nullable;
98 import androidx.appcompat.app.ActionBar;
99 import androidx.appcompat.app.ActionBarDrawerToggle;
100 import androidx.appcompat.app.AppCompatActivity;
101 import androidx.appcompat.app.AppCompatDelegate;
102 import androidx.appcompat.widget.Toolbar;
103 import androidx.coordinatorlayout.widget.CoordinatorLayout;
104 import androidx.core.content.res.ResourcesCompat;
105 import androidx.core.view.GravityCompat;
106 import androidx.drawerlayout.widget.DrawerLayout;
107 import androidx.fragment.app.DialogFragment;
108 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
109 import androidx.viewpager.widget.ViewPager;
110 import androidx.webkit.WebSettingsCompat;
111 import androidx.webkit.WebViewFeature;
113 import com.google.android.material.appbar.AppBarLayout;
114 import com.google.android.material.floatingactionbutton.FloatingActionButton;
115 import com.google.android.material.navigation.NavigationView;
116 import com.google.android.material.snackbar.Snackbar;
117 import com.google.android.material.tabs.TabLayout;
119 import com.stoutner.privacybrowser.BuildConfig;
120 import com.stoutner.privacybrowser.R;
121 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
122 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
123 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
124 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
125 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
126 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
127 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
128 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
129 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
130 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
131 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
132 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
133 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
134 import com.stoutner.privacybrowser.dialogs.OpenDialog;
135 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
136 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
137 import com.stoutner.privacybrowser.dialogs.SaveWebpageDialog;
138 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
139 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
140 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
141 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
142 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
143 import com.stoutner.privacybrowser.helpers.AdHelper;
144 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
145 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
146 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
147 import com.stoutner.privacybrowser.helpers.ProxyHelper;
148 import com.stoutner.privacybrowser.views.NestedScrollWebView;
150 import java.io.ByteArrayInputStream;
151 import java.io.ByteArrayOutputStream;
153 import java.io.IOException;
154 import java.io.UnsupportedEncodingException;
155 import java.net.MalformedURLException;
157 import java.net.URLDecoder;
158 import java.net.URLEncoder;
159 import java.text.NumberFormat;
160 import java.util.ArrayList;
161 import java.util.Date;
162 import java.util.HashMap;
163 import java.util.HashSet;
164 import java.util.List;
165 import java.util.Map;
166 import java.util.Objects;
167 import java.util.Set;
168 import java.util.concurrent.ExecutorService;
169 import java.util.concurrent.Executors;
171 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
172 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
173 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageDialog.SaveWebpageListener, UrlHistoryDialog.NavigateHistoryListener,
174 WebViewTabFragment.NewTabListener {
176 // The executor service handles background tasks. It is accessed from `ViewSourceActivity`.
177 public static ExecutorService executorService = Executors.newFixedThreadPool(4);
179 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
180 public static String orbotStatus = "unknown";
182 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
183 public static WebViewPagerAdapter webViewPagerAdapter;
185 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
186 public static boolean restartFromBookmarksActivity;
188 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
189 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
190 public static String currentBookmarksFolder;
192 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
193 public final static int UNRECOGNIZED_USER_AGENT = -1;
194 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
195 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
196 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
197 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
198 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
200 // Define the start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
201 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
202 public final static int BROWSE_OPEN_REQUEST_CODE = 1;
203 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 2;
205 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
206 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
207 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
208 public static String proxyMode = ProxyHelper.NONE;
210 // Define the saved instance state constants.
211 private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
212 private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
213 private final String SAVED_TAB_POSITION = "saved_tab_position";
214 private final String PROXY_MODE = "proxy_mode";
216 // Define the saved instance state variables.
217 private ArrayList<Bundle> savedStateArrayList;
218 private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
219 private int savedTabPosition;
220 private String savedProxyMode;
222 // Define the class variables.
223 @SuppressWarnings("rawtypes")
224 AsyncTask populateBlocklists;
226 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
227 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
228 private NestedScrollWebView currentWebView;
230 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
231 private final Map<String, String> customHeaders = new HashMap<>();
233 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
234 private String searchURL;
236 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
237 private ArrayList<List<String[]>> easyList;
238 private ArrayList<List<String[]>> easyPrivacy;
239 private ArrayList<List<String[]>> fanboysAnnoyanceList;
240 private ArrayList<List<String[]>> fanboysSocialList;
241 private ArrayList<List<String[]>> ultraList;
242 private ArrayList<List<String[]>> ultraPrivacy;
244 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
245 private String webViewDefaultUserAgent;
247 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
248 private boolean incognitoModeEnabled;
250 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
251 private boolean fullScreenBrowsingModeEnabled;
253 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
254 private boolean inFullScreenBrowsingMode;
256 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
257 private boolean hideAppBar;
258 private boolean scrollAppBar;
260 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
261 private boolean loadingNewIntent;
263 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
264 private boolean reapplyDomainSettingsOnRestart;
266 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
267 private boolean reapplyAppSettingsOnRestart;
269 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
270 private boolean displayingFullScreenVideo;
272 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
273 private BroadcastReceiver orbotStatusBroadcastReceiver;
275 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
276 private boolean waitingForProxy = false;
278 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
279 private ActionBarDrawerToggle actionBarDrawerToggle;
281 // The color spans are used in `onCreate()` and `highlightUrlText()`.
282 private ForegroundColorSpan redColorSpan;
283 private ForegroundColorSpan initialGrayColorSpan;
284 private ForegroundColorSpan finalGrayColorSpan;
286 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
287 // and `loadBookmarksFolder()`.
288 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
290 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
291 private Cursor bookmarksCursor;
293 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
294 private CursorAdapter bookmarksCursorAdapter;
296 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
297 private String oldFolderNameString;
299 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
300 private ValueCallback<Uri[]> fileChooserCallback;
302 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
303 private int appBarHeight;
304 private int defaultProgressViewStartOffset;
305 private int defaultProgressViewEndOffset;
307 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
308 private boolean sanitizeGoogleAnalytics;
309 private boolean sanitizeFacebookClickIds;
310 private boolean sanitizeTwitterAmpRedirects;
312 // Declare the class views.
313 private FrameLayout rootFrameLayout;
314 private DrawerLayout drawerLayout;
315 private RelativeLayout mainContentRelativeLayout;
316 private AppBarLayout appBarLayout;
317 private Toolbar toolbar;
318 private RelativeLayout urlRelativeLayout;
319 private EditText urlEditText;
320 private ActionBar actionBar;
321 private LinearLayout findOnPageLinearLayout;
322 private LinearLayout tabsLinearLayout;
323 private TabLayout tabLayout;
324 private SwipeRefreshLayout swipeRefreshLayout;
325 private ViewPager webViewPager;
326 private FrameLayout fullScreenVideoFrameLayout;
328 // Declare the class menus.
329 private Menu optionsMenu;
331 // Declare the class menu items.
332 private MenuItem navigationBackMenuItem;
333 private MenuItem navigationForwardMenuItem;
334 private MenuItem navigationHistoryMenuItem;
335 private MenuItem navigationRequestsMenuItem;
336 private MenuItem optionsPrivacyMenuItem;
337 private MenuItem optionsRefreshMenuItem;
338 private MenuItem optionsFirstPartyCookiesMenuItem;
339 private MenuItem optionsThirdPartyCookiesMenuItem;
340 private MenuItem optionsDomStorageMenuItem;
341 private MenuItem optionsSaveFormDataMenuItem;
342 private MenuItem optionsClearDataMenuItem;
343 private MenuItem optionsClearCookiesMenuItem;
344 private MenuItem optionsClearDomStorageMenuItem;
345 private MenuItem optionsClearFormDataMenuItem;
346 private MenuItem optionsBlocklistsMenuItem;
347 private MenuItem optionsEasyListMenuItem;
348 private MenuItem optionsEasyPrivacyMenuItem;
349 private MenuItem optionsFanboysAnnoyanceListMenuItem;
350 private MenuItem optionsFanboysSocialBlockingListMenuItem;
351 private MenuItem optionsUltraListMenuItem;
352 private MenuItem optionsUltraPrivacyMenuItem;
353 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
354 private MenuItem optionsProxyMenuItem;
355 private MenuItem optionsProxyNoneMenuItem;
356 private MenuItem optionsProxyTorMenuItem;
357 private MenuItem optionsProxyI2pMenuItem;
358 private MenuItem optionsProxyCustomMenuItem;
359 private MenuItem optionsUserAgentMenuItem;
360 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
361 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
362 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
363 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
364 private MenuItem optionsUserAgentSafariOnIosMenuItem;
365 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
366 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
367 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
368 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
369 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
370 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
371 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
372 private MenuItem optionsUserAgentCustomMenuItem;
373 private MenuItem optionsSwipeToRefreshMenuItem;
374 private MenuItem optionsWideViewportMenuItem;
375 private MenuItem optionsDisplayImagesMenuItem;
376 private MenuItem optionsDarkWebViewMenuItem;
377 private MenuItem optionsFontSizeMenuItem;
378 private MenuItem optionsAddOrEditDomainMenuItem;
381 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
382 @SuppressLint("ClickableViewAccessibility")
383 protected void onCreate(Bundle savedInstanceState) {
384 // Run the default commands.
385 super.onCreate(savedInstanceState);
387 // Check to see if the activity has been restarted.
388 if (savedInstanceState != null) {
389 // Store the saved instance state variables.
390 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
391 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
392 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
393 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
396 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
397 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
399 // Get a handle for the shared preferences.
400 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
402 // Get the screenshot preference.
403 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
404 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
406 // Get the theme entry values string array.
407 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
409 // 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.
410 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
411 // Apply the light theme.
412 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
413 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
414 // Apply the dark theme.
415 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
416 } else { // The system default theme is selected.
417 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
418 // Follow the system default theme.
419 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
420 } else { // The system default theme is not supported.
421 // Follow the battery saver mode.
422 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
426 // Disable screenshots if not allowed.
427 if (!allowScreenshots) {
428 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
431 // 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.
432 if (Build.VERSION.SDK_INT >= 21) {
433 WebView.enableSlowWholeDocumentDraw();
437 setTheme(R.style.PrivacyBrowser);
439 // Set the content view.
440 setContentView(R.layout.main_framelayout);
442 // Get handles for the views.
443 rootFrameLayout = findViewById(R.id.root_framelayout);
444 drawerLayout = findViewById(R.id.drawerlayout);
445 mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
446 appBarLayout = findViewById(R.id.appbar_layout);
447 toolbar = findViewById(R.id.toolbar);
448 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
449 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
450 tabLayout = findViewById(R.id.tablayout);
451 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
452 webViewPager = findViewById(R.id.webviewpager);
453 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
455 // Get a handle for the navigation view.
456 NavigationView navigationView = findViewById(R.id.navigationview);
458 // Get a handle for the navigation menu.
459 Menu navigationMenu = navigationView.getMenu();
461 // Get handles for the navigation menu items.
462 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
463 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
464 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
465 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
467 // Listen for touches on the navigation menu.
468 navigationView.setNavigationItemSelectedListener(this);
470 // Get a handle for the app compat delegate.
471 AppCompatDelegate appCompatDelegate = getDelegate();
473 // Set the support action bar.
474 appCompatDelegate.setSupportActionBar(toolbar);
476 // Get a handle for the action bar.
477 actionBar = appCompatDelegate.getSupportActionBar();
479 // Remove the incorrect lint warning below that the action bar might be null.
480 assert actionBar != null;
482 // Add the custom layout, which shows the URL text bar.
483 actionBar.setCustomView(R.layout.url_app_bar);
484 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
486 // Get handles for the views in the URL app bar.
487 urlRelativeLayout = findViewById(R.id.url_relativelayout);
488 urlEditText = findViewById(R.id.url_edittext);
490 // Create the hamburger icon at the start of the AppBar.
491 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
493 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
494 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
496 // Initialize the web view pager adapter.
497 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
499 // Set the pager adapter on the web view pager.
500 webViewPager.setAdapter(webViewPagerAdapter);
502 // Store up to 100 tabs in memory.
503 webViewPager.setOffscreenPageLimit(100);
505 // Initialize the app.
508 // Apply the app settings from the shared preferences.
511 // Populate the blocklists.
512 populateBlocklists = new PopulateBlocklists(this, this).execute();
516 protected void onNewIntent(Intent intent) {
517 // Run the default commands.
518 super.onNewIntent(intent);
520 // Replace the intent that started the app with this one.
523 // Check to see if the app is being restarted from a saved state.
524 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
525 // Get the information from the intent.
526 String intentAction = intent.getAction();
527 Uri intentUriData = intent.getData();
528 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
530 // Determine if this is a web search.
531 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
533 // 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.
534 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
535 // Get the shared preferences.
536 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
538 // Create a URL string.
541 // If the intent action is a web search, perform the search.
542 if (isWebSearch) { // The intent is a web search.
543 // Create an encoded URL string.
544 String encodedUrlString;
546 // Sanitize the search input and convert it to a search.
548 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
549 } catch (UnsupportedEncodingException exception) {
550 encodedUrlString = "";
553 // Add the base search URL.
554 url = searchURL + encodedUrlString;
555 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
556 // Set the intent data as the URL.
557 url = intentUriData.toString();
558 } else { // The intent contains a string, which might be a URL.
559 // Set the intent string as the URL.
560 url = intentStringExtra;
563 // Add a new tab if specified in the preferences.
564 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
565 // Set the loading new intent flag.
566 loadingNewIntent = true;
569 addNewTab(url, true);
570 } else { // Load the URL in the current tab.
572 loadUrl(currentWebView, url);
575 // Close the navigation drawer if it is open.
576 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
577 drawerLayout.closeDrawer(GravityCompat.START);
580 // Close the bookmarks drawer if it is open.
581 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
582 drawerLayout.closeDrawer(GravityCompat.END);
589 public void onRestart() {
590 // Run the default commands.
593 // Apply the app settings if returning from the Settings activity.
594 if (reapplyAppSettingsOnRestart) {
595 // Reset the reapply app settings on restart tracker.
596 reapplyAppSettingsOnRestart = false;
598 // Apply the app settings.
602 // Apply the domain settings if returning from the settings or domains activity.
603 if (reapplyDomainSettingsOnRestart) {
604 // Reset the reapply domain settings on restart tracker.
605 reapplyDomainSettingsOnRestart = false;
607 // Reapply the domain settings for each tab.
608 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
609 // Get the WebView tab fragment.
610 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
612 // Get the fragment view.
613 View fragmentView = webViewTabFragment.getView();
615 // Only reload the WebViews if they exist.
616 if (fragmentView != null) {
617 // Get the nested scroll WebView from the tab fragment.
618 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
620 // Reset the current domain name so the domain settings will be reapplied.
621 nestedScrollWebView.resetCurrentDomainName();
623 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
624 if (nestedScrollWebView.getUrl() != null) {
625 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
631 // Update the bookmarks drawer if returning from the Bookmarks activity.
632 if (restartFromBookmarksActivity) {
633 // Close the bookmarks drawer.
634 drawerLayout.closeDrawer(GravityCompat.END);
636 // Reload the bookmarks drawer.
637 loadBookmarksFolder();
639 // Reset `restartFromBookmarksActivity`.
640 restartFromBookmarksActivity = false;
643 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
644 updatePrivacyIcons(true);
647 // `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.
649 public void onStart() {
650 // Run the default commands.
653 // Resume any WebViews.
654 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
655 // Get the WebView tab fragment.
656 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
658 // Get the fragment view.
659 View fragmentView = webViewTabFragment.getView();
661 // Only resume the WebViews if they exist (they won't when the app is first created).
662 if (fragmentView != null) {
663 // Get the nested scroll WebView from the tab fragment.
664 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
666 // Resume the nested scroll WebView.
667 nestedScrollWebView.onResume();
671 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
672 if (currentWebView != null) {
673 currentWebView.resumeTimers();
676 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
677 if (!proxyMode.equals(ProxyHelper.NONE)) {
681 // Reapply any system UI flags and the ad in the free flavor.
682 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
683 /* Hide the system bars.
684 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
685 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
686 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
687 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
689 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
690 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
691 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
692 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
693 View adView = findViewById(R.id.adview);
696 AdHelper.resumeAd(adView);
700 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
702 public void onStop() {
703 // Run the default commands.
706 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
707 // Get the WebView tab fragment.
708 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
710 // Get the fragment view.
711 View fragmentView = webViewTabFragment.getView();
713 // Only pause the WebViews if they exist (they won't when the app is first created).
714 if (fragmentView != null) {
715 // Get the nested scroll WebView from the tab fragment.
716 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
718 // Pause the nested scroll WebView.
719 nestedScrollWebView.onPause();
723 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
724 if (currentWebView != null) {
725 currentWebView.pauseTimers();
728 // Pause the ad or it will continue to consume resources in the background on the free flavor.
729 if (BuildConfig.FLAVOR.contentEquals("free")) {
730 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
731 View adView = findViewById(R.id.adview);
734 AdHelper.pauseAd(adView);
739 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
740 // Run the default commands.
741 super.onSaveInstanceState(savedInstanceState);
743 // Create the saved state array lists.
744 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
745 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
747 // Get the URLs from each tab.
748 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
749 // Get the WebView tab fragment.
750 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
752 // Get the fragment view.
753 View fragmentView = webViewTabFragment.getView();
755 if (fragmentView != null) {
756 // Get the nested scroll WebView from the tab fragment.
757 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
759 // Create saved state bundle.
760 Bundle savedStateBundle = new Bundle();
762 // Get the current states.
763 nestedScrollWebView.saveState(savedStateBundle);
764 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
766 // Store the saved states in the array lists.
767 savedStateArrayList.add(savedStateBundle);
768 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
772 // Get the current tab position.
773 int currentTabPosition = tabLayout.getSelectedTabPosition();
775 // Store the saved states in the bundle.
776 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
777 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
778 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
779 savedInstanceState.putString(PROXY_MODE, proxyMode);
783 public void onDestroy() {
784 // Unregister the orbot status broadcast receiver if it exists.
785 if (orbotStatusBroadcastReceiver != null) {
786 this.unregisterReceiver(orbotStatusBroadcastReceiver);
789 // Close the bookmarks cursor if it exists.
790 if (bookmarksCursor != null) {
791 bookmarksCursor.close();
794 // Close the bookmarks database if it exists.
795 if (bookmarksDatabaseHelper != null) {
796 bookmarksDatabaseHelper.close();
799 // Stop populating the blocklists if the AsyncTask is running in the background.
800 if (populateBlocklists != null) {
801 populateBlocklists.cancel(true);
804 // Run the default commands.
809 public boolean onCreateOptionsMenu(Menu menu) {
810 // Inflate the menu. This adds items to the action bar if it is present.
811 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
813 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
816 // Get handles for the class menu items.
817 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
818 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
819 optionsFirstPartyCookiesMenuItem = menu.findItem(R.id.first_party_cookies);
820 optionsThirdPartyCookiesMenuItem = menu.findItem(R.id.third_party_cookies);
821 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
822 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
823 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
824 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
825 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
826 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
827 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
828 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
829 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
830 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
831 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
832 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
833 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
834 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
835 optionsProxyMenuItem = menu.findItem(R.id.proxy);
836 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
837 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
838 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
839 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
840 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
841 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
842 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
843 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
844 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
845 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
846 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
847 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
848 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
849 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
850 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
851 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
852 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
853 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
854 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
855 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
856 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
857 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
858 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
859 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
861 // Get handles for the method menu items.
862 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
863 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
865 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
866 updatePrivacyIcons(false);
868 // Only display third-party cookies if API >= 21
869 optionsThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
871 // Only display the form data menu items if the API < 26.
872 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
873 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
875 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
876 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
878 // Only display the dark WebView menu item if API >= 21.
879 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
881 // Only show Ad Consent if this is the free flavor.
882 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
884 // Get the shared preferences.
885 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
887 // Get the dark theme and app bar preferences.
888 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
890 // 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.
891 if (displayAdditionalAppBarIcons) {
892 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
893 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
894 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
895 } else { //Do not display the additional icons.
896 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
897 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
898 optionsFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
901 // Replace Refresh with Stop if a URL is already loading.
902 if (currentWebView != null && currentWebView.getProgress() != 100) {
904 optionsRefreshMenuItem.setTitle(R.string.stop);
906 // Set the icon if it is displayed in the app bar.
907 if (displayAdditionalAppBarIcons) {
908 // Get the current theme status.
909 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
911 // Set the icon according to the current theme status.
912 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
913 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
915 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
925 public boolean onPrepareOptionsMenu(Menu menu) {
926 // Get a handle for the cookie manager.
927 CookieManager cookieManager = CookieManager.getInstance();
929 // Initialize the current user agent string and the font size.
930 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
933 // 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.
934 if (currentWebView != null) {
935 // Set the add or edit domain text.
936 if (currentWebView.getDomainSettingsApplied()) {
937 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
939 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
942 // Get the current user agent from the WebView.
943 currentUserAgent = currentWebView.getSettings().getUserAgentString();
945 // Get the current font size from the
946 fontSize = currentWebView.getSettings().getTextZoom();
948 // Set the status of the menu item checkboxes.
949 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
950 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
951 optionsEasyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
952 optionsEasyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
953 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
954 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
955 optionsUltraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
956 optionsUltraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
957 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
958 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
959 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
960 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
962 // Initialize the display names for the blocklists with the number of blocked requests.
963 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
964 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
965 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
966 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
967 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
968 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
969 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
970 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
972 // Only modify third-party cookies if the API >= 21.
973 if (Build.VERSION.SDK_INT >= 21) {
974 // Set the status of the third-party cookies checkbox.
975 optionsThirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
977 // Enable third-party cookies if first-party cookies are enabled.
978 optionsThirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
981 // Enable DOM Storage if JavaScript is enabled.
982 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
984 // Set the checkbox status for dark WebView if the WebView supports it.
985 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
986 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
990 // Set the checked status of the first party cookies menu item.
991 optionsFirstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
993 // Enable Clear Cookies if there are any.
994 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
996 // 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`.
997 String privateDataDirectoryString = getApplicationInfo().dataDir;
999 // Get a count of the number of files in the Local Storage directory.
1000 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1001 int localStorageDirectoryNumberOfFiles = 0;
1002 if (localStorageDirectory.exists()) {
1003 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1004 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1007 // Get a count of the number of files in the IndexedDB directory.
1008 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1009 int indexedDBDirectoryNumberOfFiles = 0;
1010 if (indexedDBDirectory.exists()) {
1011 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1012 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1015 // Enable Clear DOM Storage if there is any.
1016 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1018 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1019 if (Build.VERSION.SDK_INT < 26) {
1020 // Get the WebView database.
1021 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1023 // Enable the clear form data menu item if there is anything to clear.
1024 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1027 // Enable Clear Data if any of the submenu items are enabled.
1028 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1030 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1031 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1033 // Set the proxy title and check the applied proxy.
1034 switch (proxyMode) {
1035 case ProxyHelper.NONE:
1036 // Set the proxy title.
1037 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1039 // Check the proxy None radio button.
1040 optionsProxyNoneMenuItem.setChecked(true);
1043 case ProxyHelper.TOR:
1044 // Set the proxy title.
1045 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1047 // Check the proxy Tor radio button.
1048 optionsProxyTorMenuItem.setChecked(true);
1051 case ProxyHelper.I2P:
1052 // Set the proxy title.
1053 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1055 // Check the proxy I2P radio button.
1056 optionsProxyI2pMenuItem.setChecked(true);
1059 case ProxyHelper.CUSTOM:
1060 // Set the proxy title.
1061 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1063 // Check the proxy Custom radio button.
1064 optionsProxyCustomMenuItem.setChecked(true);
1068 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1069 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1070 // Update the user agent menu item title.
1071 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1073 // Select the Privacy Browser radio box.
1074 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1075 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1076 // Update the user agent menu item title.
1077 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1079 // Select the WebView Default radio box.
1080 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1081 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1082 // Update the user agent menu item title.
1083 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1085 // Select the Firefox on Android radio box.
1086 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1087 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1088 // Update the user agent menu item title.
1089 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1091 // Select the Chrome on Android radio box.
1092 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1093 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1094 // Update the user agent menu item title.
1095 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1097 // Select the Safari on iOS radio box.
1098 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1099 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1100 // Update the user agent menu item title.
1101 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1103 // Select the Firefox on Linux radio box.
1104 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1105 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1106 // Update the user agent menu item title.
1107 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1109 // Select the Chromium on Linux radio box.
1110 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1111 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1112 // Update the user agent menu item title.
1113 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1115 // Select the Firefox on Windows radio box.
1116 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1117 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1118 // Update the user agent menu item title.
1119 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1121 // Select the Chrome on Windows radio box.
1122 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1123 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1124 // Update the user agent menu item title.
1125 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1127 // Select the Edge on Windows radio box.
1128 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1129 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1130 // Update the user agent menu item title.
1131 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1133 // Select the Internet on Windows radio box.
1134 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1135 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1136 // Update the user agent menu item title.
1137 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1139 // Select the Safari on macOS radio box.
1140 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1141 } else { // Custom user agent.
1142 // Update the user agent menu item title.
1143 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1145 // Select the Custom radio box.
1146 optionsUserAgentCustomMenuItem.setChecked(true);
1149 // Set the font size title.
1150 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1152 // Run all the other default commands.
1153 super.onPrepareOptionsMenu(menu);
1155 // Display the menu.
1160 public boolean onOptionsItemSelected(MenuItem menuItem) {
1161 // Get a handle for the shared preferences.
1162 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1164 // Get a handle for the cookie manager.
1165 CookieManager cookieManager = CookieManager.getInstance();
1167 // Get the selected menu item ID.
1168 int menuItemId = menuItem.getItemId();
1170 // Run the commands that correlate to the selected menu item.
1171 if (menuItemId == R.id.javascript) { // JavaScript.
1172 // Toggle the JavaScript status.
1173 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1175 // Update the privacy icon.
1176 updatePrivacyIcons(true);
1178 // Display a `Snackbar`.
1179 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1180 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1181 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1182 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1183 } else { // Privacy mode.
1184 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1187 // Reload the current WebView.
1188 currentWebView.reload();
1190 // Consume the event.
1192 } else if (menuItemId == R.id.refresh) { // Refresh.
1193 // Run the command that correlates to the current status of the menu item.
1194 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1195 // Reload the current WebView.
1196 currentWebView.reload();
1197 } else { // The stop button was pushed.
1198 // Stop the loading of the WebView.
1199 currentWebView.stopLoading();
1202 // Consume the event.
1204 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1205 // Open the bookmarks drawer.
1206 drawerLayout.openDrawer(GravityCompat.END);
1208 // Consume the event.
1210 } else if (menuItemId == R.id.first_party_cookies) { // First-party cookies.
1211 // Switch the first-party cookie status.
1212 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1214 // Store the first-party cookie status.
1215 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1217 // Update the menu checkbox.
1218 menuItem.setChecked(cookieManager.acceptCookie());
1220 // Update the privacy icon.
1221 updatePrivacyIcons(true);
1223 // Display a snackbar.
1224 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1225 Snackbar.make(webViewPager, R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1226 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1227 Snackbar.make(webViewPager, R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1228 } else { // Privacy mode.
1229 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1232 // Reload the current WebView.
1233 currentWebView.reload();
1235 // Consume the event.
1237 } else if (menuItemId == R.id.third_party_cookies) { // Third-party cookies.
1238 // Only act if the API >= 21. Otherwise, there are no third-party cookie controls.
1239 if (Build.VERSION.SDK_INT >= 21) {
1240 // Toggle the status of thirdPartyCookiesEnabled.
1241 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1243 // Update the menu checkbox.
1244 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1246 // Display a snackbar.
1247 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1248 Snackbar.make(webViewPager, R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1250 Snackbar.make(webViewPager, R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1253 // Reload the current WebView.
1254 currentWebView.reload();
1257 // Consume the event.
1259 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1260 // Toggle the status of domStorageEnabled.
1261 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1263 // Update the menu checkbox.
1264 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1266 // Update the privacy icon.
1267 updatePrivacyIcons(true);
1269 // Display a snackbar.
1270 if (currentWebView.getSettings().getDomStorageEnabled()) {
1271 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1273 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1276 // Reload the current WebView.
1277 currentWebView.reload();
1279 // Consume the event.
1281 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1282 // Switch the status of saveFormDataEnabled.
1283 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1285 // Update the menu checkbox.
1286 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1288 // Display a snackbar.
1289 if (currentWebView.getSettings().getSaveFormData()) {
1290 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1292 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1295 // Update the privacy icon.
1296 updatePrivacyIcons(true);
1298 // Reload the current WebView.
1299 currentWebView.reload();
1301 // Consume the event.
1303 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1304 // Create a snackbar.
1305 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1306 .setAction(R.string.undo, v -> {
1307 // Do nothing because everything will be handled by `onDismissed()` below.
1309 .addCallback(new Snackbar.Callback() {
1311 public void onDismissed(Snackbar snackbar, int event) {
1312 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1313 // Delete the cookies, which command varies by SDK.
1314 if (Build.VERSION.SDK_INT < 21) {
1315 cookieManager.removeAllCookie();
1317 cookieManager.removeAllCookies(null);
1324 // Consume the event.
1326 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1327 // Create a snackbar.
1328 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1329 .setAction(R.string.undo, v -> {
1330 // Do nothing because everything will be handled by `onDismissed()` below.
1332 .addCallback(new Snackbar.Callback() {
1334 public void onDismissed(Snackbar snackbar, int event) {
1335 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1336 // Delete the DOM Storage.
1337 WebStorage webStorage = WebStorage.getInstance();
1338 webStorage.deleteAllData();
1340 // Initialize a handler to manually delete the DOM storage files and directories.
1341 Handler deleteDomStorageHandler = new Handler();
1343 // Setup a runnable to manually delete the DOM storage files and directories.
1344 Runnable deleteDomStorageRunnable = () -> {
1346 // Get a handle for the runtime.
1347 Runtime runtime = Runtime.getRuntime();
1349 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1350 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1351 String privateDataDirectoryString = getApplicationInfo().dataDir;
1353 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1354 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1356 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1357 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1358 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1359 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1360 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1362 // Wait for the processes to finish.
1363 deleteLocalStorageProcess.waitFor();
1364 deleteIndexProcess.waitFor();
1365 deleteQuotaManagerProcess.waitFor();
1366 deleteQuotaManagerJournalProcess.waitFor();
1367 deleteDatabasesProcess.waitFor();
1368 } catch (Exception exception) {
1369 // Do nothing if an error is thrown.
1373 // Manually delete the DOM storage files after 200 milliseconds.
1374 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1380 // Consume the event.
1382 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1383 // Create a snackbar.
1384 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1385 .setAction(R.string.undo, v -> {
1386 // Do nothing because everything will be handled by `onDismissed()` below.
1388 .addCallback(new Snackbar.Callback() {
1390 public void onDismissed(Snackbar snackbar, int event) {
1391 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1392 // Get a handle for the webView database.
1393 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1395 // Delete the form data.
1396 webViewDatabase.clearFormData();
1402 // Consume the event.
1404 } else if (menuItemId == R.id.easylist) { // EasyList.
1405 // Toggle the EasyList status.
1406 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1408 // Update the menu checkbox.
1409 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1411 // Reload the current WebView.
1412 currentWebView.reload();
1414 // Consume the event.
1416 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1417 // Toggle the EasyPrivacy status.
1418 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1420 // Update the menu checkbox.
1421 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1423 // Reload the current WebView.
1424 currentWebView.reload();
1426 // Consume the event.
1428 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1429 // Toggle Fanboy's Annoyance List status.
1430 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1432 // Update the menu checkbox.
1433 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1435 // Update the staus of Fanboy's Social Blocking List.
1436 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1438 // Reload the current WebView.
1439 currentWebView.reload();
1441 // Consume the event.
1443 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1444 // Toggle Fanboy's Social Blocking List status.
1445 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1447 // Update the menu checkbox.
1448 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1450 // Reload the current WebView.
1451 currentWebView.reload();
1453 // Consume the event.
1455 } else if (menuItemId == R.id.ultralist) { // UltraList.
1456 // Toggle the UltraList status.
1457 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1459 // Update the menu checkbox.
1460 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1462 // Reload the current WebView.
1463 currentWebView.reload();
1465 // Consume the event.
1467 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1468 // Toggle the UltraPrivacy status.
1469 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1471 // Update the menu checkbox.
1472 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1474 // Reload the current WebView.
1475 currentWebView.reload();
1477 // Consume the event.
1479 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1480 //Toggle the third-party requests blocker status.
1481 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1483 // Update the menu checkbox.
1484 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1486 // Reload the current WebView.
1487 currentWebView.reload();
1489 // Consume the event.
1491 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1492 // Update the proxy mode.
1493 proxyMode = ProxyHelper.NONE;
1495 // Apply the proxy mode.
1498 // Consume the event.
1500 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1501 // Update the proxy mode.
1502 proxyMode = ProxyHelper.TOR;
1504 // Apply the proxy mode.
1507 // Consume the event.
1509 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1510 // Update the proxy mode.
1511 proxyMode = ProxyHelper.I2P;
1513 // Apply the proxy mode.
1516 // Consume the event.
1518 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1519 // Update the proxy mode.
1520 proxyMode = ProxyHelper.CUSTOM;
1522 // Apply the proxy mode.
1525 // Consume the event.
1527 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1528 // Update the user agent.
1529 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1531 // Reload the current WebView.
1532 currentWebView.reload();
1534 // Consume the event.
1536 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1537 // Update the user agent.
1538 currentWebView.getSettings().setUserAgentString("");
1540 // Reload the current WebView.
1541 currentWebView.reload();
1543 // Consume the event.
1545 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1546 // Update the user agent.
1547 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1549 // Reload the current WebView.
1550 currentWebView.reload();
1552 // Consume the event.
1554 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1555 // Update the user agent.
1556 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1558 // Reload the current WebView.
1559 currentWebView.reload();
1561 // Consume the event.
1563 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1564 // Update the user agent.
1565 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1567 // Reload the current WebView.
1568 currentWebView.reload();
1570 // Consume the event.
1572 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1573 // Update the user agent.
1574 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1576 // Reload the current WebView.
1577 currentWebView.reload();
1579 // Consume the event.
1581 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1582 // Update the user agent.
1583 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1585 // Reload the current WebView.
1586 currentWebView.reload();
1588 // Consume the event.
1590 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1591 // Update the user agent.
1592 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1594 // Reload the current WebView.
1595 currentWebView.reload();
1597 // Consume the event.
1599 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1600 // Update the user agent.
1601 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1603 // Reload the current WebView.
1604 currentWebView.reload();
1606 // Consume the event.
1608 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1609 // Update the user agent.
1610 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1612 // Reload the current WebView.
1613 currentWebView.reload();
1615 // Consume the event.
1617 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1618 // Update the user agent.
1619 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1621 // Reload the current WebView.
1622 currentWebView.reload();
1624 // Consume the event.
1626 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1627 // Update the user agent.
1628 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1630 // Reload the current WebView.
1631 currentWebView.reload();
1633 // Consume the event.
1635 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1636 // Update the user agent.
1637 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1639 // Reload the current WebView.
1640 currentWebView.reload();
1642 // Consume the event.
1644 } else if (menuItemId == R.id.font_size) { // Font size.
1645 // Instantiate the font size dialog.
1646 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1648 // Show the font size dialog.
1649 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1651 // Consume the event.
1653 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1654 // Toggle the stored status of swipe to refresh.
1655 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1657 // Update the swipe refresh layout.
1658 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1659 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1660 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1661 } else { // Swipe to refresh is disabled.
1662 // Disable the swipe refresh layout.
1663 swipeRefreshLayout.setEnabled(false);
1666 // Consume the event.
1668 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1669 // Toggle the viewport.
1670 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1672 // Consume the event.
1674 } else if (menuItemId == R.id.display_images) { // Display images.
1675 // Toggle the displaying of images.
1676 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1677 // Disable loading of images.
1678 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1680 // Reload the website to remove existing images.
1681 currentWebView.reload();
1682 } else { // Images are not currently loaded automatically.
1683 // Enable loading of images. Missing images will be loaded without the need for a reload.
1684 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1687 // Consume the event.
1689 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1690 // Check to see if dark WebView is supported by this WebView.
1691 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1692 // Toggle the dark WebView setting.
1693 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1694 // Turn off dark WebView.
1695 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1696 } else { // Dark WebView is currently disabled.
1697 // Turn on dark WebView.
1698 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1702 // Consume the event.
1704 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1705 // Get a handle for the views.
1706 Toolbar toolbar = findViewById(R.id.toolbar);
1707 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1708 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1710 // Set the minimum height of the find on page linear layout to match the toolbar.
1711 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1713 // Hide the toolbar.
1714 toolbar.setVisibility(View.GONE);
1716 // Show the find on page linear layout.
1717 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1719 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1720 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1721 findOnPageEditText.postDelayed(() -> {
1722 // Set the focus on the find on page edit text.
1723 findOnPageEditText.requestFocus();
1725 // Get a handle for the input method manager.
1726 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1728 // Remove the lint warning below that the input method manager might be null.
1729 assert inputMethodManager != null;
1731 // Display the keyboard. `0` sets no input flags.
1732 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1735 // Consume the event.
1737 } else if (menuItemId == R.id.print) { // Print.
1738 // Get a print manager instance.
1739 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1741 // Remove the lint error below that print manager might be null.
1742 assert printManager != null;
1744 // Create a print document adapter from the current WebView.
1745 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1747 // Print the document.
1748 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1750 // Consume the event.
1752 } else if (menuItemId == R.id.save_url) { // Save URL.
1753 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1754 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1755 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1757 // Consume the event.
1759 } else if (menuItemId == R.id.save_image) { // Save image.
1760 // Instantiate the save dialog.
1761 DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_IMAGE, null, null, getString(R.string.webpage_png), null,
1764 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1765 saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1767 // Consume the event.
1769 } else if (menuItemId == R.id.save_archive) {
1772 // Create an MHT file.
1773 File mhtFile = File.createTempFile("mht_file", ".mht", getCacheDir());
1775 // Populate the MHT file.
1776 currentWebView.saveWebArchive(mhtFile.toString());
1778 // Check the file length.
1779 Log.i("MHT", "MHT file size: " + mhtFile.length());
1780 } catch (Exception exception){
1781 Log.i("MHT", "MHT exception: " + exception.toString());
1787 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1788 // Instantiate the create home screen shortcut dialog.
1789 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1790 currentWebView.getFavoriteOrDefaultIcon());
1792 // Show the create home screen shortcut dialog.
1793 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1795 // Consume the event.
1797 } else if (menuItemId == R.id.view_source) { // View source.
1798 // Create an intent to launch the view source activity.
1799 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1801 // Add the variables to the intent.
1802 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1803 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1806 startActivity(viewSourceIntent);
1808 // Consume the event.
1810 } else if (menuItemId == R.id.share_url) { // Share URL.
1811 // Setup the share string.
1812 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1814 // Create the share intent.
1815 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1817 // Add the share string to the intent.
1818 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1820 // Set the MIME type.
1821 shareIntent.setType("text/plain");
1823 // Set the intent to open in a new task.
1824 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1827 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1829 // Consume the event.
1831 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1832 // Open the URL with an outside app.
1833 openWithApp(currentWebView.getUrl());
1835 // Consume the event.
1837 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1838 // Open the URL with an outside browser.
1839 openWithBrowser(currentWebView.getUrl());
1841 // Consume the event.
1843 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1844 // Check if domain settings currently exist.
1845 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1846 // Reapply the domain settings on returning to `MainWebViewActivity`.
1847 reapplyDomainSettingsOnRestart = true;
1849 // Create an intent to launch the domains activity.
1850 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1852 // Add the extra information to the intent.
1853 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1854 domainsIntent.putExtra("close_on_back", true);
1855 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1857 // Get the current certificate.
1858 SslCertificate sslCertificate = currentWebView.getCertificate();
1860 // Check to see if the SSL certificate is populated.
1861 if (sslCertificate != null) {
1862 // Extract the certificate to strings.
1863 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1864 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1865 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1866 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1867 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1868 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1869 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1870 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1872 // Add the certificate to the intent.
1873 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1874 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1875 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1876 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1877 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1878 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1879 domainsIntent.putExtra("ssl_start_date", startDateLong);
1880 domainsIntent.putExtra("ssl_end_date", endDateLong);
1883 // Check to see if the current IP addresses have been received.
1884 if (currentWebView.hasCurrentIpAddresses()) {
1885 // Add the current IP addresses to the intent.
1886 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1890 startActivity(domainsIntent);
1891 } else { // Add a new domain.
1892 // Apply the new domain settings on returning to `MainWebViewActivity`.
1893 reapplyDomainSettingsOnRestart = true;
1895 // Get the current domain
1896 Uri currentUri = Uri.parse(currentWebView.getUrl());
1897 String currentDomain = currentUri.getHost();
1899 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1900 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1902 // Create the domain and store the database ID.
1903 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1905 // Create an intent to launch the domains activity.
1906 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1908 // Add the extra information to the intent.
1909 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1910 domainsIntent.putExtra("close_on_back", true);
1911 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1913 // Get the current certificate.
1914 SslCertificate sslCertificate = currentWebView.getCertificate();
1916 // Check to see if the SSL certificate is populated.
1917 if (sslCertificate != null) {
1918 // Extract the certificate to strings.
1919 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1920 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1921 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1922 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1923 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1924 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1925 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1926 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1928 // Add the certificate to the intent.
1929 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1930 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1931 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1932 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1933 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1934 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1935 domainsIntent.putExtra("ssl_start_date", startDateLong);
1936 domainsIntent.putExtra("ssl_end_date", endDateLong);
1939 // Check to see if the current IP addresses have been received.
1940 if (currentWebView.hasCurrentIpAddresses()) {
1941 // Add the current IP addresses to the intent.
1942 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1946 startActivity(domainsIntent);
1949 // Consume the event.
1951 } else if (menuItemId == R.id.ad_consent) { // Ad consent.
1952 // Instantiate the ad consent dialog.
1953 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1955 // Display the ad consent dialog.
1956 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1958 // Consume the event.
1960 } else { // There is no match with the options menu. Pass the event up to the parent method.
1961 // Don't consume the event.
1962 return super.onOptionsItemSelected(menuItem);
1966 // removeAllCookies is deprecated, but it is required for API < 21.
1968 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1969 // Get a handle for the shared preferences.
1970 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1972 // Get the menu item ID.
1973 int menuItemId = menuItem.getItemId();
1975 // Run the commands that correspond to the selected menu item.
1976 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
1977 // Clear and exit Privacy Browser.
1979 } else if (menuItemId == R.id.home) { // Home.
1980 // Load the homepage.
1981 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1982 } else if (menuItemId == R.id.back) { // Back.
1983 // Check if the WebView can go back.
1984 if (currentWebView.canGoBack()) {
1985 // Get the current web back forward list.
1986 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1988 // Get the previous entry URL.
1989 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1991 // Apply the domain settings.
1992 applyDomainSettings(currentWebView, previousUrl, false, false, false);
1994 // Load the previous website in the history.
1995 currentWebView.goBack();
1997 } else if (menuItemId == R.id.forward) { // Forward.
1998 // Check if the WebView can go forward.
1999 if (currentWebView.canGoForward()) {
2000 // Get the current web back forward list.
2001 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2003 // Get the next entry URL.
2004 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2006 // Apply the domain settings.
2007 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2009 // Load the next website in the history.
2010 currentWebView.goForward();
2012 } else if (menuItemId == R.id.history) { // History.
2013 // Instantiate the URL history dialog.
2014 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2016 // Show the URL history dialog.
2017 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2018 } else if (menuItemId == R.id.open) { // Open.
2019 // Instantiate the open file dialog.
2020 DialogFragment openDialogFragment = new OpenDialog();
2022 // Show the open file dialog.
2023 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2024 } else if (menuItemId == R.id.requests) { // Requests.
2025 // Populate the resource requests.
2026 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2028 // Create an intent to launch the Requests activity.
2029 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2031 // Add the block third-party requests status to the intent.
2032 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2035 startActivity(requestsIntent);
2036 } else if (menuItemId == R.id.downloads) { // Downloads.
2037 // Launch the system Download Manager.
2038 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2040 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2041 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2044 startActivity(downloadManagerIntent);
2045 } else if (menuItemId == R.id.domains) { // Domains.
2046 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2047 reapplyDomainSettingsOnRestart = true;
2049 // Launch the domains activity.
2050 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2052 // Add the extra information to the intent.
2053 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2055 // Get the current certificate.
2056 SslCertificate sslCertificate = currentWebView.getCertificate();
2058 // Check to see if the SSL certificate is populated.
2059 if (sslCertificate != null) {
2060 // Extract the certificate to strings.
2061 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2062 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2063 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2064 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2065 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2066 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2067 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2068 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2070 // Add the certificate to the intent.
2071 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2072 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2073 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2074 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2075 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2076 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2077 domainsIntent.putExtra("ssl_start_date", startDateLong);
2078 domainsIntent.putExtra("ssl_end_date", endDateLong);
2081 // Check to see if the current IP addresses have been received.
2082 if (currentWebView.hasCurrentIpAddresses()) {
2083 // Add the current IP addresses to the intent.
2084 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2088 startActivity(domainsIntent);
2089 } else if (menuItemId == R.id.settings) { // Settings.
2090 // Set the flag to reapply app settings on restart when returning from Settings.
2091 reapplyAppSettingsOnRestart = true;
2093 // Set the flag to reapply the domain settings on restart when returning from Settings.
2094 reapplyDomainSettingsOnRestart = true;
2096 // Launch the settings activity.
2097 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2098 startActivity(settingsIntent);
2099 } else if (menuItemId == R.id.import_export) { // Import/Export.
2100 // Create an intent to launch the import/export activity.
2101 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2104 startActivity(importExportIntent);
2105 } else if (menuItemId == R.id.logcat) { // Logcat.
2106 // Create an intent to launch the logcat activity.
2107 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2110 startActivity(logcatIntent);
2111 } else if (menuItemId == R.id.guide) { // Guide.
2112 // Create an intent to launch the guide activity.
2113 Intent guideIntent = new Intent(this, GuideActivity.class);
2116 startActivity(guideIntent);
2117 } else if (menuItemId == R.id.about) { // About
2118 // Create an intent to launch the about activity.
2119 Intent aboutIntent = new Intent(this, AboutActivity.class);
2121 // Create a string array for the blocklist versions.
2122 String[] blocklistVersions = new String[]{easyList.get(0).get(0)[0], easyPrivacy.get(0).get(0)[0], fanboysAnnoyanceList.get(0).get(0)[0], fanboysSocialList.get(0).get(0)[0],
2123 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2125 // Add the blocklist versions to the intent.
2126 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2129 startActivity(aboutIntent);
2132 // Close the navigation drawer.
2133 drawerLayout.closeDrawer(GravityCompat.START);
2138 public void onPostCreate(Bundle savedInstanceState) {
2139 // Run the default commands.
2140 super.onPostCreate(savedInstanceState);
2142 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2143 actionBarDrawerToggle.syncState();
2147 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2148 // Run the default commands.
2149 super.onConfigurationChanged(newConfig);
2151 // Reload the ad for the free flavor if not in full screen mode.
2152 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2153 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2154 View adView = findViewById(R.id.adview);
2156 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2157 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2158 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2161 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
2162 // https://code.google.com/p/android/issues/detail?id=20493#c8
2163 // ActivityCompat.invalidateOptionsMenu(this);
2167 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2168 // Get the hit test result.
2169 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2171 // Define the URL strings.
2172 final String imageUrl;
2173 final String linkUrl;
2175 // Get handles for the system managers.
2176 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2178 // Remove the lint errors below that the clipboard manager might be null.
2179 assert clipboardManager != null;
2181 // Process the link according to the type.
2182 switch (hitTestResult.getType()) {
2183 // `SRC_ANCHOR_TYPE` is a link.
2184 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2185 // Get the target URL.
2186 linkUrl = hitTestResult.getExtra();
2188 // Set the target URL as the title of the `ContextMenu`.
2189 menu.setHeaderTitle(linkUrl);
2191 // Add an Open in New Tab entry.
2192 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2193 // Load the link URL in a new tab and move to it.
2194 addNewTab(linkUrl, true);
2196 // Consume the event.
2200 // Add an Open in Background entry.
2201 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2202 // Load the link URL in a new tab but do not move to it.
2203 addNewTab(linkUrl, false);
2205 // Consume the event.
2209 // Add an Open with App entry.
2210 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2211 openWithApp(linkUrl);
2213 // Consume the event.
2217 // Add an Open with Browser entry.
2218 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2219 openWithBrowser(linkUrl);
2221 // Consume the event.
2225 // Add a Copy URL entry.
2226 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2227 // Save the link URL in a `ClipData`.
2228 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2230 // Set the `ClipData` as the clipboard's primary clip.
2231 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2233 // Consume the event.
2237 // Add a Save URL entry.
2238 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2239 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2240 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2241 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2243 // Consume the event.
2247 // Add an empty Cancel entry, which by default closes the context menu.
2248 menu.add(R.string.cancel);
2251 // `IMAGE_TYPE` is an image.
2252 case WebView.HitTestResult.IMAGE_TYPE:
2253 // Get the image URL.
2254 imageUrl = hitTestResult.getExtra();
2256 // Remove the incorrect lint warning below that the image URL might be null.
2257 assert imageUrl != null;
2259 // Set the context menu title.
2260 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2261 // Truncate the image URL before making it the title.
2262 menu.setHeaderTitle(imageUrl.substring(0, 100));
2263 } else { // The image URL does not contain the full image data.
2264 // Set the image URL as the title of the context menu.
2265 menu.setHeaderTitle(imageUrl);
2268 // Add an Open in New Tab entry.
2269 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2270 // Load the image in a new tab.
2271 addNewTab(imageUrl, true);
2273 // Consume the event.
2277 // Add an Open with App entry.
2278 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2279 // Open the image URL with an external app.
2280 openWithApp(imageUrl);
2282 // Consume the event.
2286 // Add an Open with Browser entry.
2287 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2288 // Open the image URL with an external browser.
2289 openWithBrowser(imageUrl);
2291 // Consume the event.
2295 // Add a View Image entry.
2296 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2297 // Load the image in the current tab.
2298 loadUrl(currentWebView, imageUrl);
2300 // Consume the event.
2304 // Add a Save Image entry.
2305 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2306 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2307 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2308 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2310 // Consume the event.
2314 // Add a Copy URL entry.
2315 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2316 // Save the image URL in a clip data.
2317 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2319 // Set the clip data as the clipboard's primary clip.
2320 clipboardManager.setPrimaryClip(imageTypeClipData);
2322 // Consume the event.
2326 // Add an empty Cancel entry, which by default closes the context menu.
2327 menu.add(R.string.cancel);
2330 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2331 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2332 // Get the image URL.
2333 imageUrl = hitTestResult.getExtra();
2335 // Instantiate a handler.
2336 Handler handler = new Handler();
2338 // Get a message from the handler.
2339 Message message = handler.obtainMessage();
2341 // Request the image details from the last touched node be returned in the message.
2342 currentWebView.requestFocusNodeHref(message);
2344 // Get the link URL from the message data.
2345 linkUrl = message.getData().getString("url");
2347 // Set the link URL as the title of the context menu.
2348 menu.setHeaderTitle(linkUrl);
2350 // Add an Open in New Tab entry.
2351 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2352 // Load the link URL in a new tab and move to it.
2353 addNewTab(linkUrl, true);
2355 // Consume the event.
2359 // Add an Open in Background entry.
2360 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2361 // Lod the link URL in a new tab but do not move to it.
2362 addNewTab(linkUrl, false);
2364 // Consume the event.
2368 // Add an Open Image in New Tab entry.
2369 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2370 // Load the image in a new tab and move to it.
2371 addNewTab(imageUrl, true);
2373 // Consume the event.
2377 // Add an Open with App entry.
2378 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2379 // Open the link URL with an external app.
2380 openWithApp(linkUrl);
2382 // Consume the event.
2386 // Add an Open with Browser entry.
2387 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2388 // Open the link URL with an external browser.
2389 openWithBrowser(linkUrl);
2391 // Consume the event.
2395 // Add a View Image entry.
2396 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2397 // View the image in the current tab.
2398 loadUrl(currentWebView, imageUrl);
2400 // Consume the event.
2404 // Add a Save Image entry.
2405 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2406 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2407 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2408 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2410 // Consume the event.
2414 // Add a Copy URL entry.
2415 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2416 // Save the link URL in a clip data.
2417 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2419 // Set the clip data as the clipboard's primary clip.
2420 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2422 // Consume the event.
2426 // Add a Save URL entry.
2427 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2428 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2429 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2430 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2432 // Consume the event.
2436 // Add an empty Cancel entry, which by default closes the context menu.
2437 menu.add(R.string.cancel);
2440 case WebView.HitTestResult.EMAIL_TYPE:
2441 // Get the target URL.
2442 linkUrl = hitTestResult.getExtra();
2444 // Set the target URL as the title of the `ContextMenu`.
2445 menu.setHeaderTitle(linkUrl);
2447 // Add a Write Email entry.
2448 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2449 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2450 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2452 // Parse the url and set it as the data for the `Intent`.
2453 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2455 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2456 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2460 startActivity(emailIntent);
2461 } catch (ActivityNotFoundException exception) {
2462 // Display a snackbar.
2463 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2466 // Consume the event.
2470 // Add a Copy Email Address entry.
2471 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2472 // Save the email address in a `ClipData`.
2473 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2475 // Set the `ClipData` as the clipboard's primary clip.
2476 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2478 // Consume the event.
2482 // Add an empty Cancel entry, which by default closes the context menu.
2483 menu.add(R.string.cancel);
2489 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2490 // Get a handle for the bookmarks list view.
2491 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2494 Dialog dialog = dialogFragment.getDialog();
2496 // Remove the incorrect lint warning below that the dialog might be null.
2497 assert dialog != null;
2499 // Get the views from the dialog fragment.
2500 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2501 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2503 // Extract the strings from the edit texts.
2504 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2505 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2507 // Create a favorite icon byte array output stream.
2508 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2510 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2511 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2513 // Convert the favorite icon byte array stream to a byte array.
2514 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2516 // Display the new bookmark below the current items in the (0 indexed) list.
2517 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2519 // Create the bookmark.
2520 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2522 // Update the bookmarks cursor with the current contents of this folder.
2523 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2525 // Update the list view.
2526 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2528 // Scroll to the new bookmark.
2529 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2533 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2534 // Get a handle for the bookmarks list view.
2535 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2538 Dialog dialog = dialogFragment.getDialog();
2540 // Remove the incorrect lint warning below that the dialog might be null.
2541 assert dialog != null;
2543 // Get handles for the views in the dialog fragment.
2544 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2545 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2546 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2548 // Get new folder name string.
2549 String folderNameString = folderNameEditText.getText().toString();
2551 // Create a folder icon bitmap.
2552 Bitmap folderIconBitmap;
2554 // Set the folder icon bitmap according to the dialog.
2555 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2556 // Get the default folder icon drawable.
2557 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2559 // Convert the folder icon drawable to a bitmap drawable.
2560 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2562 // Convert the folder icon bitmap drawable to a bitmap.
2563 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2564 } else { // Use the WebView favorite icon.
2565 // Copy the favorite icon bitmap to the folder icon bitmap.
2566 folderIconBitmap = favoriteIconBitmap;
2569 // Create a folder icon byte array output stream.
2570 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2572 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2573 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2575 // Convert the folder icon byte array stream to a byte array.
2576 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2578 // Move all the bookmarks down one in the display order.
2579 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2580 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2581 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2584 // Create the folder, which will be placed at the top of the `ListView`.
2585 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2587 // Update the bookmarks cursor with the current contents of this folder.
2588 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2590 // Update the `ListView`.
2591 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2593 // Scroll to the new folder.
2594 bookmarksListView.setSelection(0);
2598 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2599 // Remove the incorrect lint warning below that the dialog fragment might be null.
2600 assert dialogFragment != null;
2603 Dialog dialog = dialogFragment.getDialog();
2605 // Remove the incorrect lint warning below that the dialog might be null.
2606 assert dialog != null;
2608 // Get handles for the views from the dialog.
2609 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2610 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2611 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2612 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2614 // Get the new folder name.
2615 String newFolderNameString = editFolderNameEditText.getText().toString();
2617 // Check if the favorite icon has changed.
2618 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2619 // Update the name in the database.
2620 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2621 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2622 // Create the new folder icon Bitmap.
2623 Bitmap folderIconBitmap;
2625 // Populate the new folder icon bitmap.
2626 if (defaultFolderIconRadioButton.isChecked()) {
2627 // Get the default folder icon drawable.
2628 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2630 // Convert the folder icon drawable to a bitmap drawable.
2631 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2633 // Convert the folder icon bitmap drawable to a bitmap.
2634 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2635 } else { // Use the `WebView` favorite icon.
2636 // Copy the favorite icon bitmap to the folder icon bitmap.
2637 folderIconBitmap = favoriteIconBitmap;
2640 // Create a folder icon byte array output stream.
2641 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2643 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2644 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2646 // Convert the folder icon byte array stream to a byte array.
2647 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2649 // Update the folder icon in the database.
2650 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2651 } else { // The folder icon and the name have changed.
2652 // Get the new folder icon bitmap.
2653 Bitmap folderIconBitmap;
2654 if (defaultFolderIconRadioButton.isChecked()) {
2655 // Get the default folder icon drawable.
2656 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2658 // Convert the folder icon drawable to a bitmap drawable.
2659 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2661 // Convert the folder icon bitmap drawable to a bitmap.
2662 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2663 } else { // Use the `WebView` favorite icon.
2664 // Copy the favorite icon bitmap to the folder icon bitmap.
2665 folderIconBitmap = favoriteIconBitmap;
2668 // Create a folder icon byte array output stream.
2669 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2671 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2672 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2674 // Convert the folder icon byte array stream to a byte array.
2675 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2677 // Update the folder name and icon in the database.
2678 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2681 // Update the bookmarks cursor with the current contents of this folder.
2682 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2684 // Update the `ListView`.
2685 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2688 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2690 public void onBackPressed() {
2691 // Check the different options for processing `back`.
2692 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2693 // Close the navigation drawer.
2694 drawerLayout.closeDrawer(GravityCompat.START);
2695 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2696 // close the bookmarks drawer.
2697 drawerLayout.closeDrawer(GravityCompat.END);
2698 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2699 // Re-enable the screen timeout.
2700 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2702 // Unset the full screen video flag.
2703 displayingFullScreenVideo = false;
2705 // Remove all the views from the full screen video frame layout.
2706 fullScreenVideoFrameLayout.removeAllViews();
2708 // Hide the full screen video frame layout.
2709 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2711 // Enable the sliding drawers.
2712 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2714 // Show the main content relative layout.
2715 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2717 // Apply the appropriate full screen mode flags.
2718 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2719 // Hide the banner ad in the free flavor.
2720 if (BuildConfig.FLAVOR.contentEquals("free")) {
2721 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2722 View adView = findViewById(R.id.adview);
2724 // Hide the banner ad.
2725 AdHelper.hideAd(adView);
2728 /* Hide the system bars.
2729 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2730 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2731 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2732 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2734 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2735 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2737 // Reload the website if the app bar is hidden. Otherwise, there is some bug in Android that causes the WebView to be entirely black.
2739 // Reload the WebView.
2740 currentWebView.reload();
2742 } else { // Switch to normal viewing mode.
2743 // Remove the `SYSTEM_UI` flags from the root frame layout.
2744 rootFrameLayout.setSystemUiVisibility(0);
2747 // Reload the ad for the free flavor if not in full screen mode.
2748 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2749 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2750 View adView = findViewById(R.id.adview);
2752 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2753 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2755 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2756 // Get the current web back forward list.
2757 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2759 // Get the previous entry URL.
2760 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2762 // Apply the domain settings.
2763 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2766 currentWebView.goBack();
2767 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2768 // Close the current tab.
2770 } else { // There isn't anything to do in Privacy Browser.
2771 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2772 if (Build.VERSION.SDK_INT >= 21) {
2773 finishAndRemoveTask();
2778 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2783 // Process the results of a file browse.
2785 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2786 // Run the default commands.
2787 super.onActivityResult(requestCode, resultCode, returnedIntent);
2789 // Run the commands that correlate to the specified request code.
2790 switch (requestCode) {
2791 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2792 // File uploads only work on API >= 21.
2793 if (Build.VERSION.SDK_INT >= 21) {
2794 // Pass the file to the WebView.
2795 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2799 case BROWSE_OPEN_REQUEST_CODE:
2800 // Don't do anything if the user pressed back from the file picker.
2801 if (resultCode == Activity.RESULT_OK) {
2802 // Get a handle for the open dialog fragment.
2803 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2805 // Only update the file name if the dialog still exists.
2806 if (openDialogFragment != null) {
2807 // Get a handle for the open dialog.
2808 Dialog openDialog = openDialogFragment.getDialog();
2810 // Remove the incorrect lint warning below that the dialog might be null.
2811 assert openDialog != null;
2813 // Get a handle for the file name edit text.
2814 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2816 // Get the file name URI from the intent.
2817 Uri fileNameUri = returnedIntent.getData();
2819 // Get the file name string from the URI.
2820 String fileNameString = fileNameUri.toString();
2822 // Set the file name text.
2823 fileNameEditText.setText(fileNameString);
2825 // Move the cursor to the end of the file name edit text.
2826 fileNameEditText.setSelection(fileNameString.length());
2831 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2832 // Don't do anything if the user pressed back from the file picker.
2833 if (resultCode == Activity.RESULT_OK) {
2834 // Get a handle for the save dialog fragment.
2835 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2837 // Only update the file name if the dialog still exists.
2838 if (saveWebpageDialogFragment != null) {
2839 // Get a handle for the save webpage dialog.
2840 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2842 // Remove the incorrect lint warning below that the dialog might be null.
2843 assert saveWebpageDialog != null;
2845 // Get a handle for the file name edit text.
2846 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2848 // Get the file name URI from the intent.
2849 Uri fileNameUri = returnedIntent.getData();
2851 // Get the file name string from the URI.
2852 String fileNameString = fileNameUri.toString();
2854 // Set the file name text.
2855 fileNameEditText.setText(fileNameString);
2857 // Move the cursor to the end of the file name edit text.
2858 fileNameEditText.setSelection(fileNameString.length());
2865 private void loadUrlFromTextBox() {
2866 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2867 String unformattedUrlString = urlEditText.getText().toString().trim();
2869 // Initialize the formatted URL string.
2872 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2873 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2874 // Load the entire content URL.
2875 url = unformattedUrlString;
2876 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2877 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2878 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2879 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2880 unformattedUrlString = "https://" + unformattedUrlString;
2883 // Initialize `unformattedUrl`.
2884 URL unformattedUrl = null;
2886 // 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.
2888 unformattedUrl = new URL(unformattedUrlString);
2889 } catch (MalformedURLException e) {
2890 e.printStackTrace();
2893 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2894 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2895 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2896 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2897 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2898 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2901 Uri.Builder uri = new Uri.Builder();
2902 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2904 // Decode the URI as a UTF-8 string in.
2906 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2907 } catch (UnsupportedEncodingException exception) {
2908 // Do nothing. The formatted URL string will remain blank.
2910 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2911 // Create an encoded URL String.
2912 String encodedUrlString;
2914 // Sanitize the search input.
2916 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2917 } catch (UnsupportedEncodingException exception) {
2918 encodedUrlString = "";
2921 // Add the base search URL.
2922 url = searchURL + encodedUrlString;
2925 // 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.
2926 urlEditText.clearFocus();
2929 loadUrl(currentWebView, url);
2932 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2933 // Sanitize the URL.
2934 url = sanitizeUrl(url);
2936 // Apply the domain settings and load the URL.
2937 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2940 public void findPreviousOnPage(View view) {
2941 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2942 currentWebView.findNext(false);
2945 public void findNextOnPage(View view) {
2946 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2947 currentWebView.findNext(true);
2950 public void closeFindOnPage(View view) {
2951 // Get a handle for the views.
2952 Toolbar toolbar = findViewById(R.id.toolbar);
2953 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2954 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2956 // Delete the contents of `find_on_page_edittext`.
2957 findOnPageEditText.setText(null);
2959 // Clear the highlighted phrases if the WebView is not null.
2960 if (currentWebView != null) {
2961 currentWebView.clearMatches();
2964 // Hide the find on page linear layout.
2965 findOnPageLinearLayout.setVisibility(View.GONE);
2967 // Show the toolbar.
2968 toolbar.setVisibility(View.VISIBLE);
2970 // Get a handle for the input method manager.
2971 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2973 // Remove the lint warning below that the input method manager might be null.
2974 assert inputMethodManager != null;
2976 // Hide the keyboard.
2977 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2981 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2982 // Remove the incorrect lint warning below that the dialog fragment might be null.
2983 assert dialogFragment != null;
2986 Dialog dialog = dialogFragment.getDialog();
2988 // Remove the incorrect lint warning below tha the dialog might be null.
2989 assert dialog != null;
2991 // Get a handle for the font size edit text.
2992 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2994 // Initialize the new font size variable with the current font size.
2995 int newFontSize = currentWebView.getSettings().getTextZoom();
2997 // Get the font size from the edit text.
2999 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
3000 } catch (Exception exception) {
3001 // If the edit text does not contain a valid font size do nothing.
3004 // Apply the new font size.
3005 currentWebView.getSettings().setTextZoom(newFontSize);
3009 public void onOpen(DialogFragment dialogFragment) {
3011 Dialog dialog = dialogFragment.getDialog();
3013 // Remove the incorrect lint warning below that the dialog might be null.
3014 assert dialog != null;
3016 // Get a handle for the file name edit text.
3017 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3019 // Get the file path string.
3020 String openFilePath = fileNameEditText.getText().toString();
3022 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
3023 applyDomainSettings(currentWebView, openFilePath, true, false, false);
3026 currentWebView.loadUrl(openFilePath);
3030 public void onSaveWebpage(int saveType, @Nullable String originalUrlString, DialogFragment dialogFragment) {
3032 Dialog dialog = dialogFragment.getDialog();
3034 // Remove the incorrect lint warning below that the dialog might be null.
3035 assert dialog != null;
3037 // Get a handle for the file name edit text.
3038 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3040 // Get the file path from the edit text.
3041 String saveWebpageFilePath = fileNameEditText.getText().toString();
3043 //Save the webpage according to the save type.
3045 case SaveWebpageDialog.SAVE_URL:
3046 // Get a handle for the dialog URL edit text.
3047 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3049 // Define the save webpage URL.
3050 String saveWebpageUrl;
3053 if ((originalUrlString != null) && originalUrlString.startsWith("data:")) {
3054 // Save the original URL.
3055 saveWebpageUrl = originalUrlString;
3057 // Get the URL from the edit text, which may have been modified.
3058 saveWebpageUrl = dialogUrlEditText.getText().toString();
3062 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3065 case SaveWebpageDialog.SAVE_IMAGE:
3066 // Save the webpage image.
3067 new SaveWebpageImage(this, saveWebpageFilePath, currentWebView).execute();
3072 private void initializeApp() {
3073 // Get a handle for the input method.
3074 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3076 // Remove the lint warning below that the input method manager might be null.
3077 assert inputMethodManager != null;
3079 // Initialize the gray foreground color spans for highlighting the URLs. The deprecated `getResources()` must be used until API >= 23.
3080 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3081 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3083 // Get the current theme status.
3084 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3086 // Set the red color span according to the theme.
3087 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3088 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3090 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
3093 // Remove the formatting from the URL edit text when the user is editing the text.
3094 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3095 if (hasFocus) { // The user is editing the URL text box.
3096 // Remove the highlighting.
3097 urlEditText.getText().removeSpan(redColorSpan);
3098 urlEditText.getText().removeSpan(initialGrayColorSpan);
3099 urlEditText.getText().removeSpan(finalGrayColorSpan);
3100 } else { // The user has stopped editing the URL text box.
3101 // Move to the beginning of the string.
3102 urlEditText.setSelection(0);
3104 // Reapply the highlighting.
3109 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3110 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3111 // If the event is a key-down event on the `enter` button, load the URL.
3112 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3113 // Load the URL into the mainWebView and consume the event.
3114 loadUrlFromTextBox();
3116 // If the enter key was pressed, consume the event.
3119 // If any other key was pressed, do not consume the event.
3124 // Create an Orbot status broadcast receiver.
3125 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3127 public void onReceive(Context context, Intent intent) {
3128 // Store the content of the status message in `orbotStatus`.
3129 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3131 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3132 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3133 // Reset the waiting for proxy status.
3134 waitingForProxy = false;
3136 // Get a handle for the waiting for proxy dialog.
3137 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3139 // Dismiss the waiting for proxy dialog if it is displayed.
3140 if (waitingForProxyDialogFragment != null) {
3141 waitingForProxyDialogFragment.dismiss();
3144 // Reload existing URLs and load any URLs that are waiting for the proxy.
3145 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3146 // Get the WebView tab fragment.
3147 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3149 // Get the fragment view.
3150 View fragmentView = webViewTabFragment.getView();
3152 // Only process the WebViews if they exist.
3153 if (fragmentView != null) {
3154 // Get the nested scroll WebView from the tab fragment.
3155 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3157 // Get the waiting for proxy URL string.
3158 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3160 // Load the pending URL if it exists.
3161 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3163 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3165 // Reset the waiting for proxy URL string.
3166 nestedScrollWebView.resetWaitingForProxyUrlString();
3167 } else { // No URL is waiting to be loaded.
3168 // Reload the existing URL.
3169 nestedScrollWebView.reload();
3177 // Register the Orbot status broadcast receiver on `this` context.
3178 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3180 // Get handles for views that need to be modified.
3181 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3182 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3183 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3184 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3185 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3187 // Update the web view pager every time a tab is modified.
3188 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3190 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3195 public void onPageSelected(int position) {
3196 // Close the find on page bar if it is open.
3197 closeFindOnPage(null);
3199 // Set the current WebView.
3200 setCurrentWebView(position);
3202 // 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.
3203 if (tabLayout.getSelectedTabPosition() != position) {
3204 // Wait until the new tab has been created.
3205 tabLayout.post(() -> {
3206 // Get a handle for the tab.
3207 TabLayout.Tab tab = tabLayout.getTabAt(position);
3209 // Assert that the tab is not null.
3219 public void onPageScrollStateChanged(int state) {
3224 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3225 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3227 public void onTabSelected(TabLayout.Tab tab) {
3228 // Select the same page in the view pager.
3229 webViewPager.setCurrentItem(tab.getPosition());
3233 public void onTabUnselected(TabLayout.Tab tab) {
3238 public void onTabReselected(TabLayout.Tab tab) {
3239 // Instantiate the View SSL Certificate dialog.
3240 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3242 // Display the View SSL Certificate dialog.
3243 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3247 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3248 launchBookmarksActivityFab.setOnClickListener(v -> {
3249 // Get a copy of the favorite icon bitmap.
3250 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3252 // Create a favorite icon byte array output stream.
3253 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3255 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3256 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3258 // Convert the favorite icon byte array stream to a byte array.
3259 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3261 // Create an intent to launch the bookmarks activity.
3262 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3264 // Add the extra information to the intent.
3265 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3266 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3267 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3268 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3271 startActivity(bookmarksIntent);
3274 // Set the create new bookmark folder FAB to display an alert dialog.
3275 createBookmarkFolderFab.setOnClickListener(v -> {
3276 // Create a create bookmark folder dialog.
3277 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3279 // Show the create bookmark folder dialog.
3280 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3283 // Set the create new bookmark FAB to display an alert dialog.
3284 createBookmarkFab.setOnClickListener(view -> {
3285 // Instantiate the create bookmark dialog.
3286 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3288 // Display the create bookmark dialog.
3289 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3292 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3293 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3295 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3300 public void onTextChanged(CharSequence s, int start, int before, int count) {
3305 public void afterTextChanged(Editable s) {
3306 // 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.
3307 if (currentWebView != null) {
3308 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3313 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3314 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3315 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3316 // Hide the soft keyboard.
3317 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3319 // Consume the event.
3321 } else { // A different key was pressed.
3322 // Do not consume the event.
3327 // Implement swipe to refresh.
3328 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3330 // Store the default progress view offsets for use later in `initializeWebView()`.
3331 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3332 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3334 // Set the refresh color scheme according to the theme.
3335 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3336 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
3338 swipeRefreshLayout.setColorSchemeResources(R.color.violet_500);
3341 // Initialize a color background typed value.
3342 TypedValue colorBackgroundTypedValue = new TypedValue();
3344 // Get the color background from the theme.
3345 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3347 // Get the color background int from the typed value.
3348 int colorBackgroundInt = colorBackgroundTypedValue.data;
3350 // Set the swipe refresh background color.
3351 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3353 // The drawer titles identify the drawer layouts in accessibility mode.
3354 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3355 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3357 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3358 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3360 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3361 currentBookmarksFolder = "";
3363 // Load the home folder, which is `""` in the database.
3364 loadBookmarksFolder();
3366 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3367 // Convert the id from long to int to match the format of the bookmarks database.
3368 int databaseId = (int) id;
3370 // Get the bookmark cursor for this ID.
3371 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3373 // Move the bookmark cursor to the first row.
3374 bookmarkCursor.moveToFirst();
3376 // Act upon the bookmark according to the type.
3377 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3378 // Store the new folder name in `currentBookmarksFolder`.
3379 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3381 // Load the new folder.
3382 loadBookmarksFolder();
3383 } else { // The selected bookmark is not a folder.
3384 // Load the bookmark URL.
3385 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3387 // Close the bookmarks drawer.
3388 drawerLayout.closeDrawer(GravityCompat.END);
3391 // Close the `Cursor`.
3392 bookmarkCursor.close();
3395 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3396 // Convert the database ID from `long` to `int`.
3397 int databaseId = (int) id;
3399 // Find out if the selected bookmark is a folder.
3400 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3403 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3404 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3406 // Instantiate the edit folder bookmark dialog.
3407 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3409 // Show the edit folder bookmark dialog.
3410 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3412 // Get the bookmark cursor for this ID.
3413 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3415 // Move the bookmark cursor to the first row.
3416 bookmarkCursor.moveToFirst();
3418 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3419 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3422 // Consume the event.
3426 // The drawer listener is used to update the navigation menu.
3427 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3429 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3433 public void onDrawerOpened(@NonNull View drawerView) {
3437 public void onDrawerClosed(@NonNull View drawerView) {
3438 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3439 actionBarDrawerToggle.syncState();
3443 public void onDrawerStateChanged(int newState) {
3444 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3445 // Update the navigation menu items if the WebView is not null.
3446 if (currentWebView != null) {
3447 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3448 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3449 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3450 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3452 // Hide the keyboard (if displayed).
3453 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3456 // 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.
3457 urlEditText.clearFocus();
3458 currentWebView.clearFocus();
3463 // 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).
3464 customHeaders.put("X-Requested-With", "");
3466 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3467 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3469 // Get a handle for the WebView.
3470 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3472 // Store the default user agent.
3473 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3475 // Destroy the bare WebView.
3476 bareWebView.destroy();
3479 private void applyAppSettings() {
3480 // Get a handle for the shared preferences.
3481 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3483 // Store the values from the shared preferences in variables.
3484 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3485 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3486 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3487 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3488 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3489 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3490 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3491 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3492 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3494 // Apply the saved proxy mode if the app has been restarted.
3495 if (savedProxyMode != null) {
3496 // Apply the saved proxy mode.
3497 proxyMode = savedProxyMode;
3499 // Reset the saved proxy mode.
3500 savedProxyMode = null;
3503 // Get the search string.
3504 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3506 // Set the search string.
3507 if (searchString.equals("Custom URL")) { // A custom search string is used.
3508 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3509 } else { // A custom search string is not used.
3510 searchURL = searchString;
3516 // Set Do Not Track status.
3517 if (doNotTrackEnabled) {
3518 customHeaders.put("DNT", "1");
3520 customHeaders.remove("DNT");
3523 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3524 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3525 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3526 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3527 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3529 // Add the scrolling behavior to the layout parameters.
3531 // Enable scrolling of the app bar.
3532 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3533 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3534 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3535 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3537 // Disable scrolling of the app bar.
3538 swipeRefreshLayoutParams.setBehavior(null);
3539 toolbarLayoutParams.setScrollFlags(0);
3540 findOnPageLayoutParams.setScrollFlags(0);
3541 tabsLayoutParams.setScrollFlags(0);
3543 // Expand the app bar if it is currently collapsed.
3544 appBarLayout.setExpanded(true);
3547 // Apply the modified layout parameters.
3548 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3549 toolbar.setLayoutParams(toolbarLayoutParams);
3550 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3551 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3553 // Set the app bar scrolling for each WebView.
3554 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3555 // Get the WebView tab fragment.
3556 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3558 // Get the fragment view.
3559 View fragmentView = webViewTabFragment.getView();
3561 // Only modify the WebViews if they exist.
3562 if (fragmentView != null) {
3563 // Get the nested scroll WebView from the tab fragment.
3564 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3566 // Set the app bar scrolling.
3567 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3571 // Update the full screen browsing mode settings.
3572 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3573 // Update the visibility of the app bar, which might have changed in the settings.
3575 // Hide the tab linear layout.
3576 tabsLinearLayout.setVisibility(View.GONE);
3578 // Hide the action bar.
3581 // Show the tab linear layout.
3582 tabsLinearLayout.setVisibility(View.VISIBLE);
3584 // Show the action bar.
3588 // Hide the banner ad in the free flavor.
3589 if (BuildConfig.FLAVOR.contentEquals("free")) {
3590 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3591 View adView = findViewById(R.id.adview);
3593 // Hide the banner ad.
3594 AdHelper.hideAd(adView);
3597 /* Hide the system bars.
3598 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3599 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3600 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3601 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3603 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3604 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3605 } else { // Privacy Browser is not in full screen browsing mode.
3606 // 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.
3607 inFullScreenBrowsingMode = false;
3609 // Show the tab linear layout.
3610 tabsLinearLayout.setVisibility(View.VISIBLE);
3612 // Show the action bar.
3615 // Show the banner ad in the free flavor.
3616 if (BuildConfig.FLAVOR.contentEquals("free")) {
3617 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3618 View adView = findViewById(R.id.adview);
3620 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3621 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
3622 AdHelper.initializeAds(adView, getApplicationContext(), this, getSupportFragmentManager(), getString(R.string.ad_unit_id));
3625 // Remove the `SYSTEM_UI` flags from the root frame layout.
3626 rootFrameLayout.setSystemUiVisibility(0);
3631 public void navigateHistory(@NonNull String url, int steps) {
3632 // Apply the domain settings.
3633 applyDomainSettings(currentWebView, url, false, false, false);
3635 // Load the history entry.
3636 currentWebView.goBackOrForward(steps);
3640 public void pinnedErrorGoBack() {
3641 // Get the current web back forward list.
3642 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3644 // Get the previous entry URL.
3645 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3647 // Apply the domain settings.
3648 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3651 currentWebView.goBack();
3654 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3655 @SuppressLint("SetJavaScriptEnabled")
3656 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3657 // Store the current URL.
3658 nestedScrollWebView.setCurrentUrl(url);
3660 // Parse the URL into a URI.
3661 Uri uri = Uri.parse(url);
3663 // Extract the domain from `uri`.
3664 String newHostName = uri.getHost();
3666 // Strings don't like to be null.
3667 if (newHostName == null) {
3671 // 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.
3672 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3673 // Set the new host name as the current domain name.
3674 nestedScrollWebView.setCurrentDomainName(newHostName);
3676 // Reset the ignoring of pinned domain information.
3677 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3679 // Clear any pinned SSL certificate or IP addresses.
3680 nestedScrollWebView.clearPinnedSslCertificate();
3681 nestedScrollWebView.clearPinnedIpAddresses();
3683 // Reset the favorite icon if specified.
3685 // Initialize the favorite icon.
3686 nestedScrollWebView.initializeFavoriteIcon();
3688 // Get the current page position.
3689 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3691 // Get the corresponding tab.
3692 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3694 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3696 // Get the tab custom view.
3697 View tabCustomView = tab.getCustomView();
3699 // Remove the warning below that the tab custom view might be null.
3700 assert tabCustomView != null;
3702 // Get the tab views.
3703 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3704 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3706 // Set the default favorite icon as the favorite icon for this tab.
3707 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3709 // Set the loading title text.
3710 tabTitleTextView.setText(R.string.loading);
3714 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3715 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3717 // Get a full cursor from `domainsDatabaseHelper`.
3718 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3720 // Initialize `domainSettingsSet`.
3721 Set<String> domainSettingsSet = new HashSet<>();
3723 // Get the domain name column index.
3724 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3726 // Populate `domainSettingsSet`.
3727 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3728 // Move `domainsCursor` to the current row.
3729 domainNameCursor.moveToPosition(i);
3731 // Store the domain name in `domainSettingsSet`.
3732 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3735 // Close `domainNameCursor.
3736 domainNameCursor.close();
3738 // Initialize the domain name in database variable.
3739 String domainNameInDatabase = null;
3741 // Check the hostname against the domain settings set.
3742 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3743 // Record the domain name in the database.
3744 domainNameInDatabase = newHostName;
3746 // Set the domain settings applied tracker to true.
3747 nestedScrollWebView.setDomainSettingsApplied(true);
3748 } else { // The hostname is not contained in the domain settings set.
3749 // Set the domain settings applied tracker to false.
3750 nestedScrollWebView.setDomainSettingsApplied(false);
3753 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3754 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3755 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3756 // Set the domain settings applied tracker to true.
3757 nestedScrollWebView.setDomainSettingsApplied(true);
3759 // Store the applied domain names as it appears in the database.
3760 domainNameInDatabase = "*." + newHostName;
3763 // Strip out the lowest subdomain of of the host name.
3764 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3768 // Get a handle for the shared preferences.
3769 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3771 // Store the general preference information.
3772 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3773 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3774 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3775 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3776 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3777 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3779 // Get the WebView theme entry values string array.
3780 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3782 // Get a handle for the cookie manager.
3783 CookieManager cookieManager = CookieManager.getInstance();
3785 // Initialize the user agent array adapter and string array.
3786 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3787 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3789 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3790 // Get a cursor for the current host and move it to the first position.
3791 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3792 currentDomainSettingsCursor.moveToFirst();
3794 // Get the settings from the cursor.
3795 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3796 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3797 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3798 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3799 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3800 // Form data can be removed once the minimum API >= 26.
3801 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3802 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3803 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3804 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3805 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3806 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3807 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3808 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3809 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3810 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3811 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3812 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3813 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3814 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3815 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3816 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3817 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3818 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WEBVIEW_THEME));
3819 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3820 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3821 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3822 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3823 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3824 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3825 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3826 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3827 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3828 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3829 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3831 // Get the pinned SSL date longs.
3832 long pinnedSslStartDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE));
3833 long pinnedSslEndDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE));
3835 // Define the pinned SSL date variables.
3836 Date pinnedSslStartDate;
3837 Date pinnedSslEndDate;
3839 // 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.
3840 if (pinnedSslStartDateLong == 0) {
3841 pinnedSslStartDate = null;
3843 pinnedSslStartDate = new Date(pinnedSslStartDateLong);
3846 // 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.
3847 if (pinnedSslEndDateLong == 0) {
3848 pinnedSslEndDate = null;
3850 pinnedSslEndDate = new Date(pinnedSslEndDateLong);
3853 // Close the current host domain settings cursor.
3854 currentDomainSettingsCursor.close();
3856 // If there is a pinned SSL certificate, store it in the WebView.
3857 if (pinnedSslCertificate) {
3858 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3859 pinnedSslStartDate, pinnedSslEndDate);
3862 // If there is a pinned IP address, store it in the WebView.
3863 if (pinnedIpAddresses) {
3864 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3867 // Apply the cookie domain settings.
3868 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3870 // Set third-party cookies status if API >= 21.
3871 if (Build.VERSION.SDK_INT >= 21) {
3872 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3875 // Apply the form data setting if the API < 26.
3876 if (Build.VERSION.SDK_INT < 26) {
3877 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3880 // Apply the font size.
3881 try { // Try the specified font size to see if it is valid.
3882 if (fontSize == 0) { // Apply the default font size.
3883 // Try to set the font size from the value in the app settings.
3884 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3885 } else { // Apply the font size from domain settings.
3886 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3888 } catch (Exception exception) { // The specified font size is invalid
3889 // Set the font size to be 100%
3890 nestedScrollWebView.getSettings().setTextZoom(100);
3893 // Set the user agent.
3894 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3895 // Get the array position of the default user agent name.
3896 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3898 // Set the user agent according to the system default.
3899 switch (defaultUserAgentArrayPosition) {
3900 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3901 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3902 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3905 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3906 // Set the user agent to `""`, which uses the default value.
3907 nestedScrollWebView.getSettings().setUserAgentString("");
3910 case SETTINGS_CUSTOM_USER_AGENT:
3911 // Set the default custom user agent.
3912 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3916 // Get the user agent string from the user agent data array
3917 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3919 } else { // Set the user agent according to the stored name.
3920 // Get the array position of the user agent name.
3921 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3923 switch (userAgentArrayPosition) {
3924 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3925 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3928 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3929 // Set the user agent to `""`, which uses the default value.
3930 nestedScrollWebView.getSettings().setUserAgentString("");
3934 // Get the user agent string from the user agent data array.
3935 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3939 // Set swipe to refresh.
3940 switch (swipeToRefreshInt) {
3941 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3942 // Store the swipe to refresh status in the nested scroll WebView.
3943 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3945 // Update the swipe refresh layout.
3946 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3947 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3948 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3949 } else { // Swipe to refresh is disabled.
3950 // Disable the swipe refresh layout.
3951 swipeRefreshLayout.setEnabled(false);
3955 case DomainsDatabaseHelper.ENABLED:
3956 // Store the swipe to refresh status in the nested scroll WebView.
3957 nestedScrollWebView.setSwipeToRefresh(true);
3959 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3960 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3963 case DomainsDatabaseHelper.DISABLED:
3964 // Store the swipe to refresh status in the nested scroll WebView.
3965 nestedScrollWebView.setSwipeToRefresh(false);
3967 // Disable swipe to refresh.
3968 swipeRefreshLayout.setEnabled(false);
3971 // Check to see if WebView themes are supported.
3972 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
3973 // Set the WebView theme.
3974 switch (webViewThemeInt) {
3975 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3976 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3977 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
3978 // Turn off the WebView dark mode.
3979 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3980 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
3981 // Turn on the WebView dark mode.
3982 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3983 } else { // The system default theme is selected.
3984 // Get the current system theme status.
3985 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3987 // Set the WebView theme according to the current system theme status.
3988 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
3989 // Turn off the WebView dark mode.
3990 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3991 } else { // The system is in night mode.
3992 // Turn on the WebView dark mode.
3993 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3998 case DomainsDatabaseHelper.LIGHT_THEME:
3999 // Turn off the WebView dark mode.
4000 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4003 case DomainsDatabaseHelper.DARK_THEME:
4004 // Turn on the WebView dark mode.
4005 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4010 // Set the viewport.
4011 switch (wideViewportInt) {
4012 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4013 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4016 case DomainsDatabaseHelper.ENABLED:
4017 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4020 case DomainsDatabaseHelper.DISABLED:
4021 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4025 // Set the loading of webpage images.
4026 switch (displayWebpageImagesInt) {
4027 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4028 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4031 case DomainsDatabaseHelper.ENABLED:
4032 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4035 case DomainsDatabaseHelper.DISABLED:
4036 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4040 // Get the current theme status.
4041 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4043 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4044 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4045 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
4047 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
4049 } else { // The new URL does not have custom domain settings. Load the defaults.
4050 // Store the values from the shared preferences.
4051 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4052 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4053 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4054 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4055 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4056 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4057 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4058 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4059 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4060 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4061 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4062 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4064 // Apply the default first-party cookie setting.
4065 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4067 // Apply the default font size setting.
4069 // Try to set the font size from the value in the app settings.
4070 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4071 } catch (Exception exception) {
4072 // If the app settings value is invalid, set the font size to 100%.
4073 nestedScrollWebView.getSettings().setTextZoom(100);
4076 // Apply the form data setting if the API < 26.
4077 if (Build.VERSION.SDK_INT < 26) {
4078 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4081 // Store the swipe to refresh status in the nested scroll WebView.
4082 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4084 // Update the swipe refresh layout.
4085 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4086 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4087 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4088 } else { // Swipe to refresh is disabled.
4089 // Disable the swipe refresh layout.
4090 swipeRefreshLayout.setEnabled(false);
4093 // Reset the pinned variables.
4094 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4096 // Set third-party cookies status if API >= 21.
4097 if (Build.VERSION.SDK_INT >= 21) {
4098 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4101 // Get the array position of the user agent name.
4102 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4104 // Set the user agent.
4105 switch (userAgentArrayPosition) {
4106 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4107 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4108 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4111 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4112 // Set the user agent to `""`, which uses the default value.
4113 nestedScrollWebView.getSettings().setUserAgentString("");
4116 case SETTINGS_CUSTOM_USER_AGENT:
4117 // Set the default custom user agent.
4118 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4122 // Get the user agent string from the user agent data array
4123 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4126 // Apply the WebView theme if supported by the installed WebView.
4127 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4128 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4129 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4130 // Turn off the WebView dark mode.
4131 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4132 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4133 // Turn on the WebView dark mode.
4134 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4135 } else { // The system default theme is selected.
4136 // Get the current system theme status.
4137 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4139 // Set the WebView theme according to the current system theme status.
4140 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4141 // Turn off the WebView dark mode.
4142 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4143 } else { // The system is in night mode.
4144 // Turn on the WebView dark mode.
4145 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4150 // Set the viewport.
4151 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4153 // Set the loading of webpage images.
4154 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4156 // Set a transparent background on the URL relative layout.
4157 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4160 // Close the domains database helper.
4161 domainsDatabaseHelper.close();
4163 // Update the privacy icons.
4164 updatePrivacyIcons(true);
4167 // Reload the website if returning from the Domains activity.
4168 if (reloadWebsite) {
4169 nestedScrollWebView.reload();
4172 // 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.
4174 nestedScrollWebView.loadUrl(url, customHeaders);
4178 private void applyProxy(boolean reloadWebViews) {
4179 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4180 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4182 // Reset the waiting for proxy tracker.
4183 waitingForProxy = false;
4185 // Get the current theme status.
4186 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4188 // Update the user interface and reload the WebViews if requested.
4189 switch (proxyMode) {
4190 case ProxyHelper.NONE:
4191 // Initialize a color background typed value.
4192 TypedValue colorBackgroundTypedValue = new TypedValue();
4194 // Get the color background from the theme.
4195 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4197 // Get the color background int from the typed value.
4198 int colorBackgroundInt = colorBackgroundTypedValue.data;
4200 // Set the default app bar layout background.
4201 appBarLayout.setBackgroundColor(colorBackgroundInt);
4204 case ProxyHelper.TOR:
4205 // Set the app bar background to indicate proxying through Orbot is enabled.
4206 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4207 appBarLayout.setBackgroundResource(R.color.blue_50);
4209 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4212 // Check to see if Orbot is installed.
4214 // Get the package manager.
4215 PackageManager packageManager = getPackageManager();
4217 // 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.
4218 packageManager.getPackageInfo("org.torproject.android", 0);
4220 // Check to see if the proxy is ready.
4221 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4222 // Set the waiting for proxy status.
4223 waitingForProxy = true;
4225 // Show the waiting for proxy dialog if it isn't already displayed.
4226 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4227 // Get a handle for the waiting for proxy alert dialog.
4228 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4230 // Display the waiting for proxy alert dialog.
4231 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4234 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4235 // Show the Orbot not installed dialog if it is not already displayed.
4236 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4237 // Get a handle for the Orbot not installed alert dialog.
4238 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4240 // Display the Orbot not installed alert dialog.
4241 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4246 case ProxyHelper.I2P:
4247 // Set the app bar background to indicate proxying through Orbot is enabled.
4248 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4249 appBarLayout.setBackgroundResource(R.color.blue_50);
4251 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4254 // Check to see if I2P is installed.
4256 // Get the package manager.
4257 PackageManager packageManager = getPackageManager();
4259 // 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.
4260 packageManager.getPackageInfo("net.i2p.android.router", 0);
4261 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4262 // Sow the I2P not installed dialog if it is not already displayed.
4263 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4264 // Get a handle for the waiting for proxy alert dialog.
4265 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4267 // Display the I2P not installed alert dialog.
4268 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4273 case ProxyHelper.CUSTOM:
4274 // Set the app bar background to indicate proxying through Orbot is enabled.
4275 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4276 appBarLayout.setBackgroundResource(R.color.blue_50);
4278 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4283 // Reload the WebViews if requested and not waiting for the proxy.
4284 if (reloadWebViews && !waitingForProxy) {
4285 // Reload the WebViews.
4286 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4287 // Get the WebView tab fragment.
4288 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4290 // Get the fragment view.
4291 View fragmentView = webViewTabFragment.getView();
4293 // Only reload the WebViews if they exist.
4294 if (fragmentView != null) {
4295 // Get the nested scroll WebView from the tab fragment.
4296 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4298 // Reload the WebView.
4299 nestedScrollWebView.reload();
4305 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4306 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4307 if ((optionsMenu != null) && (currentWebView != null)) {
4308 // Update the privacy icon.
4309 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4310 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4311 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4312 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4313 } else { // All the dangerous features are disabled.
4314 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4317 // Get the current theme status.
4318 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4320 // Update the first-party cookies icon.
4321 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4322 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4323 } else { // First-party cookies are disabled.
4324 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4325 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4327 optionsFirstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4331 // Update the refresh icon.
4332 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4333 // Set the icon according to the theme.
4334 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4335 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4337 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4339 } else { // The stop icon is displayed.
4340 // Set the icon according to the theme.
4341 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4342 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
4344 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
4348 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4349 if (runInvalidateOptionsMenu) {
4350 invalidateOptionsMenu();
4355 private void highlightUrlText() {
4356 // Only highlight the URL text if the box is not currently selected.
4357 if (!urlEditText.hasFocus()) {
4358 // Get the URL string.
4359 String urlString = urlEditText.getText().toString();
4361 // Highlight the URL according to the protocol.
4362 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4363 // De-emphasize everything before the file name.
4364 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4365 } else { // This is a web URL.
4366 // Get the index of the `/` immediately after the domain name.
4367 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4369 // Create a base URL string.
4372 // Get the base URL.
4373 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4374 // Get the base URL.
4375 baseUrl = urlString.substring(0, endOfDomainName);
4376 } else { // There are no characters after the base URL.
4377 // Set the base URL to be the entire URL string.
4378 baseUrl = urlString;
4381 // Get the index of the last `.` in the domain.
4382 int lastDotIndex = baseUrl.lastIndexOf(".");
4384 // Get the index of the penultimate `.` in the domain.
4385 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4387 // Markup the beginning of the URL.
4388 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4389 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4391 // De-emphasize subdomains.
4392 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4393 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4395 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4396 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4397 // De-emphasize the protocol and the additional subdomains.
4398 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4399 } else { // There is only one subdomain in the domain name.
4400 // De-emphasize only the protocol.
4401 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4405 // De-emphasize the text after the domain name.
4406 if (endOfDomainName > 0) {
4407 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4413 private void loadBookmarksFolder() {
4414 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4415 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4417 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4418 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4420 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4421 // Inflate the individual item layout. `false` does not attach it to the root.
4422 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4426 public void bindView(View view, Context context, Cursor cursor) {
4427 // Get handles for the views.
4428 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4429 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4431 // Get the favorite icon byte array from the cursor.
4432 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4434 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4435 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4437 // Display the bitmap in `bookmarkFavoriteIcon`.
4438 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4440 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4441 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4442 bookmarkNameTextView.setText(bookmarkNameString);
4444 // Make the font bold for folders.
4445 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4446 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4447 } else { // Reset the font to default for normal bookmarks.
4448 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4453 // Get a handle for the bookmarks list view.
4454 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4456 // Populate the list view with the adapter.
4457 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4459 // Get a handle for the bookmarks title text view.
4460 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4462 // Set the bookmarks drawer title.
4463 if (currentBookmarksFolder.isEmpty()) {
4464 bookmarksTitleTextView.setText(R.string.bookmarks);
4466 bookmarksTitleTextView.setText(currentBookmarksFolder);
4470 private void openWithApp(String url) {
4471 // Create an open with app intent with `ACTION_VIEW`.
4472 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4474 // Set the URI but not the MIME type. This should open all available apps.
4475 openWithAppIntent.setData(Uri.parse(url));
4477 // Flag the intent to open in a new task.
4478 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4482 // Show the chooser.
4483 startActivity(openWithAppIntent);
4484 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4485 // Show a snackbar with the error.
4486 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4490 private void openWithBrowser(String url) {
4491 // Create an open with browser intent with `ACTION_VIEW`.
4492 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4494 // Set the URI and the MIME type. `"text/html"` should load browser options.
4495 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4497 // Flag the intent to open in a new task.
4498 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4502 // Show the chooser.
4503 startActivity(openWithBrowserIntent);
4504 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4505 // Show a snackbar with the error.
4506 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4510 private String sanitizeUrl(String url) {
4511 // Sanitize Google Analytics.
4512 if (sanitizeGoogleAnalytics) {
4514 if (url.contains("?utm_")) {
4515 url = url.substring(0, url.indexOf("?utm_"));
4519 if (url.contains("&utm_")) {
4520 url = url.substring(0, url.indexOf("&utm_"));
4524 // Sanitize Facebook Click IDs.
4525 if (sanitizeFacebookClickIds) {
4526 // Remove `?fbclid=`.
4527 if (url.contains("?fbclid=")) {
4528 url = url.substring(0, url.indexOf("?fbclid="));
4531 // Remove `&fbclid=`.
4532 if (url.contains("&fbclid=")) {
4533 url = url.substring(0, url.indexOf("&fbclid="));
4536 // Remove `?fbadid=`.
4537 if (url.contains("?fbadid=")) {
4538 url = url.substring(0, url.indexOf("?fbadid="));
4541 // Remove `&fbadid=`.
4542 if (url.contains("&fbadid=")) {
4543 url = url.substring(0, url.indexOf("&fbadid="));
4547 // Sanitize Twitter AMP redirects.
4548 if (sanitizeTwitterAmpRedirects) {
4550 if (url.contains("?amp=1")) {
4551 url = url.substring(0, url.indexOf("?amp=1"));
4555 // Return the sanitized URL.
4559 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4560 // Store the blocklists.
4561 easyList = combinedBlocklists.get(0);
4562 easyPrivacy = combinedBlocklists.get(1);
4563 fanboysAnnoyanceList = combinedBlocklists.get(2);
4564 fanboysSocialList = combinedBlocklists.get(3);
4565 ultraList = combinedBlocklists.get(4);
4566 ultraPrivacy = combinedBlocklists.get(5);
4568 // Check to see if the activity has been restarted with a saved state.
4569 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4570 // Add the first tab.
4571 addNewTab("", true);
4572 } else { // The activity has been restarted.
4573 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4574 for (int i = 0; i < savedStateArrayList.size(); i++) {
4576 tabLayout.addTab(tabLayout.newTab());
4579 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4581 // Remove the lint warning below that the current tab might be null.
4582 assert newTab != null;
4584 // Set a custom view on the new tab.
4585 newTab.setCustomView(R.layout.tab_custom_view);
4587 // Add the new page.
4588 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4591 // Reset the saved state variables.
4592 savedStateArrayList = null;
4593 savedNestedScrollWebViewStateArrayList = null;
4595 // Restore the selected tab position.
4596 if (savedTabPosition == 0) { // The first tab is selected.
4597 // Set the first page as the current WebView.
4598 setCurrentWebView(0);
4599 } else { // the first tab is not selected.
4600 // Move to the selected tab.
4601 webViewPager.setCurrentItem(savedTabPosition);
4604 // Get the intent that started the app.
4605 Intent intent = getIntent();
4607 // Reset the intent. This prevents a duplicate tab from being created on restart.
4608 setIntent(new Intent());
4610 // Get the information from the intent.
4611 String intentAction = intent.getAction();
4612 Uri intentUriData = intent.getData();
4613 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4615 // Determine if this is a web search.
4616 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4618 // 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.
4619 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4620 // Get the shared preferences.
4621 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4623 // Create a URL string.
4626 // If the intent action is a web search, perform the search.
4627 if (isWebSearch) { // The intent is a web search.
4628 // Create an encoded URL string.
4629 String encodedUrlString;
4631 // Sanitize the search input and convert it to a search.
4633 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4634 } catch (UnsupportedEncodingException exception) {
4635 encodedUrlString = "";
4638 // Add the base search URL.
4639 url = searchURL + encodedUrlString;
4640 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4641 // Set the intent data as the URL.
4642 url = intentUriData.toString();
4643 } else { // The intent contains a string, which might be a URL.
4644 // Set the intent string as the URL.
4645 url = intentStringExtra;
4648 // Add a new tab if specified in the preferences.
4649 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4650 // Set the loading new intent flag.
4651 loadingNewIntent = true;
4654 addNewTab(url, true);
4655 } else { // Load the URL in the current tab.
4657 loadUrl(currentWebView, url);
4663 public void addTab(View view) {
4664 // Add a new tab with a blank URL.
4665 addNewTab("", true);
4668 private void addNewTab(String url, boolean moveToTab) {
4669 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4670 urlEditText.clearFocus();
4672 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4673 int newTabNumber = tabLayout.getTabCount();
4676 tabLayout.addTab(tabLayout.newTab());
4679 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4681 // Remove the lint warning below that the current tab might be null.
4682 assert newTab != null;
4684 // Set a custom view on the new tab.
4685 newTab.setCustomView(R.layout.tab_custom_view);
4687 // Add the new WebView page.
4688 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4691 public void closeTab(View view) {
4692 // Run the command according to the number of tabs.
4693 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4694 // Close the current tab.
4696 } else { // There is only one tab open.
4701 private void closeCurrentTab() {
4702 // Get the current tab number.
4703 int currentTabNumber = tabLayout.getSelectedTabPosition();
4705 // Delete the current tab.
4706 tabLayout.removeTabAt(currentTabNumber);
4708 // 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,
4709 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4710 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4711 setCurrentWebView(currentTabNumber);
4715 private void clearAndExit() {
4716 // Get a handle for the shared preferences.
4717 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4719 // Close the bookmarks cursor and database.
4720 bookmarksCursor.close();
4721 bookmarksDatabaseHelper.close();
4723 // Get the status of the clear everything preference.
4724 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4726 // Get a handle for the runtime.
4727 Runtime runtime = Runtime.getRuntime();
4729 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4730 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4731 String privateDataDirectoryString = getApplicationInfo().dataDir;
4734 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4735 // The command to remove cookies changed slightly in API 21.
4736 if (Build.VERSION.SDK_INT >= 21) {
4737 CookieManager.getInstance().removeAllCookies(null);
4739 CookieManager.getInstance().removeAllCookie();
4742 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4744 // Two commands must be used because `Runtime.exec()` does not like `*`.
4745 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4746 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4748 // Wait until the processes have finished.
4749 deleteCookiesProcess.waitFor();
4750 deleteCookiesJournalProcess.waitFor();
4751 } catch (Exception exception) {
4752 // Do nothing if an error is thrown.
4756 // Clear DOM storage.
4757 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4758 // Ask `WebStorage` to clear the DOM storage.
4759 WebStorage webStorage = WebStorage.getInstance();
4760 webStorage.deleteAllData();
4762 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4764 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4765 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4767 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4768 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4769 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4770 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4771 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4773 // Wait until the processes have finished.
4774 deleteLocalStorageProcess.waitFor();
4775 deleteIndexProcess.waitFor();
4776 deleteQuotaManagerProcess.waitFor();
4777 deleteQuotaManagerJournalProcess.waitFor();
4778 deleteDatabaseProcess.waitFor();
4779 } catch (Exception exception) {
4780 // Do nothing if an error is thrown.
4784 // Clear form data if the API < 26.
4785 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4786 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4787 webViewDatabase.clearFormData();
4789 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4791 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4792 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4793 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4795 // Wait until the processes have finished.
4796 deleteWebDataProcess.waitFor();
4797 deleteWebDataJournalProcess.waitFor();
4798 } catch (Exception exception) {
4799 // Do nothing if an error is thrown.
4803 // Clear the logcat.
4804 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4806 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
4807 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4809 // Wait for the process to finish.
4811 } catch (IOException|InterruptedException exception) {
4817 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4818 // Clear the cache from each WebView.
4819 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4820 // Get the WebView tab fragment.
4821 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4823 // Get the WebView fragment view.
4824 View webViewFragmentView = webViewTabFragment.getView();
4826 // Only clear the cache if the WebView exists.
4827 if (webViewFragmentView != null) {
4828 // Get the nested scroll WebView from the tab fragment.
4829 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4831 // Clear the cache for this WebView.
4832 nestedScrollWebView.clearCache(true);
4836 // Manually delete the cache directories.
4838 // Delete the main cache directory.
4839 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4841 // Delete the secondary `Service Worker` cache directory.
4842 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4843 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4845 // Wait until the processes have finished.
4846 deleteCacheProcess.waitFor();
4847 deleteServiceWorkerProcess.waitFor();
4848 } catch (Exception exception) {
4849 // Do nothing if an error is thrown.
4853 // Wipe out each WebView.
4854 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4855 // Get the WebView tab fragment.
4856 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4858 // Get the WebView frame layout.
4859 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4861 // Only wipe out the WebView if it exists.
4862 if (webViewFrameLayout != null) {
4863 // Get the nested scroll WebView from the tab fragment.
4864 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4866 // Clear SSL certificate preferences for this WebView.
4867 nestedScrollWebView.clearSslPreferences();
4869 // Clear the back/forward history for this WebView.
4870 nestedScrollWebView.clearHistory();
4872 // Remove all the views from the frame layout.
4873 webViewFrameLayout.removeAllViews();
4875 // Destroy the internal state of the WebView.
4876 nestedScrollWebView.destroy();
4880 // Clear the custom headers.
4881 customHeaders.clear();
4883 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4884 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4885 if (clearEverything) {
4887 // Delete the folder.
4888 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4890 // Wait until the process has finished.
4891 deleteAppWebviewProcess.waitFor();
4892 } catch (Exception exception) {
4893 // Do nothing if an error is thrown.
4897 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4898 if (Build.VERSION.SDK_INT >= 21) {
4899 finishAndRemoveTask();
4904 // Remove the terminated program from RAM. The status code is `0`.
4908 public void bookmarksBack(View view) {
4909 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
4910 // close the bookmarks drawer.
4911 drawerLayout.closeDrawer(GravityCompat.END);
4912 } else { // A subfolder is displayed.
4913 // Place the former parent folder in `currentFolder`.
4914 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4916 // Load the new folder.
4917 loadBookmarksFolder();
4921 private void setCurrentWebView(int pageNumber) {
4922 // Stop the swipe to refresh indicator if it is running
4923 swipeRefreshLayout.setRefreshing(false);
4925 // Get the WebView tab fragment.
4926 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4928 // Get the fragment view.
4929 View webViewFragmentView = webViewTabFragment.getView();
4931 // Set the current WebView if the fragment view is not null.
4932 if (webViewFragmentView != null) { // The fragment has been populated.
4933 // Store the current WebView.
4934 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4936 // Update the status of swipe to refresh.
4937 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4938 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4939 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4940 } else { // Swipe to refresh is disabled.
4941 // Disable the swipe refresh layout.
4942 swipeRefreshLayout.setEnabled(false);
4945 // Get a handle for the cookie manager.
4946 CookieManager cookieManager = CookieManager.getInstance();
4948 // Set the first-party cookie status.
4949 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4951 // Update the privacy icons. `true` redraws the icons in the app bar.
4952 updatePrivacyIcons(true);
4954 // Get a handle for the input method manager.
4955 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4957 // Remove the lint warning below that the input method manager might be null.
4958 assert inputMethodManager != null;
4960 // Get the current URL.
4961 String url = currentWebView.getUrl();
4963 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4964 if (!loadingNewIntent) { // A new intent is not being loaded.
4965 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4966 // Display the hint in the URL edit text.
4967 urlEditText.setText("");
4969 // Request focus for the URL text box.
4970 urlEditText.requestFocus();
4972 // Display the keyboard.
4973 inputMethodManager.showSoftInput(urlEditText, 0);
4974 } else { // The WebView has a loaded URL.
4975 // Clear the focus from the URL text box.
4976 urlEditText.clearFocus();
4978 // Hide the soft keyboard.
4979 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4981 // Display the current URL in the URL text box.
4982 urlEditText.setText(url);
4984 // Highlight the URL text.
4987 } else { // A new intent is being loaded.
4988 // Reset the loading new intent tracker.
4989 loadingNewIntent = false;
4992 // Set the background to indicate the domain settings status.
4993 if (currentWebView.getDomainSettingsApplied()) {
4994 // Get the current theme status.
4995 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4997 // Set a green background on the URL relative layout to indicate that custom domain settings are being used.
4998 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4999 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
5001 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
5004 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5006 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5007 // Create a handler to set the current WebView.
5008 Handler setCurrentWebViewHandler = new Handler();
5010 // Create a runnable to set the current WebView.
5011 Runnable setCurrentWebWebRunnable = () -> {
5012 // Set the current WebView.
5013 setCurrentWebView(pageNumber);
5016 // Try setting the current WebView again after 100 milliseconds.
5017 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5022 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5023 // Get a handle for the shared preferences.
5024 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5026 // Get the WebView theme.
5027 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5029 // Get the WebView theme entry values string array.
5030 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5032 // Apply the WebView theme if supported by the installed WebView.
5033 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5034 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5035 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5036 // Turn off the WebView dark mode.
5037 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5039 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5040 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5041 nestedScrollWebView.setVisibility(View.VISIBLE);
5042 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5043 // Turn on the WebView dark mode.
5044 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5045 } else { // The system default theme is selected.
5046 // Get the current system theme status.
5047 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5049 // Set the WebView theme according to the current system theme status.
5050 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5051 // Turn off the WebView dark mode.
5052 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5054 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5055 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5056 nestedScrollWebView.setVisibility(View.VISIBLE);
5057 } else { // The system is in night mode.
5058 // Turn on the WebView dark mode.
5059 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5064 // Get a handle for the activity
5065 Activity activity = this;
5067 // Get a handle for the input method manager.
5068 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5070 // Instantiate the blocklist helper.
5071 BlocklistHelper blocklistHelper = new BlocklistHelper();
5073 // Remove the lint warning below that the input method manager might be null.
5074 assert inputMethodManager != null;
5076 // Initialize the favorite icon.
5077 nestedScrollWebView.initializeFavoriteIcon();
5079 // Set the app bar scrolling.
5080 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5082 // Allow pinch to zoom.
5083 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5085 // Hide zoom controls.
5086 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5088 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5089 if (Build.VERSION.SDK_INT >= 21) {
5090 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5093 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5094 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5096 // Explicitly disable geolocation.
5097 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5099 // Create a double-tap gesture detector to toggle full-screen mode.
5100 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5101 // Override `onDoubleTap()`. All other events are handled using the default settings.
5103 public boolean onDoubleTap(MotionEvent event) {
5104 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5105 // Toggle the full screen browsing mode tracker.
5106 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5108 // Toggle the full screen browsing mode.
5109 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5110 // Hide the app bar if specified.
5112 // Close the find on page bar if it is visible.
5113 closeFindOnPage(null);
5115 // Hide the tab linear layout.
5116 tabsLinearLayout.setVisibility(View.GONE);
5118 // Hide the action bar.
5121 // Check to see if the app bar is normally scrolled.
5122 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5123 // Get the swipe refresh layout parameters.
5124 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5126 // Remove the off-screen scrolling layout.
5127 swipeRefreshLayoutParams.setBehavior(null);
5128 } else { // The app bar is not scrolled when it is displayed.
5129 // Remove the padding from the top of the swipe refresh layout.
5130 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5132 // The swipe refresh circle must be moved above the now removed status bar location.
5133 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5137 // Hide the banner ad in the free flavor.
5138 if (BuildConfig.FLAVOR.contentEquals("free")) {
5139 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5140 View adView = findViewById(R.id.adview);
5142 // Hide the banner ad.
5143 AdHelper.hideAd(adView);
5146 /* Hide the system bars.
5147 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5148 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5149 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5150 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5152 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5153 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5154 } else { // Switch to normal viewing mode.
5155 // Show the app bar if it was hidden.
5157 // Show the tab linear layout.
5158 tabsLinearLayout.setVisibility(View.VISIBLE);
5160 // Show the action bar.
5163 // Check to see if the app bar is normally scrolled.
5164 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5165 // Get the swipe refresh layout parameters.
5166 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5168 // Add the off-screen scrolling layout.
5169 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5170 } else { // The app bar is not scrolled when it is displayed.
5171 // The swipe refresh layout must be manually moved below the app bar layout.
5172 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5174 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5175 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5179 // Show the banner ad in the free flavor.
5180 if (BuildConfig.FLAVOR.contentEquals("free")) {
5181 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5182 View adView = findViewById(R.id.adview);
5184 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5185 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5188 // Remove the `SYSTEM_UI` flags from the root frame layout.
5189 rootFrameLayout.setSystemUiVisibility(0);
5192 // Consume the double-tap.
5194 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5200 // Pass all touch events on the WebView through the double-tap gesture detector.
5201 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5202 // Call `performClick()` on the view, which is required for accessibility.
5203 view.performClick();
5205 // Send the event to the gesture detector.
5206 return doubleTapGestureDetector.onTouchEvent(event);
5209 // Register the WebView for a context menu. This is used to see link targets and download images.
5210 registerForContextMenu(nestedScrollWebView);
5212 // Allow the downloading of files.
5213 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5214 // Define a formatted file size string.
5215 String formattedFileSizeString;
5217 // Process the content length if it contains data.
5218 if (contentLength > 0) { // The content length is greater than 0.
5219 // Format the content length as a string.
5220 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5221 } else { // The content length is not greater than 0.
5222 // Set the formatted file size string to be `unknown size`.
5223 formattedFileSizeString = getString(R.string.unknown_size);
5226 // Get the file name from the content disposition.
5227 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5229 // Prevent the dialog from displaying if the app window is not visible.
5230 // The download listener continues to function even when the WebView is paused. Attempting to display a dialog in that state leads to a crash.
5231 while (!activity.getWindow().isActive()) {
5233 // The window is not active. Wait 1 second.
5235 } catch (InterruptedException e) {
5240 // Instantiate the save dialog.
5241 DialogFragment saveDialogFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_URL, downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5242 nestedScrollWebView.getAcceptFirstPartyCookies());
5244 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5245 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5248 // Update the find on page count.
5249 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5250 // Get a handle for `findOnPageCountTextView`.
5251 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5254 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5255 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5256 // Set `findOnPageCountTextView` to `0/0`.
5257 findOnPageCountTextView.setText(R.string.zero_of_zero);
5258 } else if (isDoneCounting) { // There are matches.
5259 // `activeMatchOrdinal` is zero-based.
5260 int activeMatch = activeMatchOrdinal + 1;
5262 // Build the match string.
5263 String matchString = activeMatch + "/" + numberOfMatches;
5265 // Set `findOnPageCountTextView`.
5266 findOnPageCountTextView.setText(matchString);
5271 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5272 // 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.
5273 if (Build.VERSION.SDK_INT >= 23) {
5274 nestedScrollWebView.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
5275 if (nestedScrollWebView.getSwipeToRefresh()) {
5276 // Only enable swipe to refresh if the WebView is scrolled to the top.
5277 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5279 // Disable swipe to refresh.
5280 swipeRefreshLayout.setEnabled(false);
5283 // Reinforce the system UI visibility flags if in full screen browsing mode.
5284 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5285 if (inFullScreenBrowsingMode) {
5286 /* Hide the system bars.
5287 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5288 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5289 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5290 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5292 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5293 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5297 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5298 if (nestedScrollWebView.getSwipeToRefresh()) {
5299 // Only enable swipe to refresh if the WebView is scrolled to the top.
5300 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5302 // Disable swipe to refresh.
5303 swipeRefreshLayout.setEnabled(false);
5307 // Reinforce the system UI visibility flags if in full screen browsing mode.
5308 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5309 if (inFullScreenBrowsingMode) {
5310 /* Hide the system bars.
5311 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5312 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5313 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5314 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5316 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5317 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5322 // Set the web chrome client.
5323 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5324 // Update the progress bar when a page is loading.
5326 public void onProgressChanged(WebView view, int progress) {
5327 // Update the progress bar.
5328 progressBar.setProgress(progress);
5330 // Set the visibility of the progress bar.
5331 if (progress < 100) {
5332 // Show the progress bar.
5333 progressBar.setVisibility(View.VISIBLE);
5335 // Hide the progress bar.
5336 progressBar.setVisibility(View.GONE);
5338 //Stop the swipe to refresh indicator if it is running
5339 swipeRefreshLayout.setRefreshing(false);
5341 // 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.
5342 nestedScrollWebView.setVisibility(View.VISIBLE);
5346 // Set the favorite icon when it changes.
5348 public void onReceivedIcon(WebView view, Bitmap icon) {
5349 // Only update the favorite icon if the website has finished loading.
5350 if (progressBar.getVisibility() == View.GONE) {
5351 // Store the new favorite icon.
5352 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5354 // Get the current page position.
5355 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5357 // Get the current tab.
5358 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5360 // Check to see if the tab has been populated.
5362 // Get the custom view from the tab.
5363 View tabView = tab.getCustomView();
5365 // Check to see if the custom tab view has been populated.
5366 if (tabView != null) {
5367 // Get the favorite icon image view from the tab.
5368 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5370 // Display the favorite icon in the tab.
5371 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5377 // Save a copy of the title when it changes.
5379 public void onReceivedTitle(WebView view, String title) {
5380 // Get the current page position.
5381 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5383 // Get the current tab.
5384 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5386 // Only populate the title text view if the tab has been fully created.
5388 // Get the custom view from the tab.
5389 View tabView = tab.getCustomView();
5391 // Only populate the title text view if the tab view has been fully populated.
5392 if (tabView != null) {
5393 // Get the title text view from the tab.
5394 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5396 // Set the title according to the URL.
5397 if (title.equals("about:blank")) {
5398 // Set the title to indicate a new tab.
5399 tabTitleTextView.setText(R.string.new_tab);
5401 // Set the title as the tab text.
5402 tabTitleTextView.setText(title);
5408 // Enter full screen video.
5410 public void onShowCustomView(View video, CustomViewCallback callback) {
5411 // Set the full screen video flag.
5412 displayingFullScreenVideo = true;
5414 // Pause the ad if this is the free flavor.
5415 if (BuildConfig.FLAVOR.contentEquals("free")) {
5416 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5417 View adView = findViewById(R.id.adview);
5419 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5420 AdHelper.pauseAd(adView);
5423 // Hide the keyboard.
5424 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5426 // Hide the main content relative layout.
5427 mainContentRelativeLayout.setVisibility(View.GONE);
5429 /* Hide the system bars.
5430 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5431 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5432 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5433 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5435 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5436 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5438 // Disable the sliding drawers.
5439 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5441 // Add the video view to the full screen video frame layout.
5442 fullScreenVideoFrameLayout.addView(video);
5444 // Show the full screen video frame layout.
5445 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5447 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5448 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5451 // Exit full screen video.
5453 public void onHideCustomView() {
5454 // Re-enable the screen timeout.
5455 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5457 // Unset the full screen video flag.
5458 displayingFullScreenVideo = false;
5460 // Remove all the views from the full screen video frame layout.
5461 fullScreenVideoFrameLayout.removeAllViews();
5463 // Hide the full screen video frame layout.
5464 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5466 // Enable the sliding drawers.
5467 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5469 // Show the main content relative layout.
5470 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5472 // Apply the appropriate full screen mode flags.
5473 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5474 // Hide the app bar if specified.
5476 // Hide the tab linear layout.
5477 tabsLinearLayout.setVisibility(View.GONE);
5479 // Hide the action bar.
5483 // Hide the banner ad in the free flavor.
5484 if (BuildConfig.FLAVOR.contentEquals("free")) {
5485 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5486 View adView = findViewById(R.id.adview);
5488 // Hide the banner ad.
5489 AdHelper.hideAd(adView);
5492 /* Hide the system bars.
5493 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5494 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5495 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5496 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5498 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5499 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5500 } else { // Switch to normal viewing mode.
5501 // Remove the `SYSTEM_UI` flags from the root frame layout.
5502 rootFrameLayout.setSystemUiVisibility(0);
5505 // Reload the ad for the free flavor if not in full screen mode.
5506 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5507 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5508 View adView = findViewById(R.id.adview);
5510 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5511 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5517 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5518 // Show the file chooser if the device is running API >= 21.
5519 if (Build.VERSION.SDK_INT >= 21) {
5520 // Store the file path callback.
5521 fileChooserCallback = filePathCallback;
5523 // Create an intent to open a chooser based on the file chooser parameters.
5524 Intent fileChooserIntent = fileChooserParams.createIntent();
5526 // Get a handle for the package manager.
5527 PackageManager packageManager = getPackageManager();
5529 // Check to see if the file chooser intent resolves to an installed package.
5530 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5531 // Start the file chooser intent.
5532 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5533 } else { // The file chooser intent will cause a crash.
5534 // Create a generic intent to open a chooser.
5535 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5537 // Request an openable file.
5538 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5540 // Set the file type to everything.
5541 genericFileChooserIntent.setType("*/*");
5543 // Start the generic file chooser intent.
5544 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5551 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5552 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5553 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5555 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5556 // Sanitize the url.
5557 url = sanitizeUrl(url);
5559 // Handle the URL according to the type.
5560 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5561 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5562 loadUrl(nestedScrollWebView, url);
5564 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5565 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5567 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5568 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5569 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5571 // Parse the url and set it as the data for the intent.
5572 emailIntent.setData(Uri.parse(url));
5574 // Open the email program in a new task instead of as part of Privacy Browser.
5575 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5579 startActivity(emailIntent);
5580 } catch (ActivityNotFoundException exception) {
5581 // Display a snackbar.
5582 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5586 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5588 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5589 // Open the dialer and load the phone number, but wait for the user to place the call.
5590 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5592 // Add the phone number to the intent.
5593 dialIntent.setData(Uri.parse(url));
5595 // Open the dialer in a new task instead of as part of Privacy Browser.
5596 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5600 startActivity(dialIntent);
5601 } catch (ActivityNotFoundException exception) {
5602 // Display a snackbar.
5603 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5606 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5608 } else { // Load a system chooser to select an app that can handle the URL.
5609 // Open an app that can handle the URL.
5610 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5612 // Add the URL to the intent.
5613 genericIntent.setData(Uri.parse(url));
5615 // List all apps that can handle the URL instead of just opening the first one.
5616 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5618 // Open the app in a new task instead of as part of Privacy Browser.
5619 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5621 // Start the app or display a snackbar if no app is available to handle the URL.
5623 startActivity(genericIntent);
5624 } catch (ActivityNotFoundException exception) {
5625 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5628 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5633 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5635 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5636 // Check to see if the resource request is for the main URL.
5637 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5638 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5642 // 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.
5643 while (ultraPrivacy == null) {
5644 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5645 synchronized (this) {
5647 // Check to see if the blocklists have been populated after 100 ms.
5649 } catch (InterruptedException exception) {
5655 // Sanitize the URL.
5656 url = sanitizeUrl(url);
5658 // Create an empty web resource response to be used if the resource request is blocked.
5659 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5661 // Reset the whitelist results tracker.
5662 String[] whitelistResultStringArray = null;
5664 // Initialize the third party request tracker.
5665 boolean isThirdPartyRequest = false;
5667 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5668 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5670 // Store a copy of the current domain for use in later requests.
5671 String currentDomain = currentBaseDomain;
5673 // Nobody is happy when comparing null strings.
5674 if ((currentBaseDomain != null) && (url != null)) {
5675 // Convert the request URL to a URI.
5676 Uri requestUri = Uri.parse(url);
5678 // Get the request host name.
5679 String requestBaseDomain = requestUri.getHost();
5681 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5682 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5683 // Determine the current base domain.
5684 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5685 // Remove the first subdomain.
5686 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5689 // Determine the request base domain.
5690 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5691 // Remove the first subdomain.
5692 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5695 // Update the third party request tracker.
5696 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5700 // Get the current WebView page position.
5701 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5703 // Determine if the WebView is currently displayed.
5704 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5706 // Block third-party requests if enabled.
5707 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5708 // Add the result to the resource requests.
5709 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5711 // Increment the blocked requests counters.
5712 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5713 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5715 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5716 if (webViewDisplayed) {
5717 // Updating the UI must be run from the UI thread.
5718 activity.runOnUiThread(() -> {
5719 // Update the menu item titles.
5720 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5722 // Update the options menu if it has been populated.
5723 if (optionsMenu != null) {
5724 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5725 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5726 getString(R.string.block_all_third_party_requests));
5731 // Return an empty web resource response.
5732 return emptyWebResourceResponse;
5735 // Check UltraList if it is enabled.
5736 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5737 // Check the URL against UltraList.
5738 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5740 // Process the UltraList results.
5741 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5742 // Add the result to the resource requests.
5743 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5745 // Increment the blocked requests counters.
5746 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5747 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5749 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5750 if (webViewDisplayed) {
5751 // Updating the UI must be run from the UI thread.
5752 activity.runOnUiThread(() -> {
5753 // Update the menu item titles.
5754 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5756 // Update the options menu if it has been populated.
5757 if (optionsMenu != null) {
5758 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5759 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5764 // The resource request was blocked. Return an empty web resource response.
5765 return emptyWebResourceResponse;
5766 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5767 // Add a whitelist entry to the resource requests array.
5768 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5770 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5775 // Check UltraPrivacy if it is enabled.
5776 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5777 // Check the URL against UltraPrivacy.
5778 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5780 // Process the UltraPrivacy results.
5781 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5782 // Add the result to the resource requests.
5783 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5784 ultraPrivacyResults[5]});
5786 // Increment the blocked requests counters.
5787 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5788 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5790 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5791 if (webViewDisplayed) {
5792 // Updating the UI must be run from the UI thread.
5793 activity.runOnUiThread(() -> {
5794 // Update the menu item titles.
5795 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5797 // Update the options menu if it has been populated.
5798 if (optionsMenu != null) {
5799 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5800 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5805 // The resource request was blocked. Return an empty web resource response.
5806 return emptyWebResourceResponse;
5807 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5808 // Add a whitelist entry to the resource requests array.
5809 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5810 ultraPrivacyResults[5]});
5812 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5817 // Check EasyList if it is enabled.
5818 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
5819 // Check the URL against EasyList.
5820 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5822 // Process the EasyList results.
5823 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5824 // Add the result to the resource requests.
5825 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5827 // Increment the blocked requests counters.
5828 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5829 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5831 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5832 if (webViewDisplayed) {
5833 // Updating the UI must be run from the UI thread.
5834 activity.runOnUiThread(() -> {
5835 // Update the menu item titles.
5836 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5838 // Update the options menu if it has been populated.
5839 if (optionsMenu != null) {
5840 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5841 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5846 // The resource request was blocked. Return an empty web resource response.
5847 return emptyWebResourceResponse;
5848 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5849 // Update the whitelist result string array tracker.
5850 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5854 // Check EasyPrivacy if it is enabled.
5855 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
5856 // Check the URL against EasyPrivacy.
5857 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5859 // Process the EasyPrivacy results.
5860 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5861 // Add the result to the resource requests.
5862 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5863 easyPrivacyResults[5]});
5865 // Increment the blocked requests counters.
5866 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5867 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5869 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5870 if (webViewDisplayed) {
5871 // Updating the UI must be run from the UI thread.
5872 activity.runOnUiThread(() -> {
5873 // Update the menu item titles.
5874 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5876 // Update the options menu if it has been populated.
5877 if (optionsMenu != null) {
5878 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5879 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5884 // The resource request was blocked. Return an empty web resource response.
5885 return emptyWebResourceResponse;
5886 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5887 // Update the whitelist result string array tracker.
5888 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5892 // Check Fanboy’s Annoyance List if it is enabled.
5893 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5894 // Check the URL against Fanboy's Annoyance List.
5895 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5897 // Process the Fanboy's Annoyance List results.
5898 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5899 // Add the result to the resource requests.
5900 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5901 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5903 // Increment the blocked requests counters.
5904 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5905 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5907 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5908 if (webViewDisplayed) {
5909 // Updating the UI must be run from the UI thread.
5910 activity.runOnUiThread(() -> {
5911 // Update the menu item titles.
5912 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5914 // Update the options menu if it has been populated.
5915 if (optionsMenu != null) {
5916 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5917 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5918 getString(R.string.fanboys_annoyance_list));
5923 // The resource request was blocked. Return an empty web resource response.
5924 return emptyWebResourceResponse;
5925 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5926 // Update the whitelist result string array tracker.
5927 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5928 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5930 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5931 // Check the URL against Fanboy's Annoyance List.
5932 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5934 // Process the Fanboy's Social Blocking List results.
5935 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5936 // Add the result to the resource requests.
5937 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5938 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5940 // Increment the blocked requests counters.
5941 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5942 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5944 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5945 if (webViewDisplayed) {
5946 // Updating the UI must be run from the UI thread.
5947 activity.runOnUiThread(() -> {
5948 // Update the menu item titles.
5949 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5951 // Update the options menu if it has been populated.
5952 if (optionsMenu != null) {
5953 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5954 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5955 getString(R.string.fanboys_social_blocking_list));
5960 // The resource request was blocked. Return an empty web resource response.
5961 return emptyWebResourceResponse;
5962 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5963 // Update the whitelist result string array tracker.
5964 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5965 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5969 // Add the request to the log because it hasn't been processed by any of the previous checks.
5970 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5971 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5972 } else { // The request didn't match any blocklist entry. Log it as a default request.
5973 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5976 // The resource request has not been blocked. `return null` loads the requested resource.
5980 // Handle HTTP authentication requests.
5982 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5983 // Store the handler.
5984 nestedScrollWebView.setHttpAuthHandler(handler);
5986 // Instantiate an HTTP authentication dialog.
5987 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5989 // Show the HTTP authentication dialog.
5990 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5994 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5995 // Get the preferences.
5996 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5998 // 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.
5999 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6000 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6001 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6003 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6004 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6006 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6007 appBarHeight = appBarLayout.getHeight();
6009 // The swipe refresh layout must be manually moved below the app bar layout.
6010 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6012 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6013 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6016 // Reset the list of resource requests.
6017 nestedScrollWebView.clearResourceRequests();
6019 // Reset the requests counters.
6020 nestedScrollWebView.resetRequestsCounters();
6022 // Get the current page position.
6023 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6025 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6026 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6027 // Display the formatted URL text.
6028 urlEditText.setText(url);
6030 // Apply text highlighting to `urlTextBox`.
6033 // Hide the keyboard.
6034 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6037 // Reset the list of host IP addresses.
6038 nestedScrollWebView.clearCurrentIpAddresses();
6040 // Get a URI for the current URL.
6041 Uri currentUri = Uri.parse(url);
6043 // Get the IP addresses for the host.
6044 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6046 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6047 if (optionsMenu != null) {
6049 optionsRefreshMenuItem.setTitle(R.string.stop);
6051 // Get the app bar and theme preferences.
6052 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6054 // If the icon is displayed in the AppBar, set it according to the theme.
6055 if (displayAdditionalAppBarIcons) {
6056 // Get the current theme status.
6057 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6059 // Set the stop icon according to the theme.
6060 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6061 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
6063 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
6070 public void onPageFinished(WebView view, String url) {
6071 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6072 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6073 CookieManager.getInstance().flush();
6076 // Update the Refresh menu item if the options menu has been created.
6077 if (optionsMenu != null) {
6078 // Reset the Refresh title.
6079 optionsRefreshMenuItem.setTitle(R.string.refresh);
6081 // Get the app bar and theme preferences.
6082 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6084 // If the icon is displayed in the app bar, reset it according to the theme.
6085 if (displayAdditionalAppBarIcons) {
6086 // Get the current theme status.
6087 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6089 // Set the icon according to the theme.
6090 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6091 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6093 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6098 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6099 if (incognitoModeEnabled) {
6100 // Clear the cache. `true` includes disk files.
6101 nestedScrollWebView.clearCache(true);
6103 // Clear the back/forward history.
6104 nestedScrollWebView.clearHistory();
6106 // Manually delete cache folders.
6108 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6109 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6110 String privateDataDirectoryString = getApplicationInfo().dataDir;
6112 // Delete the main cache directory.
6113 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6115 // Delete the secondary `Service Worker` cache directory.
6116 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6117 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6118 } catch (IOException exception) {
6119 // Do nothing if an error is thrown.
6122 // Clear the logcat.
6124 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6125 Runtime.getRuntime().exec("logcat -b all -c");
6126 } catch (IOException exception) {
6131 // Get the current page position.
6132 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6134 // 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.
6135 String currentUrl = nestedScrollWebView.getUrl();
6137 // Get the current tab.
6138 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6140 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6141 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6142 // Probably some sort of race condition when Privacy Browser is being resumed.
6143 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6144 // Check to see if the URL is `about:blank`.
6145 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6146 // Display the hint in the URL edit text.
6147 urlEditText.setText("");
6149 // Request focus for the URL text box.
6150 urlEditText.requestFocus();
6152 // Display the keyboard.
6153 inputMethodManager.showSoftInput(urlEditText, 0);
6155 // Apply the domain settings. This clears any settings from the previous domain.
6156 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6158 // Only populate the title text view if the tab has been fully created.
6160 // Get the custom view from the tab.
6161 View tabView = tab.getCustomView();
6163 // Remove the incorrect warning below that the current tab view might be null.
6164 assert tabView != null;
6166 // Get the title text view from the tab.
6167 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6169 // Set the title as the tab text.
6170 tabTitleTextView.setText(R.string.new_tab);
6172 } else { // The WebView has loaded a webpage.
6173 // Update the URL edit text if it is not currently being edited.
6174 if (!urlEditText.hasFocus()) {
6175 // 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.
6176 String sanitizedUrl = sanitizeUrl(currentUrl);
6178 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6179 urlEditText.setText(sanitizedUrl);
6181 // Apply text highlighting to the URL.
6185 // Only populate the title text view if the tab has been fully created.
6187 // Get the custom view from the tab.
6188 View tabView = tab.getCustomView();
6190 // Remove the incorrect warning below that the current tab view might be null.
6191 assert tabView != null;
6193 // Get the title text view from the tab.
6194 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6196 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6197 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6203 // Handle SSL Certificate errors.
6205 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6206 // Get the current website SSL certificate.
6207 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6209 // Extract the individual pieces of information from the current website SSL certificate.
6210 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6211 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6212 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6213 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6214 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6215 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6216 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6217 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6219 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6220 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6221 // Get the pinned SSL certificate.
6222 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6224 // Extract the arrays from the array list.
6225 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6226 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6228 // Check if the current SSL certificate matches the pinned certificate.
6229 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6230 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6231 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6232 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6234 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6237 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6238 // Store the SSL error handler.
6239 nestedScrollWebView.setSslErrorHandler(handler);
6241 // Prevent the dialog from displaying if the app window is not visible.
6242 // 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.
6243 while (!activity.getWindow().isActive()) {
6245 // The window is not active. Wait 1 second.
6247 } catch (InterruptedException e) {
6252 // Instantiate an SSL certificate error alert dialog.
6253 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6255 // Show the SSL certificate error dialog.
6256 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6261 // Check to see if the state is being restored.
6262 if (restoringState) { // The state is being restored.
6263 // Resume the nested scroll WebView JavaScript timers.
6264 nestedScrollWebView.resumeTimers();
6265 } else if (pageNumber == 0) { // The first page is being loaded.
6266 // Set this nested scroll WebView as the current WebView.
6267 currentWebView = nestedScrollWebView;
6269 // Initialize the URL to load string.
6270 String urlToLoadString;
6272 // Get the intent that started the app.
6273 Intent launchingIntent = getIntent();
6275 // Reset the intent. This prevents a duplicate tab from being created on restart.
6276 setIntent(new Intent());
6278 // Get the information from the intent.
6279 String launchingIntentAction = launchingIntent.getAction();
6280 Uri launchingIntentUriData = launchingIntent.getData();
6281 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6283 // Parse the launching intent URL.
6284 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6285 // Create an encoded URL string.
6286 String encodedUrlString;
6288 // Sanitize the search input and convert it to a search.
6290 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6291 } catch (UnsupportedEncodingException exception) {
6292 encodedUrlString = "";
6295 // Store the web search as the URL to load.
6296 urlToLoadString = searchURL + encodedUrlString;
6297 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6298 // Store the URI as a URL.
6299 urlToLoadString = launchingIntentUriData.toString();
6300 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6302 urlToLoadString = launchingIntentStringExtra;
6303 } else if (!url.equals("")) { // The activity has been restarted.
6304 // Load the saved URL.
6305 urlToLoadString = url;
6306 } else { // The is no URL in the intent.
6307 // Store the homepage to be loaded.
6308 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6311 // Load the website if not waiting for the proxy.
6312 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6313 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6314 } else { // Load the URL.
6315 loadUrl(nestedScrollWebView, urlToLoadString);
6318 // 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.
6319 // 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.
6320 setIntent(new Intent());
6321 } else { // This is not the first tab.
6323 loadUrl(nestedScrollWebView, url);
6325 // Set the focus and display the keyboard if the URL is blank.
6326 if (url.equals("")) {
6327 // Request focus for the URL text box.
6328 urlEditText.requestFocus();
6330 // Create a display keyboard handler.
6331 Handler displayKeyboardHandler = new Handler();
6333 // Create a display keyboard runnable.
6334 Runnable displayKeyboardRunnable = () -> {
6335 // Display the keyboard.
6336 inputMethodManager.showSoftInput(urlEditText, 0);
6339 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6340 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);