2 * Copyright © 2015-2021 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.annotation.SuppressLint;
25 import android.app.Activity;
26 import android.app.Dialog;
27 import android.app.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.AsyncTask;
49 import android.os.Build;
50 import android.os.Bundle;
51 import android.os.Environment;
52 import android.os.Handler;
53 import android.os.Message;
54 import android.preference.PreferenceManager;
55 import android.print.PrintDocumentAdapter;
56 import android.print.PrintManager;
57 import android.provider.DocumentsContract;
58 import android.text.Editable;
59 import android.text.Spanned;
60 import android.text.TextWatcher;
61 import android.text.style.ForegroundColorSpan;
62 import android.util.Patterns;
63 import android.util.TypedValue;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.ViewGroup;
72 import android.view.WindowManager;
73 import android.view.inputmethod.InputMethodManager;
74 import android.webkit.CookieManager;
75 import android.webkit.HttpAuthHandler;
76 import android.webkit.SslErrorHandler;
77 import android.webkit.ValueCallback;
78 import android.webkit.WebBackForwardList;
79 import android.webkit.WebChromeClient;
80 import android.webkit.WebResourceResponse;
81 import android.webkit.WebSettings;
82 import android.webkit.WebStorage;
83 import android.webkit.WebView;
84 import android.webkit.WebViewClient;
85 import android.webkit.WebViewDatabase;
86 import android.widget.ArrayAdapter;
87 import android.widget.CheckBox;
88 import android.widget.CursorAdapter;
89 import android.widget.EditText;
90 import android.widget.FrameLayout;
91 import android.widget.ImageView;
92 import android.widget.LinearLayout;
93 import android.widget.ListView;
94 import android.widget.ProgressBar;
95 import android.widget.RadioButton;
96 import android.widget.RelativeLayout;
97 import android.widget.TextView;
99 import androidx.annotation.NonNull;
100 import androidx.appcompat.app.ActionBar;
101 import androidx.appcompat.app.ActionBarDrawerToggle;
102 import androidx.appcompat.app.AppCompatActivity;
103 import androidx.appcompat.app.AppCompatDelegate;
104 import androidx.appcompat.widget.Toolbar;
105 import androidx.coordinatorlayout.widget.CoordinatorLayout;
106 import androidx.core.content.res.ResourcesCompat;
107 import androidx.core.view.GravityCompat;
108 import androidx.drawerlayout.widget.DrawerLayout;
109 import androidx.fragment.app.DialogFragment;
110 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
111 import androidx.viewpager.widget.ViewPager;
112 import androidx.webkit.WebSettingsCompat;
113 import androidx.webkit.WebViewFeature;
115 import com.google.android.material.appbar.AppBarLayout;
116 import com.google.android.material.floatingactionbutton.FloatingActionButton;
117 import com.google.android.material.navigation.NavigationView;
118 import com.google.android.material.snackbar.Snackbar;
119 import com.google.android.material.tabs.TabLayout;
121 import com.stoutner.privacybrowser.BuildConfig;
122 import com.stoutner.privacybrowser.R;
123 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
124 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
125 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
126 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
127 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
128 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
129 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
130 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
131 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
132 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
133 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
134 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
135 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
136 import com.stoutner.privacybrowser.dialogs.OpenDialog;
137 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
138 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
139 import com.stoutner.privacybrowser.dialogs.SaveWebpageDialog;
140 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
141 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
142 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
143 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
144 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
145 import com.stoutner.privacybrowser.helpers.AdHelper;
146 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
147 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
148 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
149 import com.stoutner.privacybrowser.helpers.ProxyHelper;
150 import com.stoutner.privacybrowser.views.NestedScrollWebView;
152 import java.io.ByteArrayInputStream;
153 import java.io.ByteArrayOutputStream;
155 import java.io.FileInputStream;
156 import java.io.FileOutputStream;
157 import java.io.IOException;
158 import java.io.InputStream;
159 import java.io.OutputStream;
160 import java.io.UnsupportedEncodingException;
161 import java.net.MalformedURLException;
163 import java.net.URLDecoder;
164 import java.net.URLEncoder;
165 import java.text.NumberFormat;
166 import java.util.ArrayList;
167 import java.util.Date;
168 import java.util.HashMap;
169 import java.util.HashSet;
170 import java.util.List;
171 import java.util.Map;
172 import java.util.Objects;
173 import java.util.Set;
174 import java.util.concurrent.ExecutorService;
175 import java.util.concurrent.Executors;
177 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
178 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
179 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageDialog.SaveWebpageListener, UrlHistoryDialog.NavigateHistoryListener,
180 WebViewTabFragment.NewTabListener {
182 // The executor service handles background tasks. It is accessed from `ViewSourceActivity`.
183 public static ExecutorService executorService = Executors.newFixedThreadPool(4);
185 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
186 public static String orbotStatus = "unknown";
188 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
189 public static WebViewPagerAdapter webViewPagerAdapter;
191 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
192 public static boolean restartFromBookmarksActivity;
194 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
195 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
196 public static String currentBookmarksFolder;
198 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
199 public final static int UNRECOGNIZED_USER_AGENT = -1;
200 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
201 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
202 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
203 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
204 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
206 // Define the start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
207 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
208 public final static int BROWSE_OPEN_REQUEST_CODE = 1;
209 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 2;
211 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
212 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
213 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
214 public static String proxyMode = ProxyHelper.NONE;
216 // Define the saved instance state constants.
217 private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
218 private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
219 private final String SAVED_TAB_POSITION = "saved_tab_position";
220 private final String PROXY_MODE = "proxy_mode";
222 // Define the saved instance state variables.
223 private ArrayList<Bundle> savedStateArrayList;
224 private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
225 private int savedTabPosition;
226 private String savedProxyMode;
228 // Define the class variables.
229 @SuppressWarnings("rawtypes")
230 AsyncTask populateBlocklists;
232 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
233 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
234 private NestedScrollWebView currentWebView;
236 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
237 private final Map<String, String> customHeaders = new HashMap<>();
239 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
240 private String searchURL;
242 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
243 private ArrayList<List<String[]>> easyList;
244 private ArrayList<List<String[]>> easyPrivacy;
245 private ArrayList<List<String[]>> fanboysAnnoyanceList;
246 private ArrayList<List<String[]>> fanboysSocialList;
247 private ArrayList<List<String[]>> ultraList;
248 private ArrayList<List<String[]>> ultraPrivacy;
250 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
251 private String webViewDefaultUserAgent;
253 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
254 private boolean incognitoModeEnabled;
256 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
257 private boolean fullScreenBrowsingModeEnabled;
259 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
260 private boolean inFullScreenBrowsingMode;
262 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
263 private boolean hideAppBar;
264 private boolean scrollAppBar;
266 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
267 private boolean loadingNewIntent;
269 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
270 private boolean reapplyDomainSettingsOnRestart;
272 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
273 private boolean reapplyAppSettingsOnRestart;
275 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
276 private boolean displayingFullScreenVideo;
278 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
279 private BroadcastReceiver orbotStatusBroadcastReceiver;
281 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
282 private boolean waitingForProxy = false;
284 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
285 private ActionBarDrawerToggle actionBarDrawerToggle;
287 // The color spans are used in `onCreate()` and `highlightUrlText()`.
288 private ForegroundColorSpan redColorSpan;
289 private ForegroundColorSpan initialGrayColorSpan;
290 private ForegroundColorSpan finalGrayColorSpan;
292 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
293 // and `loadBookmarksFolder()`.
294 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
296 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
297 private Cursor bookmarksCursor;
299 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
300 private CursorAdapter bookmarksCursorAdapter;
302 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
303 private String oldFolderNameString;
305 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
306 private ValueCallback<Uri[]> fileChooserCallback;
308 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
309 private int appBarHeight;
310 private int defaultProgressViewStartOffset;
311 private int defaultProgressViewEndOffset;
313 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
314 private boolean sanitizeGoogleAnalytics;
315 private boolean sanitizeFacebookClickIds;
316 private boolean sanitizeTwitterAmpRedirects;
318 // Declare the class views.
319 private FrameLayout rootFrameLayout;
320 private DrawerLayout drawerLayout;
321 private RelativeLayout mainContentRelativeLayout;
322 private AppBarLayout appBarLayout;
323 private Toolbar toolbar;
324 private RelativeLayout urlRelativeLayout;
325 private EditText urlEditText;
326 private ActionBar actionBar;
327 private LinearLayout findOnPageLinearLayout;
328 private LinearLayout tabsLinearLayout;
329 private TabLayout tabLayout;
330 private SwipeRefreshLayout swipeRefreshLayout;
331 private ViewPager webViewPager;
332 private FrameLayout fullScreenVideoFrameLayout;
334 // Declare the class menus.
335 private Menu optionsMenu;
337 // Declare the class menu items.
338 private MenuItem navigationBackMenuItem;
339 private MenuItem navigationForwardMenuItem;
340 private MenuItem navigationHistoryMenuItem;
341 private MenuItem navigationRequestsMenuItem;
342 private MenuItem optionsPrivacyMenuItem;
343 private MenuItem optionsRefreshMenuItem;
344 private MenuItem optionsCookiesMenuItem;
345 private MenuItem optionsDomStorageMenuItem;
346 private MenuItem optionsSaveFormDataMenuItem;
347 private MenuItem optionsClearDataMenuItem;
348 private MenuItem optionsClearCookiesMenuItem;
349 private MenuItem optionsClearDomStorageMenuItem;
350 private MenuItem optionsClearFormDataMenuItem;
351 private MenuItem optionsBlocklistsMenuItem;
352 private MenuItem optionsEasyListMenuItem;
353 private MenuItem optionsEasyPrivacyMenuItem;
354 private MenuItem optionsFanboysAnnoyanceListMenuItem;
355 private MenuItem optionsFanboysSocialBlockingListMenuItem;
356 private MenuItem optionsUltraListMenuItem;
357 private MenuItem optionsUltraPrivacyMenuItem;
358 private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
359 private MenuItem optionsProxyMenuItem;
360 private MenuItem optionsProxyNoneMenuItem;
361 private MenuItem optionsProxyTorMenuItem;
362 private MenuItem optionsProxyI2pMenuItem;
363 private MenuItem optionsProxyCustomMenuItem;
364 private MenuItem optionsUserAgentMenuItem;
365 private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
366 private MenuItem optionsUserAgentWebViewDefaultMenuItem;
367 private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
368 private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
369 private MenuItem optionsUserAgentSafariOnIosMenuItem;
370 private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
371 private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
372 private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
373 private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
374 private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
375 private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
376 private MenuItem optionsUserAgentSafariOnMacosMenuItem;
377 private MenuItem optionsUserAgentCustomMenuItem;
378 private MenuItem optionsSwipeToRefreshMenuItem;
379 private MenuItem optionsWideViewportMenuItem;
380 private MenuItem optionsDisplayImagesMenuItem;
381 private MenuItem optionsDarkWebViewMenuItem;
382 private MenuItem optionsFontSizeMenuItem;
383 private MenuItem optionsAddOrEditDomainMenuItem;
386 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
387 @SuppressLint("ClickableViewAccessibility")
388 protected void onCreate(Bundle savedInstanceState) {
389 // Run the default commands.
390 super.onCreate(savedInstanceState);
392 // Check to see if the activity has been restarted.
393 if (savedInstanceState != null) {
394 // Store the saved instance state variables.
395 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
396 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
397 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
398 savedProxyMode = savedInstanceState.getString(PROXY_MODE);
401 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
402 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
404 // Get a handle for the shared preferences.
405 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
407 // Get the screenshot preference.
408 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
409 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
411 // Get the theme entry values string array.
412 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
414 // Set the app theme according to the preference. A switch statement cannot be used because the theme entry values string array is not a compile time constant.
415 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
416 // Apply the light theme.
417 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
418 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
419 // Apply the dark theme.
420 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
421 } else { // The system default theme is selected.
422 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
423 // Follow the system default theme.
424 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
425 } else { // The system default theme is not supported.
426 // Follow the battery saver mode.
427 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
431 // Disable screenshots if not allowed.
432 if (!allowScreenshots) {
433 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
436 // Enable the drawing of the entire webpage. This makes it possible to save a website image. This must be done before anything else happens with the WebView.
437 if (Build.VERSION.SDK_INT >= 21) {
438 WebView.enableSlowWholeDocumentDraw();
442 setTheme(R.style.PrivacyBrowser);
444 // Set the content view.
445 setContentView(R.layout.main_framelayout);
447 // Get handles for the views.
448 rootFrameLayout = findViewById(R.id.root_framelayout);
449 drawerLayout = findViewById(R.id.drawerlayout);
450 mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
451 appBarLayout = findViewById(R.id.appbar_layout);
452 toolbar = findViewById(R.id.toolbar);
453 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
454 tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
455 tabLayout = findViewById(R.id.tablayout);
456 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
457 webViewPager = findViewById(R.id.webviewpager);
458 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
460 // Get a handle for the navigation view.
461 NavigationView navigationView = findViewById(R.id.navigationview);
463 // Get a handle for the navigation menu.
464 Menu navigationMenu = navigationView.getMenu();
466 // Get handles for the navigation menu items.
467 navigationBackMenuItem = navigationMenu.findItem(R.id.back);
468 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
469 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
470 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
472 // Listen for touches on the navigation menu.
473 navigationView.setNavigationItemSelectedListener(this);
475 // Get a handle for the app compat delegate.
476 AppCompatDelegate appCompatDelegate = getDelegate();
478 // Set the support action bar.
479 appCompatDelegate.setSupportActionBar(toolbar);
481 // Get a handle for the action bar.
482 actionBar = appCompatDelegate.getSupportActionBar();
484 // Remove the incorrect lint warning below that the action bar might be null.
485 assert actionBar != null;
487 // Add the custom layout, which shows the URL text bar.
488 actionBar.setCustomView(R.layout.url_app_bar);
489 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
491 // Get handles for the views in the URL app bar.
492 urlRelativeLayout = findViewById(R.id.url_relativelayout);
493 urlEditText = findViewById(R.id.url_edittext);
495 // Create the hamburger icon at the start of the AppBar.
496 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
498 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
499 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
501 // Initialize the web view pager adapter.
502 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
504 // Set the pager adapter on the web view pager.
505 webViewPager.setAdapter(webViewPagerAdapter);
507 // Store up to 100 tabs in memory.
508 webViewPager.setOffscreenPageLimit(100);
510 // Initialize the app.
513 // Apply the app settings from the shared preferences.
516 // Populate the blocklists.
517 populateBlocklists = new PopulateBlocklists(this, this).execute();
521 protected void onNewIntent(Intent intent) {
522 // Run the default commands.
523 super.onNewIntent(intent);
525 // Replace the intent that started the app with this one.
528 // Check to see if the app is being restarted from a saved state.
529 if (savedStateArrayList == null || savedStateArrayList.size() == 0) { // The activity is not being restarted from a saved state.
530 // Get the information from the intent.
531 String intentAction = intent.getAction();
532 Uri intentUriData = intent.getData();
533 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
535 // Determine if this is a web search.
536 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
538 // Only process the URI if it contains data or it is a web search. If the user pressed the desktop icon after the app was already running the URI will be null.
539 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
540 // Exit the full screen video if it is displayed.
541 if (displayingFullScreenVideo) {
542 // Exit full screen video mode.
543 exitFullScreenVideo();
545 // Reload the current WebView. Otherwise, it can display entirely black.
546 currentWebView.reload();
549 // Get the shared preferences.
550 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
552 // Create a URL string.
555 // If the intent action is a web search, perform the search.
556 if (isWebSearch) { // The intent is a web search.
557 // Create an encoded URL string.
558 String encodedUrlString;
560 // Sanitize the search input and convert it to a search.
562 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
563 } catch (UnsupportedEncodingException exception) {
564 encodedUrlString = "";
567 // Add the base search URL.
568 url = searchURL + encodedUrlString;
569 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
570 // Set the intent data as the URL.
571 url = intentUriData.toString();
572 } else { // The intent contains a string, which might be a URL.
573 // Set the intent string as the URL.
574 url = intentStringExtra;
577 // Add a new tab if specified in the preferences.
578 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
579 // Set the loading new intent flag.
580 loadingNewIntent = true;
583 addNewTab(url, true);
584 } else { // Load the URL in the current tab.
586 loadUrl(currentWebView, url);
589 // Close the navigation drawer if it is open.
590 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
591 drawerLayout.closeDrawer(GravityCompat.START);
594 // Close the bookmarks drawer if it is open.
595 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
596 drawerLayout.closeDrawer(GravityCompat.END);
603 public void onRestart() {
604 // Run the default commands.
607 // Apply the app settings if returning from the Settings activity.
608 if (reapplyAppSettingsOnRestart) {
609 // Reset the reapply app settings on restart tracker.
610 reapplyAppSettingsOnRestart = false;
612 // Apply the app settings.
616 // Apply the domain settings if returning from the settings or domains activity.
617 if (reapplyDomainSettingsOnRestart) {
618 // Reset the reapply domain settings on restart tracker.
619 reapplyDomainSettingsOnRestart = false;
621 // Reapply the domain settings for each tab.
622 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
623 // Get the WebView tab fragment.
624 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
626 // Get the fragment view.
627 View fragmentView = webViewTabFragment.getView();
629 // Only reload the WebViews if they exist.
630 if (fragmentView != null) {
631 // Get the nested scroll WebView from the tab fragment.
632 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
634 // Reset the current domain name so the domain settings will be reapplied.
635 nestedScrollWebView.resetCurrentDomainName();
637 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
638 if (nestedScrollWebView.getUrl() != null) {
639 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
645 // Update the bookmarks drawer if returning from the Bookmarks activity.
646 if (restartFromBookmarksActivity) {
647 // Close the bookmarks drawer.
648 drawerLayout.closeDrawer(GravityCompat.END);
650 // Reload the bookmarks drawer.
651 loadBookmarksFolder();
653 // Reset `restartFromBookmarksActivity`.
654 restartFromBookmarksActivity = false;
657 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
658 updatePrivacyIcons(true);
661 // `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.
663 public void onStart() {
664 // Run the default commands.
667 // Resume any WebViews.
668 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
669 // Get the WebView tab fragment.
670 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
672 // Get the fragment view.
673 View fragmentView = webViewTabFragment.getView();
675 // Only resume the WebViews if they exist (they won't when the app is first created).
676 if (fragmentView != null) {
677 // Get the nested scroll WebView from the tab fragment.
678 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
680 // Resume the nested scroll WebView.
681 nestedScrollWebView.onResume();
685 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
686 if (currentWebView != null) {
687 currentWebView.resumeTimers();
690 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
691 if (!proxyMode.equals(ProxyHelper.NONE)) {
695 // Reapply any system UI flags and the ad in the free flavor.
696 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
697 /* Hide the system bars.
698 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
699 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
700 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
701 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
703 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
704 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
705 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
706 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
707 View adView = findViewById(R.id.adview);
710 AdHelper.resumeAd(adView);
714 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
716 public void onStop() {
717 // Run the default commands.
720 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
721 // Get the WebView tab fragment.
722 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
724 // Get the fragment view.
725 View fragmentView = webViewTabFragment.getView();
727 // Only pause the WebViews if they exist (they won't when the app is first created).
728 if (fragmentView != null) {
729 // Get the nested scroll WebView from the tab fragment.
730 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
732 // Pause the nested scroll WebView.
733 nestedScrollWebView.onPause();
737 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
738 if (currentWebView != null) {
739 currentWebView.pauseTimers();
742 // Pause the ad or it will continue to consume resources in the background on the free flavor.
743 if (BuildConfig.FLAVOR.contentEquals("free")) {
744 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
745 View adView = findViewById(R.id.adview);
748 AdHelper.pauseAd(adView);
753 public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
754 // Run the default commands.
755 super.onSaveInstanceState(savedInstanceState);
757 // Create the saved state array lists.
758 ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
759 ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
761 // Get the URLs from each tab.
762 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
763 // Get the WebView tab fragment.
764 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
766 // Get the fragment view.
767 View fragmentView = webViewTabFragment.getView();
769 if (fragmentView != null) {
770 // Get the nested scroll WebView from the tab fragment.
771 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
773 // Create saved state bundle.
774 Bundle savedStateBundle = new Bundle();
776 // Get the current states.
777 nestedScrollWebView.saveState(savedStateBundle);
778 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
780 // Store the saved states in the array lists.
781 savedStateArrayList.add(savedStateBundle);
782 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
786 // Get the current tab position.
787 int currentTabPosition = tabLayout.getSelectedTabPosition();
789 // Store the saved states in the bundle.
790 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
791 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
792 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
793 savedInstanceState.putString(PROXY_MODE, proxyMode);
797 public void onDestroy() {
798 // Unregister the orbot status broadcast receiver if it exists.
799 if (orbotStatusBroadcastReceiver != null) {
800 this.unregisterReceiver(orbotStatusBroadcastReceiver);
803 // Close the bookmarks cursor if it exists.
804 if (bookmarksCursor != null) {
805 bookmarksCursor.close();
808 // Close the bookmarks database if it exists.
809 if (bookmarksDatabaseHelper != null) {
810 bookmarksDatabaseHelper.close();
813 // Stop populating the blocklists if the AsyncTask is running in the background.
814 if (populateBlocklists != null) {
815 populateBlocklists.cancel(true);
818 // Run the default commands.
823 public boolean onCreateOptionsMenu(Menu menu) {
824 // Inflate the menu. This adds items to the action bar if it is present.
825 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
827 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
830 // Get handles for the class menu items.
831 optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
832 optionsRefreshMenuItem = menu.findItem(R.id.refresh);
833 optionsCookiesMenuItem = menu.findItem(R.id.cookies);
834 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
835 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data); // Form data can be removed once the minimum API >= 26.
836 optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
837 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
838 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
839 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
840 optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
841 optionsEasyListMenuItem = menu.findItem(R.id.easylist);
842 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
843 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
844 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
845 optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
846 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
847 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
848 optionsProxyMenuItem = menu.findItem(R.id.proxy);
849 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
850 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
851 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
852 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
853 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
854 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
855 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
856 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
857 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
858 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
859 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
860 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
861 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
862 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
863 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
864 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
865 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
866 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
867 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
868 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
869 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
870 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
871 optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
872 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
874 // Get handles for the method menu items.
875 MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
876 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
878 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
879 updatePrivacyIcons(false);
881 // Only display the form data menu items if the API < 26.
882 optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
883 optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
885 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
886 optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
888 // Only display the dark WebView menu item if API >= 21.
889 optionsDarkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
891 // Only show Ad Consent if this is the free flavor.
892 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
894 // Get the shared preferences.
895 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
897 // Get the dark theme and app bar preferences.
898 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
900 // 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.
901 if (displayAdditionalAppBarIcons) {
902 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
903 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
904 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
905 } else { //Do not display the additional icons.
906 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
907 bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
908 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
911 // Replace Refresh with Stop if a URL is already loading.
912 if (currentWebView != null && currentWebView.getProgress() != 100) {
914 optionsRefreshMenuItem.setTitle(R.string.stop);
916 // Set the icon if it is displayed in the app bar.
917 if (displayAdditionalAppBarIcons) {
918 // Get the current theme status.
919 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
921 // Set the icon according to the current theme status.
922 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
923 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
925 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
935 public boolean onPrepareOptionsMenu(Menu menu) {
936 // Get a handle for the cookie manager.
937 CookieManager cookieManager = CookieManager.getInstance();
939 // Initialize the current user agent string and the font size.
940 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
943 // 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.
944 if (currentWebView != null) {
945 // Set the add or edit domain text.
946 if (currentWebView.getDomainSettingsApplied()) {
947 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
949 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
952 // Get the current user agent from the WebView.
953 currentUserAgent = currentWebView.getSettings().getUserAgentString();
955 // Get the current font size from the
956 fontSize = currentWebView.getSettings().getTextZoom();
958 // Set the status of the menu item checkboxes.
959 optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
960 optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
961 optionsEasyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
962 optionsEasyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
963 optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
964 optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
965 optionsUltraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
966 optionsUltraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
967 optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
968 optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
969 optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
970 optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
972 // Initialize the display names for the blocklists with the number of blocked requests.
973 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
974 optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
975 optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
976 optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
977 optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
978 optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
979 optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
980 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
982 // Enable DOM Storage if JavaScript is enabled.
983 optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
985 // Set the checkbox status for dark WebView if the WebView supports it.
986 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
987 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
991 // Set the cookies menu item checked status.
992 optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
994 // Enable Clear Cookies if there are any.
995 optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
997 // 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`.
998 String privateDataDirectoryString = getApplicationInfo().dataDir;
1000 // Get a count of the number of files in the Local Storage directory.
1001 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1002 int localStorageDirectoryNumberOfFiles = 0;
1003 if (localStorageDirectory.exists()) {
1004 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1005 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1008 // Get a count of the number of files in the IndexedDB directory.
1009 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1010 int indexedDBDirectoryNumberOfFiles = 0;
1011 if (indexedDBDirectory.exists()) {
1012 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1013 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1016 // Enable Clear DOM Storage if there is any.
1017 optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1019 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1020 if (Build.VERSION.SDK_INT < 26) {
1021 // Get the WebView database.
1022 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1024 // Enable the clear form data menu item if there is anything to clear.
1025 optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1028 // Enable Clear Data if any of the submenu items are enabled.
1029 optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1031 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1032 optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1034 // Set the proxy title and check the applied proxy.
1035 switch (proxyMode) {
1036 case ProxyHelper.NONE:
1037 // Set the proxy title.
1038 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1040 // Check the proxy None radio button.
1041 optionsProxyNoneMenuItem.setChecked(true);
1044 case ProxyHelper.TOR:
1045 // Set the proxy title.
1046 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1048 // Check the proxy Tor radio button.
1049 optionsProxyTorMenuItem.setChecked(true);
1052 case ProxyHelper.I2P:
1053 // Set the proxy title.
1054 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1056 // Check the proxy I2P radio button.
1057 optionsProxyI2pMenuItem.setChecked(true);
1060 case ProxyHelper.CUSTOM:
1061 // Set the proxy title.
1062 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1064 // Check the proxy Custom radio button.
1065 optionsProxyCustomMenuItem.setChecked(true);
1069 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1070 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1071 // Update the user agent menu item title.
1072 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1074 // Select the Privacy Browser radio box.
1075 optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1076 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1077 // Update the user agent menu item title.
1078 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1080 // Select the WebView Default radio box.
1081 optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1082 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1083 // Update the user agent menu item title.
1084 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1086 // Select the Firefox on Android radio box.
1087 optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1088 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1089 // Update the user agent menu item title.
1090 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1092 // Select the Chrome on Android radio box.
1093 optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1094 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1095 // Update the user agent menu item title.
1096 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1098 // Select the Safari on iOS radio box.
1099 optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1100 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1101 // Update the user agent menu item title.
1102 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1104 // Select the Firefox on Linux radio box.
1105 optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1106 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1107 // Update the user agent menu item title.
1108 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1110 // Select the Chromium on Linux radio box.
1111 optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1112 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1113 // Update the user agent menu item title.
1114 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1116 // Select the Firefox on Windows radio box.
1117 optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1118 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1119 // Update the user agent menu item title.
1120 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1122 // Select the Chrome on Windows radio box.
1123 optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1124 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1125 // Update the user agent menu item title.
1126 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1128 // Select the Edge on Windows radio box.
1129 optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1130 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1131 // Update the user agent menu item title.
1132 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1134 // Select the Internet on Windows radio box.
1135 optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1136 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1137 // Update the user agent menu item title.
1138 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1140 // Select the Safari on macOS radio box.
1141 optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1142 } else { // Custom user agent.
1143 // Update the user agent menu item title.
1144 optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1146 // Select the Custom radio box.
1147 optionsUserAgentCustomMenuItem.setChecked(true);
1150 // Set the font size title.
1151 optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1153 // Run all the other default commands.
1154 super.onPrepareOptionsMenu(menu);
1156 // Display the menu.
1161 public boolean onOptionsItemSelected(MenuItem menuItem) {
1162 // Get a handle for the shared preferences.
1163 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1165 // Get a handle for the cookie manager.
1166 CookieManager cookieManager = CookieManager.getInstance();
1168 // Get the selected menu item ID.
1169 int menuItemId = menuItem.getItemId();
1171 // Run the commands that correlate to the selected menu item.
1172 if (menuItemId == R.id.javascript) { // JavaScript.
1173 // Toggle the JavaScript status.
1174 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1176 // Update the privacy icon.
1177 updatePrivacyIcons(true);
1179 // Display a `Snackbar`.
1180 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1181 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1182 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1183 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1184 } else { // Privacy mode.
1185 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1188 // Reload the current WebView.
1189 currentWebView.reload();
1191 // Consume the event.
1193 } else if (menuItemId == R.id.refresh) { // Refresh.
1194 // Run the command that correlates to the current status of the menu item.
1195 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1196 // Reload the current WebView.
1197 currentWebView.reload();
1198 } else { // The stop button was pushed.
1199 // Stop the loading of the WebView.
1200 currentWebView.stopLoading();
1203 // Consume the event.
1205 } else if (menuItemId == R.id.bookmarks) { // Bookmarks.
1206 // Open the bookmarks drawer.
1207 drawerLayout.openDrawer(GravityCompat.END);
1209 // Consume the event.
1211 } else if (menuItemId == R.id.cookies) { // Cookies.
1212 // Switch the first-party cookie status.
1213 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1215 // Store the cookie status.
1216 currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1218 // Update the menu checkbox.
1219 menuItem.setChecked(cookieManager.acceptCookie());
1221 // Update the privacy icon.
1222 updatePrivacyIcons(true);
1224 // Display a snackbar.
1225 if (cookieManager.acceptCookie()) { // Cookies are enabled.
1226 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1227 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1228 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1229 } else { // Privacy mode.
1230 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1233 // Reload the current WebView.
1234 currentWebView.reload();
1236 // Consume the event.
1238 } else if (menuItemId == R.id.dom_storage) { // DOM storage.
1239 // Toggle the status of domStorageEnabled.
1240 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1242 // Update the menu checkbox.
1243 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1245 // Update the privacy icon.
1246 updatePrivacyIcons(true);
1248 // Display a snackbar.
1249 if (currentWebView.getSettings().getDomStorageEnabled()) {
1250 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1252 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1255 // Reload the current WebView.
1256 currentWebView.reload();
1258 // Consume the event.
1260 } else if (menuItemId == R.id.save_form_data) { // Form data. This can be removed once the minimum API >= 26.
1261 // Switch the status of saveFormDataEnabled.
1262 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1264 // Update the menu checkbox.
1265 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1267 // Display a snackbar.
1268 if (currentWebView.getSettings().getSaveFormData()) {
1269 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1271 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1274 // Update the privacy icon.
1275 updatePrivacyIcons(true);
1277 // Reload the current WebView.
1278 currentWebView.reload();
1280 // Consume the event.
1282 } else if (menuItemId == R.id.clear_cookies) { // Clear cookies.
1283 // Create a snackbar.
1284 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1285 .setAction(R.string.undo, v -> {
1286 // Do nothing because everything will be handled by `onDismissed()` below.
1288 .addCallback(new Snackbar.Callback() {
1290 public void onDismissed(Snackbar snackbar, int event) {
1291 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1292 // Delete the cookies, which command varies by SDK.
1293 if (Build.VERSION.SDK_INT < 21) {
1294 cookieManager.removeAllCookie();
1296 cookieManager.removeAllCookies(null);
1303 // Consume the event.
1305 } else if (menuItemId == R.id.clear_dom_storage) { // Clear DOM storage.
1306 // Create a snackbar.
1307 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1308 .setAction(R.string.undo, v -> {
1309 // Do nothing because everything will be handled by `onDismissed()` below.
1311 .addCallback(new Snackbar.Callback() {
1313 public void onDismissed(Snackbar snackbar, int event) {
1314 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1315 // Delete the DOM Storage.
1316 WebStorage webStorage = WebStorage.getInstance();
1317 webStorage.deleteAllData();
1319 // Initialize a handler to manually delete the DOM storage files and directories.
1320 Handler deleteDomStorageHandler = new Handler();
1322 // Setup a runnable to manually delete the DOM storage files and directories.
1323 Runnable deleteDomStorageRunnable = () -> {
1325 // Get a handle for the runtime.
1326 Runtime runtime = Runtime.getRuntime();
1328 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1329 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1330 String privateDataDirectoryString = getApplicationInfo().dataDir;
1332 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1333 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1335 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1336 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1337 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1338 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1339 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1341 // Wait for the processes to finish.
1342 deleteLocalStorageProcess.waitFor();
1343 deleteIndexProcess.waitFor();
1344 deleteQuotaManagerProcess.waitFor();
1345 deleteQuotaManagerJournalProcess.waitFor();
1346 deleteDatabasesProcess.waitFor();
1347 } catch (Exception exception) {
1348 // Do nothing if an error is thrown.
1352 // Manually delete the DOM storage files after 200 milliseconds.
1353 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1359 // Consume the event.
1361 } else if (menuItemId == R.id.clear_form_data) { // Clear form data. This can be remove once the minimum API >= 26.
1362 // Create a snackbar.
1363 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1364 .setAction(R.string.undo, v -> {
1365 // Do nothing because everything will be handled by `onDismissed()` below.
1367 .addCallback(new Snackbar.Callback() {
1369 public void onDismissed(Snackbar snackbar, int event) {
1370 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1371 // Get a handle for the webView database.
1372 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1374 // Delete the form data.
1375 webViewDatabase.clearFormData();
1381 // Consume the event.
1383 } else if (menuItemId == R.id.easylist) { // EasyList.
1384 // Toggle the EasyList status.
1385 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1387 // Update the menu checkbox.
1388 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1390 // Reload the current WebView.
1391 currentWebView.reload();
1393 // Consume the event.
1395 } else if (menuItemId == R.id.easyprivacy) { // EasyPrivacy.
1396 // Toggle the EasyPrivacy status.
1397 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1399 // Update the menu checkbox.
1400 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1402 // Reload the current WebView.
1403 currentWebView.reload();
1405 // Consume the event.
1407 } else if (menuItemId == R.id.fanboys_annoyance_list) { // Fanboy's Annoyance List.
1408 // Toggle Fanboy's Annoyance List status.
1409 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1411 // Update the menu checkbox.
1412 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1414 // Update the staus of Fanboy's Social Blocking List.
1415 optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1417 // Reload the current WebView.
1418 currentWebView.reload();
1420 // Consume the event.
1422 } else if (menuItemId == R.id.fanboys_social_blocking_list) { // Fanboy's Social Blocking List.
1423 // Toggle Fanboy's Social Blocking List status.
1424 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1426 // Update the menu checkbox.
1427 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1429 // Reload the current WebView.
1430 currentWebView.reload();
1432 // Consume the event.
1434 } else if (menuItemId == R.id.ultralist) { // UltraList.
1435 // Toggle the UltraList status.
1436 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1438 // Update the menu checkbox.
1439 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1441 // Reload the current WebView.
1442 currentWebView.reload();
1444 // Consume the event.
1446 } else if (menuItemId == R.id.ultraprivacy) { // UltraPrivacy.
1447 // Toggle the UltraPrivacy status.
1448 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1450 // Update the menu checkbox.
1451 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1453 // Reload the current WebView.
1454 currentWebView.reload();
1456 // Consume the event.
1458 } else if (menuItemId == R.id.block_all_third_party_requests) { // Block all third-party requests.
1459 //Toggle the third-party requests blocker status.
1460 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1462 // Update the menu checkbox.
1463 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1465 // Reload the current WebView.
1466 currentWebView.reload();
1468 // Consume the event.
1470 } else if (menuItemId == R.id.proxy_none) { // Proxy - None.
1471 // Update the proxy mode.
1472 proxyMode = ProxyHelper.NONE;
1474 // Apply the proxy mode.
1477 // Consume the event.
1479 } else if (menuItemId == R.id.proxy_tor) { // Proxy - Tor.
1480 // Update the proxy mode.
1481 proxyMode = ProxyHelper.TOR;
1483 // Apply the proxy mode.
1486 // Consume the event.
1488 } else if (menuItemId == R.id.proxy_i2p) { // Proxy - I2P.
1489 // Update the proxy mode.
1490 proxyMode = ProxyHelper.I2P;
1492 // Apply the proxy mode.
1495 // Consume the event.
1497 } else if (menuItemId == R.id.proxy_custom) { // Proxy - Custom.
1498 // Update the proxy mode.
1499 proxyMode = ProxyHelper.CUSTOM;
1501 // Apply the proxy mode.
1504 // Consume the event.
1506 } else if (menuItemId == R.id.user_agent_privacy_browser) { // User Agent - Privacy Browser.
1507 // Update the user agent.
1508 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1510 // Reload the current WebView.
1511 currentWebView.reload();
1513 // Consume the event.
1515 } else if (menuItemId == R.id.user_agent_webview_default) { // User Agent - WebView Default.
1516 // Update the user agent.
1517 currentWebView.getSettings().setUserAgentString("");
1519 // Reload the current WebView.
1520 currentWebView.reload();
1522 // Consume the event.
1524 } else if (menuItemId == R.id.user_agent_firefox_on_android) { // User Agent - Firefox on Android.
1525 // Update the user agent.
1526 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1528 // Reload the current WebView.
1529 currentWebView.reload();
1531 // Consume the event.
1533 } else if (menuItemId == R.id.user_agent_chrome_on_android) { // User Agent - Chrome on Android.
1534 // Update the user agent.
1535 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1537 // Reload the current WebView.
1538 currentWebView.reload();
1540 // Consume the event.
1542 } else if (menuItemId == R.id.user_agent_safari_on_ios) { // User Agent - Safari on iOS.
1543 // Update the user agent.
1544 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1546 // Reload the current WebView.
1547 currentWebView.reload();
1549 // Consume the event.
1551 } else if (menuItemId == R.id.user_agent_firefox_on_linux) { // User Agent - Firefox on Linux.
1552 // Update the user agent.
1553 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1555 // Reload the current WebView.
1556 currentWebView.reload();
1558 // Consume the event.
1560 } else if (menuItemId == R.id.user_agent_chromium_on_linux) { // User Agent - Chromium on Linux.
1561 // Update the user agent.
1562 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1564 // Reload the current WebView.
1565 currentWebView.reload();
1567 // Consume the event.
1569 } else if (menuItemId == R.id.user_agent_firefox_on_windows) { // User Agent - Firefox on Windows.
1570 // Update the user agent.
1571 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1573 // Reload the current WebView.
1574 currentWebView.reload();
1576 // Consume the event.
1578 } else if (menuItemId == R.id.user_agent_chrome_on_windows) { // User Agent - Chrome on Windows.
1579 // Update the user agent.
1580 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1582 // Reload the current WebView.
1583 currentWebView.reload();
1585 // Consume the event.
1587 } else if (menuItemId == R.id.user_agent_edge_on_windows) { // User Agent - Edge on Windows.
1588 // Update the user agent.
1589 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1591 // Reload the current WebView.
1592 currentWebView.reload();
1594 // Consume the event.
1596 } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) { // User Agent - Internet Explorer on Windows.
1597 // Update the user agent.
1598 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1600 // Reload the current WebView.
1601 currentWebView.reload();
1603 // Consume the event.
1605 } else if (menuItemId == R.id.user_agent_safari_on_macos) { // User Agent - Safari on macOS.
1606 // Update the user agent.
1607 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1609 // Reload the current WebView.
1610 currentWebView.reload();
1612 // Consume the event.
1614 } else if (menuItemId == R.id.user_agent_custom) { // User Agent - Custom.
1615 // Update the user agent.
1616 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1618 // Reload the current WebView.
1619 currentWebView.reload();
1621 // Consume the event.
1623 } else if (menuItemId == R.id.font_size) { // Font size.
1624 // Instantiate the font size dialog.
1625 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1627 // Show the font size dialog.
1628 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1630 // Consume the event.
1632 } else if (menuItemId == R.id.swipe_to_refresh) { // Swipe to refresh.
1633 // Toggle the stored status of swipe to refresh.
1634 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1636 // Update the swipe refresh layout.
1637 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1638 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1639 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1640 } else { // Swipe to refresh is disabled.
1641 // Disable the swipe refresh layout.
1642 swipeRefreshLayout.setEnabled(false);
1645 // Consume the event.
1647 } else if (menuItemId == R.id.wide_viewport) { // Wide viewport.
1648 // Toggle the viewport.
1649 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1651 // Consume the event.
1653 } else if (menuItemId == R.id.display_images) { // Display images.
1654 // Toggle the displaying of images.
1655 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1656 // Disable loading of images.
1657 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1659 // Reload the website to remove existing images.
1660 currentWebView.reload();
1661 } else { // Images are not currently loaded automatically.
1662 // Enable loading of images. Missing images will be loaded without the need for a reload.
1663 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1666 // Consume the event.
1668 } else if (menuItemId == R.id.dark_webview) { // Dark WebView.
1669 // Check to see if dark WebView is supported by this WebView.
1670 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1671 // Toggle the dark WebView setting.
1672 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1673 // Turn off dark WebView.
1674 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1675 } else { // Dark WebView is currently disabled.
1676 // Turn on dark WebView.
1677 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1681 // Consume the event.
1683 } else if (menuItemId == R.id.find_on_page) { // Find on page.
1684 // Get a handle for the views.
1685 Toolbar toolbar = findViewById(R.id.toolbar);
1686 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1687 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1689 // Set the minimum height of the find on page linear layout to match the toolbar.
1690 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1692 // Hide the toolbar.
1693 toolbar.setVisibility(View.GONE);
1695 // Show the find on page linear layout.
1696 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1698 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1699 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1700 findOnPageEditText.postDelayed(() -> {
1701 // Set the focus on the find on page edit text.
1702 findOnPageEditText.requestFocus();
1704 // Get a handle for the input method manager.
1705 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1707 // Remove the lint warning below that the input method manager might be null.
1708 assert inputMethodManager != null;
1710 // Display the keyboard. `0` sets no input flags.
1711 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1714 // Consume the event.
1716 } else if (menuItemId == R.id.print) { // Print.
1717 // Get a print manager instance.
1718 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1720 // Remove the lint error below that print manager might be null.
1721 assert printManager != null;
1723 // Create a print document adapter from the current WebView.
1724 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1726 // Print the document.
1727 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1729 // Consume the event.
1731 } else if (menuItemId == R.id.save_url) { // Save URL.
1732 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1733 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1734 currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1736 // Consume the event.
1738 } else if (menuItemId == R.id.save_archive) {
1739 // Instantiate the save dialog.
1740 DialogFragment saveArchiveFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_ARCHIVE, currentWebView.getCurrentUrl(), null, null, null,
1743 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1744 saveArchiveFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1747 } else if (menuItemId == R.id.save_image) { // Save image.
1748 // Instantiate the save dialog.
1749 DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_IMAGE, currentWebView.getCurrentUrl(), null, null, null,
1752 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
1753 saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1755 // Consume the event.
1757 } else if (menuItemId == R.id.add_to_homescreen) { // Add to homescreen.
1758 // Instantiate the create home screen shortcut dialog.
1759 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1760 currentWebView.getFavoriteOrDefaultIcon());
1762 // Show the create home screen shortcut dialog.
1763 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1765 // Consume the event.
1767 } else if (menuItemId == R.id.view_source) { // View source.
1768 // Create an intent to launch the view source activity.
1769 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1771 // Add the variables to the intent.
1772 viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1773 viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1776 startActivity(viewSourceIntent);
1778 // Consume the event.
1780 } else if (menuItemId == R.id.share_url) { // Share URL.
1781 // Setup the share string.
1782 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1784 // Create the share intent.
1785 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1787 // Add the share string to the intent.
1788 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1790 // Set the MIME type.
1791 shareIntent.setType("text/plain");
1793 // Set the intent to open in a new task.
1794 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1797 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1799 // Consume the event.
1801 } else if (menuItemId == R.id.open_with_app) { // Open with app.
1802 // Open the URL with an outside app.
1803 openWithApp(currentWebView.getUrl());
1805 // Consume the event.
1807 } else if (menuItemId == R.id.open_with_browser) { // Open with browser.
1808 // Open the URL with an outside browser.
1809 openWithBrowser(currentWebView.getUrl());
1811 // Consume the event.
1813 } else if (menuItemId == R.id.add_or_edit_domain) { // Add or edit domain.
1814 // Check if domain settings currently exist.
1815 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1816 // Reapply the domain settings on returning to `MainWebViewActivity`.
1817 reapplyDomainSettingsOnRestart = true;
1819 // Create an intent to launch the domains activity.
1820 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1822 // Add the extra information to the intent.
1823 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1824 domainsIntent.putExtra("close_on_back", true);
1825 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1827 // Get the current certificate.
1828 SslCertificate sslCertificate = currentWebView.getCertificate();
1830 // Check to see if the SSL certificate is populated.
1831 if (sslCertificate != null) {
1832 // Extract the certificate to strings.
1833 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1834 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1835 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1836 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1837 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1838 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1839 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1840 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1842 // Add the certificate to the intent.
1843 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1844 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1845 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1846 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1847 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1848 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1849 domainsIntent.putExtra("ssl_start_date", startDateLong);
1850 domainsIntent.putExtra("ssl_end_date", endDateLong);
1853 // Check to see if the current IP addresses have been received.
1854 if (currentWebView.hasCurrentIpAddresses()) {
1855 // Add the current IP addresses to the intent.
1856 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1860 startActivity(domainsIntent);
1861 } else { // Add a new domain.
1862 // Apply the new domain settings on returning to `MainWebViewActivity`.
1863 reapplyDomainSettingsOnRestart = true;
1865 // Get the current domain
1866 Uri currentUri = Uri.parse(currentWebView.getUrl());
1867 String currentDomain = currentUri.getHost();
1869 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1870 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1872 // Create the domain and store the database ID.
1873 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1875 // Create an intent to launch the domains activity.
1876 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1878 // Add the extra information to the intent.
1879 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1880 domainsIntent.putExtra("close_on_back", true);
1881 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1883 // Get the current certificate.
1884 SslCertificate sslCertificate = currentWebView.getCertificate();
1886 // Check to see if the SSL certificate is populated.
1887 if (sslCertificate != null) {
1888 // Extract the certificate to strings.
1889 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1890 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1891 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1892 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1893 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1894 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1895 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1896 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1898 // Add the certificate to the intent.
1899 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1900 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1901 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1902 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1903 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1904 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1905 domainsIntent.putExtra("ssl_start_date", startDateLong);
1906 domainsIntent.putExtra("ssl_end_date", endDateLong);
1909 // Check to see if the current IP addresses have been received.
1910 if (currentWebView.hasCurrentIpAddresses()) {
1911 // Add the current IP addresses to the intent.
1912 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1916 startActivity(domainsIntent);
1919 // Consume the event.
1921 } else if (menuItemId == R.id.ad_consent) { // Ad consent.
1922 // Instantiate the ad consent dialog.
1923 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1925 // Display the ad consent dialog.
1926 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1928 // Consume the event.
1930 } else { // There is no match with the options menu. Pass the event up to the parent method.
1931 // Don't consume the event.
1932 return super.onOptionsItemSelected(menuItem);
1936 // removeAllCookies is deprecated, but it is required for API < 21.
1938 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1939 // Get a handle for the shared preferences.
1940 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1942 // Get the menu item ID.
1943 int menuItemId = menuItem.getItemId();
1945 // Run the commands that correspond to the selected menu item.
1946 if (menuItemId == R.id.clear_and_exit) { // Clear and exit.
1947 // Clear and exit Privacy Browser.
1949 } else if (menuItemId == R.id.home) { // Home.
1950 // Load the homepage.
1951 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1952 } else if (menuItemId == R.id.back) { // Back.
1953 // Check if the WebView can go back.
1954 if (currentWebView.canGoBack()) {
1955 // Get the current web back forward list.
1956 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1958 // Get the previous entry URL.
1959 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1961 // Apply the domain settings.
1962 applyDomainSettings(currentWebView, previousUrl, false, false, false);
1964 // Load the previous website in the history.
1965 currentWebView.goBack();
1967 } else if (menuItemId == R.id.forward) { // Forward.
1968 // Check if the WebView can go forward.
1969 if (currentWebView.canGoForward()) {
1970 // Get the current web back forward list.
1971 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1973 // Get the next entry URL.
1974 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1976 // Apply the domain settings.
1977 applyDomainSettings(currentWebView, nextUrl, false, false, false);
1979 // Load the next website in the history.
1980 currentWebView.goForward();
1982 } else if (menuItemId == R.id.history) { // History.
1983 // Instantiate the URL history dialog.
1984 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1986 // Show the URL history dialog.
1987 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1988 } else if (menuItemId == R.id.open) { // Open.
1989 // Instantiate the open file dialog.
1990 DialogFragment openDialogFragment = new OpenDialog();
1992 // Show the open file dialog.
1993 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1994 } else if (menuItemId == R.id.requests) { // Requests.
1995 // Populate the resource requests.
1996 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1998 // Create an intent to launch the Requests activity.
1999 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2001 // Add the block third-party requests status to the intent.
2002 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2005 startActivity(requestsIntent);
2006 } else if (menuItemId == R.id.downloads) { // Downloads.
2007 // Try the default system download manager.
2009 // Launch the default system Download Manager.
2010 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2012 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2013 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2016 startActivity(defaultDownloadManagerIntent);
2017 } catch (Exception defaultDownloadManagerException) {
2018 // Try a generic file manager.
2020 // Create a generic file manager intent.
2021 Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2023 // Open the download directory.
2024 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2026 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2027 genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2030 startActivity(genericFileManagerIntent);
2031 } catch (Exception genericFileManagerException) {
2032 // Try an alternate file manager.
2034 // Create an alternate file manager intent.
2035 Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2037 // Open the download directory.
2038 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2040 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2041 alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2043 // Open the alternate file manager.
2044 startActivity(alternateFileManagerIntent);
2045 } catch (Exception alternateFileManagerException) {
2046 // Display a snackbar.
2047 Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2051 } else if (menuItemId == R.id.domains) { // Domains.
2052 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2053 reapplyDomainSettingsOnRestart = true;
2055 // Launch the domains activity.
2056 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2058 // Add the extra information to the intent.
2059 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2061 // Get the current certificate.
2062 SslCertificate sslCertificate = currentWebView.getCertificate();
2064 // Check to see if the SSL certificate is populated.
2065 if (sslCertificate != null) {
2066 // Extract the certificate to strings.
2067 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2068 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2069 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2070 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2071 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2072 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2073 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2074 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2076 // Add the certificate to the intent.
2077 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2078 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2079 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2080 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2081 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2082 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2083 domainsIntent.putExtra("ssl_start_date", startDateLong);
2084 domainsIntent.putExtra("ssl_end_date", endDateLong);
2087 // Check to see if the current IP addresses have been received.
2088 if (currentWebView.hasCurrentIpAddresses()) {
2089 // Add the current IP addresses to the intent.
2090 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2094 startActivity(domainsIntent);
2095 } else if (menuItemId == R.id.settings) { // Settings.
2096 // Set the flag to reapply app settings on restart when returning from Settings.
2097 reapplyAppSettingsOnRestart = true;
2099 // Set the flag to reapply the domain settings on restart when returning from Settings.
2100 reapplyDomainSettingsOnRestart = true;
2102 // Launch the settings activity.
2103 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2104 startActivity(settingsIntent);
2105 } else if (menuItemId == R.id.import_export) { // Import/Export.
2106 // Create an intent to launch the import/export activity.
2107 Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2110 startActivity(importExportIntent);
2111 } else if (menuItemId == R.id.logcat) { // Logcat.
2112 // Create an intent to launch the logcat activity.
2113 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2116 startActivity(logcatIntent);
2117 } else if (menuItemId == R.id.guide) { // Guide.
2118 // Create an intent to launch the guide activity.
2119 Intent guideIntent = new Intent(this, GuideActivity.class);
2122 startActivity(guideIntent);
2123 } else if (menuItemId == R.id.about) { // About
2124 // Create an intent to launch the about activity.
2125 Intent aboutIntent = new Intent(this, AboutActivity.class);
2127 // Create a string array for the blocklist versions.
2128 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],
2129 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2131 // Add the blocklist versions to the intent.
2132 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2135 startActivity(aboutIntent);
2138 // Close the navigation drawer.
2139 drawerLayout.closeDrawer(GravityCompat.START);
2144 public void onPostCreate(Bundle savedInstanceState) {
2145 // Run the default commands.
2146 super.onPostCreate(savedInstanceState);
2148 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2149 actionBarDrawerToggle.syncState();
2153 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2154 // Run the default commands.
2155 super.onConfigurationChanged(newConfig);
2157 // Reload the ad for the free flavor if not in full screen mode.
2158 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2159 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
2160 View adView = findViewById(R.id.adview);
2162 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2163 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
2164 AdHelper.loadAd(adView, getApplicationContext(), this, getString(R.string.ad_unit_id));
2167 // `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:
2168 // https://code.google.com/p/android/issues/detail?id=20493#c8
2169 // ActivityCompat.invalidateOptionsMenu(this);
2173 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2174 // Get the hit test result.
2175 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2177 // Define the URL strings.
2178 final String imageUrl;
2179 final String linkUrl;
2181 // Get handles for the system managers.
2182 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2184 // Remove the lint errors below that the clipboard manager might be null.
2185 assert clipboardManager != null;
2187 // Process the link according to the type.
2188 switch (hitTestResult.getType()) {
2189 // `SRC_ANCHOR_TYPE` is a link.
2190 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2191 // Get the target URL.
2192 linkUrl = hitTestResult.getExtra();
2194 // Set the target URL as the title of the `ContextMenu`.
2195 menu.setHeaderTitle(linkUrl);
2197 // Add an Open in New Tab entry.
2198 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2199 // Load the link URL in a new tab and move to it.
2200 addNewTab(linkUrl, true);
2202 // Consume the event.
2206 // Add an Open in Background entry.
2207 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2208 // Load the link URL in a new tab but do not move to it.
2209 addNewTab(linkUrl, false);
2211 // Consume the event.
2215 // Add an Open with App entry.
2216 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2217 openWithApp(linkUrl);
2219 // Consume the event.
2223 // Add an Open with Browser entry.
2224 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2225 openWithBrowser(linkUrl);
2227 // Consume the event.
2231 // Add a Copy URL entry.
2232 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2233 // Save the link URL in a `ClipData`.
2234 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2236 // Set the `ClipData` as the clipboard's primary clip.
2237 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2239 // Consume the event.
2243 // Add a Save URL entry.
2244 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2245 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2246 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2247 currentWebView.getAcceptCookies()).execute(linkUrl);
2249 // Consume the event.
2253 // Add an empty Cancel entry, which by default closes the context menu.
2254 menu.add(R.string.cancel);
2257 // `IMAGE_TYPE` is an image.
2258 case WebView.HitTestResult.IMAGE_TYPE:
2259 // Get the image URL.
2260 imageUrl = hitTestResult.getExtra();
2262 // Remove the incorrect lint warning below that the image URL might be null.
2263 assert imageUrl != null;
2265 // Set the context menu title.
2266 if (imageUrl.startsWith("data:")) { // The image data is contained in within the URL, making it exceedingly long.
2267 // Truncate the image URL before making it the title.
2268 menu.setHeaderTitle(imageUrl.substring(0, 100));
2269 } else { // The image URL does not contain the full image data.
2270 // Set the image URL as the title of the context menu.
2271 menu.setHeaderTitle(imageUrl);
2274 // Add an Open in New Tab entry.
2275 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2276 // Load the image in a new tab.
2277 addNewTab(imageUrl, true);
2279 // Consume the event.
2283 // Add an Open with App entry.
2284 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2285 // Open the image URL with an external app.
2286 openWithApp(imageUrl);
2288 // Consume the event.
2292 // Add an Open with Browser entry.
2293 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2294 // Open the image URL with an external browser.
2295 openWithBrowser(imageUrl);
2297 // Consume the event.
2301 // Add a View Image entry.
2302 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2303 // Load the image in the current tab.
2304 loadUrl(currentWebView, imageUrl);
2306 // Consume the event.
2310 // Add a Save Image entry.
2311 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2312 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2313 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2314 currentWebView.getAcceptCookies()).execute(imageUrl);
2316 // Consume the event.
2320 // Add a Copy URL entry.
2321 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2322 // Save the image URL in a clip data.
2323 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2325 // Set the clip data as the clipboard's primary clip.
2326 clipboardManager.setPrimaryClip(imageTypeClipData);
2328 // Consume the event.
2332 // Add an empty Cancel entry, which by default closes the context menu.
2333 menu.add(R.string.cancel);
2336 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2337 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2338 // Get the image URL.
2339 imageUrl = hitTestResult.getExtra();
2341 // Instantiate a handler.
2342 Handler handler = new Handler();
2344 // Get a message from the handler.
2345 Message message = handler.obtainMessage();
2347 // Request the image details from the last touched node be returned in the message.
2348 currentWebView.requestFocusNodeHref(message);
2350 // Get the link URL from the message data.
2351 linkUrl = message.getData().getString("url");
2353 // Set the link URL as the title of the context menu.
2354 menu.setHeaderTitle(linkUrl);
2356 // Add an Open in New Tab entry.
2357 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2358 // Load the link URL in a new tab and move to it.
2359 addNewTab(linkUrl, true);
2361 // Consume the event.
2365 // Add an Open in Background entry.
2366 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2367 // Lod the link URL in a new tab but do not move to it.
2368 addNewTab(linkUrl, false);
2370 // Consume the event.
2374 // Add an Open Image in New Tab entry.
2375 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2376 // Load the image in a new tab and move to it.
2377 addNewTab(imageUrl, true);
2379 // Consume the event.
2383 // Add an Open with App entry.
2384 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2385 // Open the link URL with an external app.
2386 openWithApp(linkUrl);
2388 // Consume the event.
2392 // Add an Open with Browser entry.
2393 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2394 // Open the link URL with an external browser.
2395 openWithBrowser(linkUrl);
2397 // Consume the event.
2401 // Add a View Image entry.
2402 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2403 // View the image in the current tab.
2404 loadUrl(currentWebView, imageUrl);
2406 // Consume the event.
2410 // Add a Save Image entry.
2411 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2412 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2413 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2414 currentWebView.getAcceptCookies()).execute(imageUrl);
2416 // Consume the event.
2420 // Add a Copy URL entry.
2421 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2422 // Save the link URL in a clip data.
2423 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2425 // Set the clip data as the clipboard's primary clip.
2426 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2428 // Consume the event.
2432 // Add a Save URL entry.
2433 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2434 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2435 new PrepareSaveDialog(this, this, getSupportFragmentManager(), SaveWebpageDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2436 currentWebView.getAcceptCookies()).execute(linkUrl);
2438 // Consume the event.
2442 // Add an empty Cancel entry, which by default closes the context menu.
2443 menu.add(R.string.cancel);
2446 case WebView.HitTestResult.EMAIL_TYPE:
2447 // Get the target URL.
2448 linkUrl = hitTestResult.getExtra();
2450 // Set the target URL as the title of the `ContextMenu`.
2451 menu.setHeaderTitle(linkUrl);
2453 // Add a Write Email entry.
2454 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2455 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2456 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2458 // Parse the url and set it as the data for the `Intent`.
2459 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2461 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2462 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2466 startActivity(emailIntent);
2467 } catch (ActivityNotFoundException exception) {
2468 // Display a snackbar.
2469 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
2472 // Consume the event.
2476 // Add a Copy Email Address entry.
2477 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2478 // Save the email address in a `ClipData`.
2479 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2481 // Set the `ClipData` as the clipboard's primary clip.
2482 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2484 // Consume the event.
2488 // Add an empty Cancel entry, which by default closes the context menu.
2489 menu.add(R.string.cancel);
2495 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2496 // Get a handle for the bookmarks list view.
2497 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2500 Dialog dialog = dialogFragment.getDialog();
2502 // Remove the incorrect lint warning below that the dialog might be null.
2503 assert dialog != null;
2505 // Get the views from the dialog fragment.
2506 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2507 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2509 // Extract the strings from the edit texts.
2510 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2511 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2513 // Create a favorite icon byte array output stream.
2514 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2516 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2517 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2519 // Convert the favorite icon byte array stream to a byte array.
2520 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2522 // Display the new bookmark below the current items in the (0 indexed) list.
2523 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2525 // Create the bookmark.
2526 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2528 // Update the bookmarks cursor with the current contents of this folder.
2529 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2531 // Update the list view.
2532 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2534 // Scroll to the new bookmark.
2535 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2539 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2540 // Get a handle for the bookmarks list view.
2541 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2544 Dialog dialog = dialogFragment.getDialog();
2546 // Remove the incorrect lint warning below that the dialog might be null.
2547 assert dialog != null;
2549 // Get handles for the views in the dialog fragment.
2550 EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2551 RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2552 ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2554 // Get new folder name string.
2555 String folderNameString = folderNameEditText.getText().toString();
2557 // Create a folder icon bitmap.
2558 Bitmap folderIconBitmap;
2560 // Set the folder icon bitmap according to the dialog.
2561 if (defaultIconRadioButton.isChecked()) { // Use the default folder icon.
2562 // Get the default folder icon drawable.
2563 Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2565 // Convert the folder icon drawable to a bitmap drawable.
2566 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2568 // Convert the folder icon bitmap drawable to a bitmap.
2569 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2570 } else { // Use the WebView favorite icon.
2571 // Copy the favorite icon bitmap to the folder icon bitmap.
2572 folderIconBitmap = favoriteIconBitmap;
2575 // Create a folder icon byte array output stream.
2576 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2578 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2579 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2581 // Convert the folder icon byte array stream to a byte array.
2582 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2584 // Move all the bookmarks down one in the display order.
2585 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2586 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2587 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2590 // Create the folder, which will be placed at the top of the `ListView`.
2591 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2593 // Update the bookmarks cursor with the current contents of this folder.
2594 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2596 // Update the `ListView`.
2597 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2599 // Scroll to the new folder.
2600 bookmarksListView.setSelection(0);
2604 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2605 // Remove the incorrect lint warning below that the dialog fragment might be null.
2606 assert dialogFragment != null;
2609 Dialog dialog = dialogFragment.getDialog();
2611 // Remove the incorrect lint warning below that the dialog might be null.
2612 assert dialog != null;
2614 // Get handles for the views from the dialog.
2615 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2616 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2617 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2618 EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2620 // Get the new folder name.
2621 String newFolderNameString = editFolderNameEditText.getText().toString();
2623 // Check if the favorite icon has changed.
2624 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2625 // Update the name in the database.
2626 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2627 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2628 // Create the new folder icon Bitmap.
2629 Bitmap folderIconBitmap;
2631 // Populate the new folder icon bitmap.
2632 if (defaultFolderIconRadioButton.isChecked()) {
2633 // Get the default folder icon drawable.
2634 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2636 // Convert the folder icon drawable to a bitmap drawable.
2637 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2639 // Convert the folder icon bitmap drawable to a bitmap.
2640 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2641 } else { // Use the `WebView` favorite icon.
2642 // Copy the favorite icon bitmap to the folder icon bitmap.
2643 folderIconBitmap = favoriteIconBitmap;
2646 // Create a folder icon byte array output stream.
2647 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2649 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2650 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2652 // Convert the folder icon byte array stream to a byte array.
2653 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2655 // Update the folder icon in the database.
2656 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2657 } else { // The folder icon and the name have changed.
2658 // Get the new folder icon bitmap.
2659 Bitmap folderIconBitmap;
2660 if (defaultFolderIconRadioButton.isChecked()) {
2661 // Get the default folder icon drawable.
2662 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2664 // Convert the folder icon drawable to a bitmap drawable.
2665 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2667 // Convert the folder icon bitmap drawable to a bitmap.
2668 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2669 } else { // Use the `WebView` favorite icon.
2670 // Copy the favorite icon bitmap to the folder icon bitmap.
2671 folderIconBitmap = favoriteIconBitmap;
2674 // Create a folder icon byte array output stream.
2675 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2677 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2678 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2680 // Convert the folder icon byte array stream to a byte array.
2681 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2683 // Update the folder name and icon in the database.
2684 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2687 // Update the bookmarks cursor with the current contents of this folder.
2688 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2690 // Update the `ListView`.
2691 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2694 // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2696 public void onBackPressed() {
2697 // Check the different options for processing `back`.
2698 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2699 // Close the navigation drawer.
2700 drawerLayout.closeDrawer(GravityCompat.START);
2701 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2702 // close the bookmarks drawer.
2703 drawerLayout.closeDrawer(GravityCompat.END);
2704 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2705 // Exit the full screen video.
2706 exitFullScreenVideo();
2707 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2708 // Get the current web back forward list.
2709 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2711 // Get the previous entry URL.
2712 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2714 // Apply the domain settings.
2715 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2718 currentWebView.goBack();
2719 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2720 // Close the current tab.
2722 } else { // There isn't anything to do in Privacy Browser.
2723 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2724 if (Build.VERSION.SDK_INT >= 21) {
2725 finishAndRemoveTask();
2730 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2735 // Process the results of a file browse.
2737 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2738 // Run the default commands.
2739 super.onActivityResult(requestCode, resultCode, returnedIntent);
2741 // Run the commands that correlate to the specified request code.
2742 switch (requestCode) {
2743 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2744 // File uploads only work on API >= 21.
2745 if (Build.VERSION.SDK_INT >= 21) {
2746 // Pass the file to the WebView.
2747 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2751 case BROWSE_OPEN_REQUEST_CODE:
2752 // Don't do anything if the user pressed back from the file picker.
2753 if (resultCode == Activity.RESULT_OK) {
2754 // Get a handle for the open dialog fragment.
2755 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2757 // Only update the file name if the dialog still exists.
2758 if (openDialogFragment != null) {
2759 // Get a handle for the open dialog.
2760 Dialog openDialog = openDialogFragment.getDialog();
2762 // Remove the incorrect lint warning below that the dialog might be null.
2763 assert openDialog != null;
2765 // Get a handle for the file name edit text.
2766 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2768 // Get the file name URI from the intent.
2769 Uri fileNameUri = returnedIntent.getData();
2771 // Get the file name string from the URI.
2772 String fileNameString = fileNameUri.toString();
2774 // Set the file name text.
2775 fileNameEditText.setText(fileNameString);
2777 // Move the cursor to the end of the file name edit text.
2778 fileNameEditText.setSelection(fileNameString.length());
2783 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2784 // Don't do anything if the user pressed back from the file picker.
2785 if (resultCode == Activity.RESULT_OK) {
2786 // Get a handle for the save dialog fragment.
2787 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2789 // Only update the file name if the dialog still exists.
2790 if (saveWebpageDialogFragment != null) {
2791 // Get a handle for the save webpage dialog.
2792 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2794 // Remove the incorrect lint warning below that the dialog might be null.
2795 assert saveWebpageDialog != null;
2797 // Get a handle for the file name edit text.
2798 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2800 // Get the file name URI from the intent.
2801 Uri fileNameUri = returnedIntent.getData();
2803 // Get the file name string from the URI.
2804 String fileNameString = fileNameUri.toString();
2806 // Set the file name text.
2807 fileNameEditText.setText(fileNameString);
2809 // Move the cursor to the end of the file name edit text.
2810 fileNameEditText.setSelection(fileNameString.length());
2817 private void loadUrlFromTextBox() {
2818 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2819 String unformattedUrlString = urlEditText.getText().toString().trim();
2821 // Initialize the formatted URL string.
2824 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2825 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2826 // Load the entire content URL.
2827 url = unformattedUrlString;
2828 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2829 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2830 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2831 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2832 unformattedUrlString = "https://" + unformattedUrlString;
2835 // Initialize `unformattedUrl`.
2836 URL unformattedUrl = null;
2838 // 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.
2840 unformattedUrl = new URL(unformattedUrlString);
2841 } catch (MalformedURLException e) {
2842 e.printStackTrace();
2845 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2846 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2847 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2848 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2849 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2850 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2853 Uri.Builder uri = new Uri.Builder();
2854 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2856 // Decode the URI as a UTF-8 string in.
2858 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2859 } catch (UnsupportedEncodingException exception) {
2860 // Do nothing. The formatted URL string will remain blank.
2862 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2863 // Create an encoded URL String.
2864 String encodedUrlString;
2866 // Sanitize the search input.
2868 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2869 } catch (UnsupportedEncodingException exception) {
2870 encodedUrlString = "";
2873 // Add the base search URL.
2874 url = searchURL + encodedUrlString;
2877 // 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.
2878 urlEditText.clearFocus();
2881 loadUrl(currentWebView, url);
2884 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2885 // Sanitize the URL.
2886 url = sanitizeUrl(url);
2888 // Apply the domain settings and load the URL.
2889 applyDomainSettings(nestedScrollWebView, url, true, false, true);
2892 public void findPreviousOnPage(View view) {
2893 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2894 currentWebView.findNext(false);
2897 public void findNextOnPage(View view) {
2898 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2899 currentWebView.findNext(true);
2902 public void closeFindOnPage(View view) {
2903 // Get a handle for the views.
2904 Toolbar toolbar = findViewById(R.id.toolbar);
2905 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2906 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2908 // Delete the contents of `find_on_page_edittext`.
2909 findOnPageEditText.setText(null);
2911 // Clear the highlighted phrases if the WebView is not null.
2912 if (currentWebView != null) {
2913 currentWebView.clearMatches();
2916 // Hide the find on page linear layout.
2917 findOnPageLinearLayout.setVisibility(View.GONE);
2919 // Show the toolbar.
2920 toolbar.setVisibility(View.VISIBLE);
2922 // Get a handle for the input method manager.
2923 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2925 // Remove the lint warning below that the input method manager might be null.
2926 assert inputMethodManager != null;
2928 // Hide the keyboard.
2929 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2933 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2934 // Remove the incorrect lint warning below that the dialog fragment might be null.
2935 assert dialogFragment != null;
2938 Dialog dialog = dialogFragment.getDialog();
2940 // Remove the incorrect lint warning below tha the dialog might be null.
2941 assert dialog != null;
2943 // Get a handle for the font size edit text.
2944 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2946 // Initialize the new font size variable with the current font size.
2947 int newFontSize = currentWebView.getSettings().getTextZoom();
2949 // Get the font size from the edit text.
2951 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2952 } catch (Exception exception) {
2953 // If the edit text does not contain a valid font size do nothing.
2956 // Apply the new font size.
2957 currentWebView.getSettings().setTextZoom(newFontSize);
2961 public void onOpen(DialogFragment dialogFragment) {
2963 Dialog dialog = dialogFragment.getDialog();
2965 // Remove the incorrect lint warning below that the dialog might be null.
2966 assert dialog != null;
2968 // Get handles for the views.
2969 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2970 CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
2972 // Get the file path string.
2973 String openFilePath = fileNameEditText.getText().toString();
2975 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
2976 applyDomainSettings(currentWebView, openFilePath, true, false, false);
2978 // Open the file according to the type.
2979 if (mhtCheckBox.isChecked()) { // Force opening of an MHT file.
2981 // Get the MHT file input stream.
2982 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
2984 // Create a temporary MHT file.
2985 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
2987 // Get a file output stream for the temporary MHT file.
2988 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
2990 // Create a transfer byte array.
2991 byte[] transferByteArray = new byte[1024];
2993 // Create an integer to track the number of bytes read.
2996 // Copy the temporary MHT file input stream to the MHT output stream.
2997 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
2998 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3001 // Flush the temporary MHT file output stream.
3002 temporaryMhtFileOutputStream.flush();
3004 // Close the streams.
3005 temporaryMhtFileOutputStream.close();
3006 mhtFileInputStream.close();
3008 // Load the temporary MHT file.
3009 currentWebView.loadUrl(temporaryMhtFile.toString());
3010 } catch (Exception exception) {
3011 // Display a snackbar.
3012 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
3014 } else { // Let the WebView handle opening of the file.
3016 currentWebView.loadUrl(openFilePath);
3021 public void onSaveWebpage(int saveType, @NonNull String originalUrlString, DialogFragment dialogFragment) {
3023 Dialog dialog = dialogFragment.getDialog();
3025 // Remove the incorrect lint warning below that the dialog might be null.
3026 assert dialog != null;
3028 // Get a handle for the file name edit text.
3029 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3031 // Get the file path from the edit text.
3032 String saveWebpageFilePath = fileNameEditText.getText().toString();
3034 //Save the webpage according to the save type.
3036 case SaveWebpageDialog.SAVE_URL:
3037 // Get a handle for the dialog URL edit text.
3038 EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3040 // Define the save webpage URL.
3041 String saveWebpageUrl;
3044 if (originalUrlString.startsWith("data:")) {
3045 // Save the original URL.
3046 saveWebpageUrl = originalUrlString;
3048 // Get the URL from the edit text, which may have been modified.
3049 saveWebpageUrl = dialogUrlEditText.getText().toString();
3053 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveWebpageUrl);
3056 case SaveWebpageDialog.SAVE_ARCHIVE:
3058 // Create a temporary MHT file.
3059 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3061 // Save the temporary MHT file.
3062 currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
3063 if (callbackValue != null) { // The temporary MHT file was saved successfully.
3065 // Create a temporary MHT file input stream.
3066 FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
3068 // Get an output stream for the save webpage file path.
3069 OutputStream mhtOutputStream = getContentResolver().openOutputStream(Uri.parse(saveWebpageFilePath));
3071 // Create a transfer byte array.
3072 byte[] transferByteArray = new byte[1024];
3074 // Create an integer to track the number of bytes read.
3077 // Copy the temporary MHT file input stream to the MHT output stream.
3078 while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
3079 mhtOutputStream.write(transferByteArray, 0, bytesRead);
3082 // Close the streams.
3083 mhtOutputStream.close();
3084 temporaryMhtFileInputStream.close();
3086 // Display a snackbar.
3087 Snackbar.make(currentWebView, getString(R.string.file_saved) + " " + currentWebView.getCurrentUrl(), Snackbar.LENGTH_SHORT).show();
3088 } catch (Exception exception) {
3089 // Display a snackbar with the exception.
3090 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
3092 // Delete the temporary MHT file.
3093 //noinspection ResultOfMethodCallIgnored
3094 temporaryMhtFile.delete();
3096 } else { // There was an unspecified error while saving the temporary MHT file.
3097 // Display an error snackbar.
3098 Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
3101 } catch (IOException ioException) {
3102 // Display a snackbar with the IO exception.
3103 Snackbar.make(currentWebView, getString(R.string.error_saving_file) + " " + ioException.toString(), Snackbar.LENGTH_INDEFINITE).show();
3107 case SaveWebpageDialog.SAVE_IMAGE:
3108 // Save the webpage image.
3109 new SaveWebpageImage(this, saveWebpageFilePath, currentWebView).execute();
3114 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3115 @SuppressLint("ClickableViewAccessibility")
3116 private void initializeApp() {
3117 // Get a handle for the input method.
3118 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3120 // Remove the lint warning below that the input method manager might be null.
3121 assert inputMethodManager != null;
3123 // Initialize the gray foreground color spans for highlighting the URLs. The deprecated `getResources()` must be used until API >= 23.
3124 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3125 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3127 // Get the current theme status.
3128 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3130 // Set the red color span according to the theme.
3131 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3132 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3134 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_900));
3137 // Remove the formatting from the URL edit text when the user is editing the text.
3138 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3139 if (hasFocus) { // The user is editing the URL text box.
3140 // Remove the highlighting.
3141 urlEditText.getText().removeSpan(redColorSpan);
3142 urlEditText.getText().removeSpan(initialGrayColorSpan);
3143 urlEditText.getText().removeSpan(finalGrayColorSpan);
3144 } else { // The user has stopped editing the URL text box.
3145 // Move to the beginning of the string.
3146 urlEditText.setSelection(0);
3148 // Reapply the highlighting.
3153 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3154 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3155 // If the event is a key-down event on the `enter` button, load the URL.
3156 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3157 // Load the URL into the mainWebView and consume the event.
3158 loadUrlFromTextBox();
3160 // If the enter key was pressed, consume the event.
3163 // If any other key was pressed, do not consume the event.
3168 // Create an Orbot status broadcast receiver.
3169 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3171 public void onReceive(Context context, Intent intent) {
3172 // Store the content of the status message in `orbotStatus`.
3173 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3175 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3176 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3177 // Reset the waiting for proxy status.
3178 waitingForProxy = false;
3180 // Get a handle for the waiting for proxy dialog.
3181 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3183 // Dismiss the waiting for proxy dialog if it is displayed.
3184 if (waitingForProxyDialogFragment != null) {
3185 waitingForProxyDialogFragment.dismiss();
3188 // Reload existing URLs and load any URLs that are waiting for the proxy.
3189 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3190 // Get the WebView tab fragment.
3191 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3193 // Get the fragment view.
3194 View fragmentView = webViewTabFragment.getView();
3196 // Only process the WebViews if they exist.
3197 if (fragmentView != null) {
3198 // Get the nested scroll WebView from the tab fragment.
3199 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3201 // Get the waiting for proxy URL string.
3202 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3204 // Load the pending URL if it exists.
3205 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3207 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3209 // Reset the waiting for proxy URL string.
3210 nestedScrollWebView.resetWaitingForProxyUrlString();
3211 } else { // No URL is waiting to be loaded.
3212 // Reload the existing URL.
3213 nestedScrollWebView.reload();
3221 // Register the Orbot status broadcast receiver on `this` context.
3222 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3224 // Get handles for views that need to be modified.
3225 LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3226 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3227 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3228 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3229 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3230 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3232 // Update the web view pager every time a tab is modified.
3233 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3235 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3240 public void onPageSelected(int position) {
3241 // Close the find on page bar if it is open.
3242 closeFindOnPage(null);
3244 // Set the current WebView.
3245 setCurrentWebView(position);
3247 // 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.
3248 if (tabLayout.getSelectedTabPosition() != position) {
3249 // Wait until the new tab has been created.
3250 tabLayout.post(() -> {
3251 // Get a handle for the tab.
3252 TabLayout.Tab tab = tabLayout.getTabAt(position);
3254 // Assert that the tab is not null.
3264 public void onPageScrollStateChanged(int state) {
3269 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3270 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3272 public void onTabSelected(TabLayout.Tab tab) {
3273 // Select the same page in the view pager.
3274 webViewPager.setCurrentItem(tab.getPosition());
3278 public void onTabUnselected(TabLayout.Tab tab) {
3283 public void onTabReselected(TabLayout.Tab tab) {
3284 // Instantiate the View SSL Certificate dialog.
3285 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3287 // Display the View SSL Certificate dialog.
3288 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3292 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3293 bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3294 // Consume the touch.
3298 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3299 launchBookmarksActivityFab.setOnClickListener(v -> {
3300 // Get a copy of the favorite icon bitmap.
3301 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3303 // Create a favorite icon byte array output stream.
3304 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3306 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3307 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3309 // Convert the favorite icon byte array stream to a byte array.
3310 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3312 // Create an intent to launch the bookmarks activity.
3313 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3315 // Add the extra information to the intent.
3316 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3317 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3318 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3319 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3322 startActivity(bookmarksIntent);
3325 // Set the create new bookmark folder FAB to display an alert dialog.
3326 createBookmarkFolderFab.setOnClickListener(v -> {
3327 // Create a create bookmark folder dialog.
3328 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3330 // Show the create bookmark folder dialog.
3331 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3334 // Set the create new bookmark FAB to display an alert dialog.
3335 createBookmarkFab.setOnClickListener(view -> {
3336 // Instantiate the create bookmark dialog.
3337 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3339 // Display the create bookmark dialog.
3340 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3343 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3344 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3346 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3351 public void onTextChanged(CharSequence s, int start, int before, int count) {
3356 public void afterTextChanged(Editable s) {
3357 // 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.
3358 if (currentWebView != null) {
3359 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3364 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3365 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3366 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3367 // Hide the soft keyboard.
3368 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3370 // Consume the event.
3372 } else { // A different key was pressed.
3373 // Do not consume the event.
3378 // Implement swipe to refresh.
3379 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3381 // Store the default progress view offsets for use later in `initializeWebView()`.
3382 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3383 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3385 // Set the refresh color scheme according to the theme.
3386 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3387 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
3389 swipeRefreshLayout.setColorSchemeResources(R.color.violet_500);
3392 // Initialize a color background typed value.
3393 TypedValue colorBackgroundTypedValue = new TypedValue();
3395 // Get the color background from the theme.
3396 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3398 // Get the color background int from the typed value.
3399 int colorBackgroundInt = colorBackgroundTypedValue.data;
3401 // Set the swipe refresh background color.
3402 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3404 // The drawer titles identify the drawer layouts in accessibility mode.
3405 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3406 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3408 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3409 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3411 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3412 currentBookmarksFolder = "";
3414 // Load the home folder, which is `""` in the database.
3415 loadBookmarksFolder();
3417 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3418 // Convert the id from long to int to match the format of the bookmarks database.
3419 int databaseId = (int) id;
3421 // Get the bookmark cursor for this ID.
3422 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3424 // Move the bookmark cursor to the first row.
3425 bookmarkCursor.moveToFirst();
3427 // Act upon the bookmark according to the type.
3428 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3429 // Store the new folder name in `currentBookmarksFolder`.
3430 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3432 // Load the new folder.
3433 loadBookmarksFolder();
3434 } else { // The selected bookmark is not a folder.
3435 // Load the bookmark URL.
3436 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3438 // Close the bookmarks drawer.
3439 drawerLayout.closeDrawer(GravityCompat.END);
3442 // Close the `Cursor`.
3443 bookmarkCursor.close();
3446 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3447 // Convert the database ID from `long` to `int`.
3448 int databaseId = (int) id;
3450 // Find out if the selected bookmark is a folder.
3451 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3453 // Check to see if the bookmark is a folder.
3454 if (isFolder) { // The bookmark is a folder.
3455 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3456 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3458 // Instantiate the edit folder bookmark dialog.
3459 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3461 // Show the edit folder bookmark dialog.
3462 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3463 } else { // The bookmark is not a folder.
3464 // Get the bookmark cursor for this ID.
3465 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3467 // Move the bookmark cursor to the first row.
3468 bookmarkCursor.moveToFirst();
3470 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3471 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3473 // Display a snackbar.
3474 Snackbar.make(currentWebView, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3477 // Consume the event.
3481 // The drawer listener is used to update the navigation menu.
3482 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3484 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3488 public void onDrawerOpened(@NonNull View drawerView) {
3492 public void onDrawerClosed(@NonNull View drawerView) {
3493 // Reset the drawer icon when the drawer is closed. Otherwise, it is an arrow if the drawer is open when the app is restarted.
3494 actionBarDrawerToggle.syncState();
3498 public void onDrawerStateChanged(int newState) {
3499 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3500 // Update the navigation menu items if the WebView is not null.
3501 if (currentWebView != null) {
3502 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3503 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3504 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3505 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3507 // Hide the keyboard (if displayed).
3508 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3511 // 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.
3512 urlEditText.clearFocus();
3513 currentWebView.clearFocus();
3518 // 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).
3519 customHeaders.put("X-Requested-With", "");
3521 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3522 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3524 // Get a handle for the WebView.
3525 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3527 // Store the default user agent.
3528 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3530 // Destroy the bare WebView.
3531 bareWebView.destroy();
3534 private void applyAppSettings() {
3535 // Get a handle for the shared preferences.
3536 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3538 // Store the values from the shared preferences in variables.
3539 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3540 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3541 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3542 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3543 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3544 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3545 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3546 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3548 // Apply the saved proxy mode if the app has been restarted.
3549 if (savedProxyMode != null) {
3550 // Apply the saved proxy mode.
3551 proxyMode = savedProxyMode;
3553 // Reset the saved proxy mode.
3554 savedProxyMode = null;
3557 // Get the search string.
3558 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3560 // Set the search string.
3561 if (searchString.equals("Custom URL")) { // A custom search string is used.
3562 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3563 } else { // A custom search string is not used.
3564 searchURL = searchString;
3570 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3571 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3572 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3573 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3574 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3576 // Add the scrolling behavior to the layout parameters.
3578 // Enable scrolling of the app bar.
3579 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3580 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3581 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3582 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3584 // Disable scrolling of the app bar.
3585 swipeRefreshLayoutParams.setBehavior(null);
3586 toolbarLayoutParams.setScrollFlags(0);
3587 findOnPageLayoutParams.setScrollFlags(0);
3588 tabsLayoutParams.setScrollFlags(0);
3590 // Expand the app bar if it is currently collapsed.
3591 appBarLayout.setExpanded(true);
3594 // Apply the modified layout parameters.
3595 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3596 toolbar.setLayoutParams(toolbarLayoutParams);
3597 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3598 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3600 // Set the app bar scrolling for each WebView.
3601 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3602 // Get the WebView tab fragment.
3603 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3605 // Get the fragment view.
3606 View fragmentView = webViewTabFragment.getView();
3608 // Only modify the WebViews if they exist.
3609 if (fragmentView != null) {
3610 // Get the nested scroll WebView from the tab fragment.
3611 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3613 // Set the app bar scrolling.
3614 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3618 // Update the full screen browsing mode settings.
3619 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3620 // Update the visibility of the app bar, which might have changed in the settings.
3622 // Hide the tab linear layout.
3623 tabsLinearLayout.setVisibility(View.GONE);
3625 // Hide the action bar.
3628 // Show the tab linear layout.
3629 tabsLinearLayout.setVisibility(View.VISIBLE);
3631 // Show the action bar.
3635 // Hide the banner ad in the free flavor.
3636 if (BuildConfig.FLAVOR.contentEquals("free")) {
3637 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3638 View adView = findViewById(R.id.adview);
3640 // Hide the banner ad.
3641 AdHelper.hideAd(adView);
3644 /* Hide the system bars.
3645 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3646 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3647 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3648 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3650 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3651 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3652 } else { // Privacy Browser is not in full screen browsing mode.
3653 // 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.
3654 inFullScreenBrowsingMode = false;
3656 // Show the tab linear layout.
3657 tabsLinearLayout.setVisibility(View.VISIBLE);
3659 // Show the action bar.
3662 // Show the banner ad in the free flavor.
3663 if (BuildConfig.FLAVOR.contentEquals("free")) {
3664 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
3665 View adView = findViewById(R.id.adview);
3667 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3668 // `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
3669 AdHelper.initializeAds(adView, getApplicationContext(), this, getSupportFragmentManager(), getString(R.string.ad_unit_id));
3672 // Remove the `SYSTEM_UI` flags from the root frame layout.
3673 rootFrameLayout.setSystemUiVisibility(0);
3678 public void navigateHistory(@NonNull String url, int steps) {
3679 // Apply the domain settings.
3680 applyDomainSettings(currentWebView, url, false, false, false);
3682 // Load the history entry.
3683 currentWebView.goBackOrForward(steps);
3687 public void pinnedErrorGoBack() {
3688 // Get the current web back forward list.
3689 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3691 // Get the previous entry URL.
3692 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3694 // Apply the domain settings.
3695 applyDomainSettings(currentWebView, previousUrl, false, false, false);
3698 currentWebView.goBack();
3701 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3702 @SuppressLint("SetJavaScriptEnabled")
3703 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3704 // Store the current URL.
3705 nestedScrollWebView.setCurrentUrl(url);
3707 // Parse the URL into a URI.
3708 Uri uri = Uri.parse(url);
3710 // Extract the domain from `uri`.
3711 String newHostName = uri.getHost();
3713 // Strings don't like to be null.
3714 if (newHostName == null) {
3718 // 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.
3719 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3720 // Set the new host name as the current domain name.
3721 nestedScrollWebView.setCurrentDomainName(newHostName);
3723 // Reset the ignoring of pinned domain information.
3724 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3726 // Clear any pinned SSL certificate or IP addresses.
3727 nestedScrollWebView.clearPinnedSslCertificate();
3728 nestedScrollWebView.clearPinnedIpAddresses();
3730 // Reset the favorite icon if specified.
3732 // Initialize the favorite icon.
3733 nestedScrollWebView.initializeFavoriteIcon();
3735 // Get the current page position.
3736 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3738 // Get the corresponding tab.
3739 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3741 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3743 // Get the tab custom view.
3744 View tabCustomView = tab.getCustomView();
3746 // Remove the warning below that the tab custom view might be null.
3747 assert tabCustomView != null;
3749 // Get the tab views.
3750 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3751 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3753 // Set the default favorite icon as the favorite icon for this tab.
3754 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3756 // Set the loading title text.
3757 tabTitleTextView.setText(R.string.loading);
3761 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3762 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3764 // Get a full cursor from `domainsDatabaseHelper`.
3765 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3767 // Initialize `domainSettingsSet`.
3768 Set<String> domainSettingsSet = new HashSet<>();
3770 // Get the domain name column index.
3771 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3773 // Populate `domainSettingsSet`.
3774 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3775 // Move `domainsCursor` to the current row.
3776 domainNameCursor.moveToPosition(i);
3778 // Store the domain name in `domainSettingsSet`.
3779 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3782 // Close `domainNameCursor.
3783 domainNameCursor.close();
3785 // Initialize the domain name in database variable.
3786 String domainNameInDatabase = null;
3788 // Check the hostname against the domain settings set.
3789 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3790 // Record the domain name in the database.
3791 domainNameInDatabase = newHostName;
3793 // Set the domain settings applied tracker to true.
3794 nestedScrollWebView.setDomainSettingsApplied(true);
3795 } else { // The hostname is not contained in the domain settings set.
3796 // Set the domain settings applied tracker to false.
3797 nestedScrollWebView.setDomainSettingsApplied(false);
3800 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3801 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3802 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3803 // Set the domain settings applied tracker to true.
3804 nestedScrollWebView.setDomainSettingsApplied(true);
3806 // Store the applied domain names as it appears in the database.
3807 domainNameInDatabase = "*." + newHostName;
3810 // Strip out the lowest subdomain of of the host name.
3811 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3815 // Get a handle for the shared preferences.
3816 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3818 // Store the general preference information.
3819 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3820 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3821 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3822 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3823 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3824 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3826 // Get the WebView theme entry values string array.
3827 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3829 // Get a handle for the cookie manager.
3830 CookieManager cookieManager = CookieManager.getInstance();
3832 // Initialize the user agent array adapter and string array.
3833 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3834 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3836 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3837 // Get a cursor for the current host and move it to the first position.
3838 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3839 currentDomainSettingsCursor.moveToFirst();
3841 // Get the settings from the cursor.
3842 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3843 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3844 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.COOKIES)) == 1);
3845 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3846 // Form data can be removed once the minimum API >= 26.
3847 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3848 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3849 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3850 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3851 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3852 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3853 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3854 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3855 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3856 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3857 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3858 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3859 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3860 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3861 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3862 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3863 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3864 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WEBVIEW_THEME));
3865 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3866 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3867 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3868 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3869 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3870 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3871 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3872 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3873 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3874 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3875 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3877 // Get the pinned SSL date longs.
3878 long pinnedSslStartDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE));
3879 long pinnedSslEndDateLong = currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE));
3881 // Define the pinned SSL date variables.
3882 Date pinnedSslStartDate;
3883 Date pinnedSslEndDate;
3885 // 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.
3886 if (pinnedSslStartDateLong == 0) {
3887 pinnedSslStartDate = null;
3889 pinnedSslStartDate = new Date(pinnedSslStartDateLong);
3892 // 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.
3893 if (pinnedSslEndDateLong == 0) {
3894 pinnedSslEndDate = null;
3896 pinnedSslEndDate = new Date(pinnedSslEndDateLong);
3899 // Close the current host domain settings cursor.
3900 currentDomainSettingsCursor.close();
3902 // If there is a pinned SSL certificate, store it in the WebView.
3903 if (pinnedSslCertificate) {
3904 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3905 pinnedSslStartDate, pinnedSslEndDate);
3908 // If there is a pinned IP address, store it in the WebView.
3909 if (pinnedIpAddresses) {
3910 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3913 // Apply the cookie domain settings.
3914 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3916 // Apply the form data setting if the API < 26.
3917 if (Build.VERSION.SDK_INT < 26) {
3918 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3921 // Apply the font size.
3922 try { // Try the specified font size to see if it is valid.
3923 if (fontSize == 0) { // Apply the default font size.
3924 // Try to set the font size from the value in the app settings.
3925 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3926 } else { // Apply the font size from domain settings.
3927 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3929 } catch (Exception exception) { // The specified font size is invalid
3930 // Set the font size to be 100%
3931 nestedScrollWebView.getSettings().setTextZoom(100);
3934 // Set the user agent.
3935 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3936 // Get the array position of the default user agent name.
3937 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3939 // Set the user agent according to the system default.
3940 switch (defaultUserAgentArrayPosition) {
3941 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3942 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3943 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3946 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3947 // Set the user agent to `""`, which uses the default value.
3948 nestedScrollWebView.getSettings().setUserAgentString("");
3951 case SETTINGS_CUSTOM_USER_AGENT:
3952 // Set the default custom user agent.
3953 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3957 // Get the user agent string from the user agent data array
3958 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3960 } else { // Set the user agent according to the stored name.
3961 // Get the array position of the user agent name.
3962 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3964 switch (userAgentArrayPosition) {
3965 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3966 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3969 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3970 // Set the user agent to `""`, which uses the default value.
3971 nestedScrollWebView.getSettings().setUserAgentString("");
3975 // Get the user agent string from the user agent data array.
3976 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3980 // Set swipe to refresh.
3981 switch (swipeToRefreshInt) {
3982 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3983 // Store the swipe to refresh status in the nested scroll WebView.
3984 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3986 // Update the swipe refresh layout.
3987 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3988 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3989 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3990 } else { // Swipe to refresh is disabled.
3991 // Disable the swipe refresh layout.
3992 swipeRefreshLayout.setEnabled(false);
3996 case DomainsDatabaseHelper.ENABLED:
3997 // Store the swipe to refresh status in the nested scroll WebView.
3998 nestedScrollWebView.setSwipeToRefresh(true);
4000 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4001 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4004 case DomainsDatabaseHelper.DISABLED:
4005 // Store the swipe to refresh status in the nested scroll WebView.
4006 nestedScrollWebView.setSwipeToRefresh(false);
4008 // Disable swipe to refresh.
4009 swipeRefreshLayout.setEnabled(false);
4012 // Check to see if WebView themes are supported.
4013 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4014 // Set the WebView theme.
4015 switch (webViewThemeInt) {
4016 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4017 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4018 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4019 // Turn off the WebView dark mode.
4020 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4021 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4022 // Turn on the WebView dark mode.
4023 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4024 } else { // The system default theme is selected.
4025 // Get the current system theme status.
4026 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4028 // Set the WebView theme according to the current system theme status.
4029 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4030 // Turn off the WebView dark mode.
4031 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4032 } else { // The system is in night mode.
4033 // Turn on the WebView dark mode.
4034 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4039 case DomainsDatabaseHelper.LIGHT_THEME:
4040 // Turn off the WebView dark mode.
4041 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4044 case DomainsDatabaseHelper.DARK_THEME:
4045 // Turn on the WebView dark mode.
4046 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4051 // Set the viewport.
4052 switch (wideViewportInt) {
4053 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4054 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4057 case DomainsDatabaseHelper.ENABLED:
4058 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4061 case DomainsDatabaseHelper.DISABLED:
4062 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4066 // Set the loading of webpage images.
4067 switch (displayWebpageImagesInt) {
4068 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4069 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4072 case DomainsDatabaseHelper.ENABLED:
4073 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4076 case DomainsDatabaseHelper.DISABLED:
4077 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4081 // Get the current theme status.
4082 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4084 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4085 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4086 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
4088 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
4090 } else { // The new URL does not have custom domain settings. Load the defaults.
4091 // Store the values from the shared preferences.
4092 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4093 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4094 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4095 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4096 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4097 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4098 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4099 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4100 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4101 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4102 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4104 // Apply the default cookie setting.
4105 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4107 // Apply the default font size setting.
4109 // Try to set the font size from the value in the app settings.
4110 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4111 } catch (Exception exception) {
4112 // If the app settings value is invalid, set the font size to 100%.
4113 nestedScrollWebView.getSettings().setTextZoom(100);
4116 // Apply the form data setting if the API < 26.
4117 if (Build.VERSION.SDK_INT < 26) {
4118 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4121 // Store the swipe to refresh status in the nested scroll WebView.
4122 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4124 // Update the swipe refresh layout.
4125 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4126 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4127 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4128 } else { // Swipe to refresh is disabled.
4129 // Disable the swipe refresh layout.
4130 swipeRefreshLayout.setEnabled(false);
4133 // Reset the pinned variables.
4134 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4136 // Get the array position of the user agent name.
4137 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4139 // Set the user agent.
4140 switch (userAgentArrayPosition) {
4141 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4142 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4143 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4146 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4147 // Set the user agent to `""`, which uses the default value.
4148 nestedScrollWebView.getSettings().setUserAgentString("");
4151 case SETTINGS_CUSTOM_USER_AGENT:
4152 // Set the default custom user agent.
4153 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4157 // Get the user agent string from the user agent data array
4158 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4161 // Apply the WebView theme if supported by the installed WebView.
4162 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4163 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4164 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4165 // Turn off the WebView dark mode.
4166 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4167 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4168 // Turn on the WebView dark mode.
4169 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4170 } else { // The system default theme is selected.
4171 // Get the current system theme status.
4172 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4174 // Set the WebView theme according to the current system theme status.
4175 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4176 // Turn off the WebView dark mode.
4177 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4178 } else { // The system is in night mode.
4179 // Turn on the WebView dark mode.
4180 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4185 // Set the viewport.
4186 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4188 // Set the loading of webpage images.
4189 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4191 // Set a transparent background on the URL relative layout.
4192 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4195 // Close the domains database helper.
4196 domainsDatabaseHelper.close();
4198 // Update the privacy icons.
4199 updatePrivacyIcons(true);
4202 // Reload the website if returning from the Domains activity.
4203 if (reloadWebsite) {
4204 nestedScrollWebView.reload();
4207 // 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.
4209 nestedScrollWebView.loadUrl(url, customHeaders);
4213 private void applyProxy(boolean reloadWebViews) {
4214 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4215 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4217 // Reset the waiting for proxy tracker.
4218 waitingForProxy = false;
4220 // Get the current theme status.
4221 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4223 // Update the user interface and reload the WebViews if requested.
4224 switch (proxyMode) {
4225 case ProxyHelper.NONE:
4226 // Initialize a color background typed value.
4227 TypedValue colorBackgroundTypedValue = new TypedValue();
4229 // Get the color background from the theme.
4230 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4232 // Get the color background int from the typed value.
4233 int colorBackgroundInt = colorBackgroundTypedValue.data;
4235 // Set the default app bar layout background.
4236 appBarLayout.setBackgroundColor(colorBackgroundInt);
4239 case ProxyHelper.TOR:
4240 // Set the app bar background to indicate proxying through Orbot is enabled.
4241 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4242 appBarLayout.setBackgroundResource(R.color.blue_50);
4244 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4247 // Check to see if Orbot is installed.
4249 // Get the package manager.
4250 PackageManager packageManager = getPackageManager();
4252 // 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.
4253 packageManager.getPackageInfo("org.torproject.android", 0);
4255 // Check to see if the proxy is ready.
4256 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4257 // Set the waiting for proxy status.
4258 waitingForProxy = true;
4260 // Show the waiting for proxy dialog if it isn't already displayed.
4261 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4262 // Get a handle for the waiting for proxy alert dialog.
4263 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4265 // Display the waiting for proxy alert dialog.
4266 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4269 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4270 // Show the Orbot not installed dialog if it is not already displayed.
4271 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4272 // Get a handle for the Orbot not installed alert dialog.
4273 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4275 // Display the Orbot not installed alert dialog.
4276 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4281 case ProxyHelper.I2P:
4282 // Set the app bar background to indicate proxying through Orbot is enabled.
4283 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4284 appBarLayout.setBackgroundResource(R.color.blue_50);
4286 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4289 // Check to see if I2P is installed.
4291 // Get the package manager.
4292 PackageManager packageManager = getPackageManager();
4294 // 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.
4295 packageManager.getPackageInfo("net.i2p.android.router", 0);
4296 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4297 // Sow the I2P not installed dialog if it is not already displayed.
4298 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4299 // Get a handle for the waiting for proxy alert dialog.
4300 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4302 // Display the I2P not installed alert dialog.
4303 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4308 case ProxyHelper.CUSTOM:
4309 // Set the app bar background to indicate proxying through Orbot is enabled.
4310 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4311 appBarLayout.setBackgroundResource(R.color.blue_50);
4313 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4318 // Reload the WebViews if requested and not waiting for the proxy.
4319 if (reloadWebViews && !waitingForProxy) {
4320 // Reload the WebViews.
4321 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4322 // Get the WebView tab fragment.
4323 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4325 // Get the fragment view.
4326 View fragmentView = webViewTabFragment.getView();
4328 // Only reload the WebViews if they exist.
4329 if (fragmentView != null) {
4330 // Get the nested scroll WebView from the tab fragment.
4331 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4333 // Reload the WebView.
4334 nestedScrollWebView.reload();
4340 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4341 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4342 if ((optionsMenu != null) && (currentWebView != null)) {
4343 // Update the privacy icon.
4344 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4345 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4346 } else if (currentWebView.getAcceptCookies()) { // JavaScript is disabled but cookies are enabled.
4347 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4348 } else { // All the dangerous features are disabled.
4349 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4352 // Get the current theme status.
4353 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4355 // Update the cookies icon.
4356 if (currentWebView.getAcceptCookies()) { // Cookies are enabled.
4357 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4358 } else { // Cookies are disabled.
4359 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4360 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4362 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4366 // Update the refresh icon.
4367 if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) { // The refresh icon is displayed.
4368 // Set the icon according to the theme.
4369 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4370 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4372 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4374 } else { // The stop icon is displayed.
4375 // Set the icon according to the theme.
4376 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4377 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
4379 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
4383 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4384 if (runInvalidateOptionsMenu) {
4385 invalidateOptionsMenu();
4390 private void highlightUrlText() {
4391 // Only highlight the URL text if the box is not currently selected.
4392 if (!urlEditText.hasFocus()) {
4393 // Get the URL string.
4394 String urlString = urlEditText.getText().toString();
4396 // Highlight the URL according to the protocol.
4397 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4398 // De-emphasize everything before the file name.
4399 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4400 } else { // This is a web URL.
4401 // Get the index of the `/` immediately after the domain name.
4402 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4404 // Create a base URL string.
4407 // Get the base URL.
4408 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4409 // Get the base URL.
4410 baseUrl = urlString.substring(0, endOfDomainName);
4411 } else { // There are no characters after the base URL.
4412 // Set the base URL to be the entire URL string.
4413 baseUrl = urlString;
4416 // Get the index of the last `.` in the domain.
4417 int lastDotIndex = baseUrl.lastIndexOf(".");
4419 // Get the index of the penultimate `.` in the domain.
4420 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4422 // Markup the beginning of the URL.
4423 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4424 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4426 // De-emphasize subdomains.
4427 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4428 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4430 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4431 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4432 // De-emphasize the protocol and the additional subdomains.
4433 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4434 } else { // There is only one subdomain in the domain name.
4435 // De-emphasize only the protocol.
4436 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4440 // De-emphasize the text after the domain name.
4441 if (endOfDomainName > 0) {
4442 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4448 private void loadBookmarksFolder() {
4449 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4450 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4452 // Populate the bookmarks cursor adapter.
4453 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4455 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4456 // Inflate the individual item layout.
4457 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4461 public void bindView(View view, Context context, Cursor cursor) {
4462 // Get handles for the views.
4463 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4464 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4466 // Get the favorite icon byte array from the cursor.
4467 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4469 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4470 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4472 // Display the bitmap in `bookmarkFavoriteIcon`.
4473 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4475 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4476 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4477 bookmarkNameTextView.setText(bookmarkNameString);
4479 // Make the font bold for folders.
4480 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4481 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4482 } else { // Reset the font to default for normal bookmarks.
4483 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4488 // Get a handle for the bookmarks list view.
4489 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4491 // Populate the list view with the adapter.
4492 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4494 // Get a handle for the bookmarks title text view.
4495 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4497 // Set the bookmarks drawer title.
4498 if (currentBookmarksFolder.isEmpty()) {
4499 bookmarksTitleTextView.setText(R.string.bookmarks);
4501 bookmarksTitleTextView.setText(currentBookmarksFolder);
4505 private void openWithApp(String url) {
4506 // Create an open with app intent with `ACTION_VIEW`.
4507 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4509 // Set the URI but not the MIME type. This should open all available apps.
4510 openWithAppIntent.setData(Uri.parse(url));
4512 // Flag the intent to open in a new task.
4513 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4517 // Show the chooser.
4518 startActivity(openWithAppIntent);
4519 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4520 // Show a snackbar with the error.
4521 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4525 private void openWithBrowser(String url) {
4526 // Create an open with browser intent with `ACTION_VIEW`.
4527 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4529 // Set the URI and the MIME type. `"text/html"` should load browser options.
4530 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4532 // Flag the intent to open in a new task.
4533 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4537 // Show the chooser.
4538 startActivity(openWithBrowserIntent);
4539 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4540 // Show a snackbar with the error.
4541 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4545 private String sanitizeUrl(String url) {
4546 // Sanitize Google Analytics.
4547 if (sanitizeGoogleAnalytics) {
4549 if (url.contains("?utm_")) {
4550 url = url.substring(0, url.indexOf("?utm_"));
4554 if (url.contains("&utm_")) {
4555 url = url.substring(0, url.indexOf("&utm_"));
4559 // Sanitize Facebook Click IDs.
4560 if (sanitizeFacebookClickIds) {
4561 // Remove `?fbclid=`.
4562 if (url.contains("?fbclid=")) {
4563 url = url.substring(0, url.indexOf("?fbclid="));
4566 // Remove `&fbclid=`.
4567 if (url.contains("&fbclid=")) {
4568 url = url.substring(0, url.indexOf("&fbclid="));
4571 // Remove `?fbadid=`.
4572 if (url.contains("?fbadid=")) {
4573 url = url.substring(0, url.indexOf("?fbadid="));
4576 // Remove `&fbadid=`.
4577 if (url.contains("&fbadid=")) {
4578 url = url.substring(0, url.indexOf("&fbadid="));
4582 // Sanitize Twitter AMP redirects.
4583 if (sanitizeTwitterAmpRedirects) {
4585 if (url.contains("?amp=1")) {
4586 url = url.substring(0, url.indexOf("?amp=1"));
4590 // Return the sanitized URL.
4594 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4595 // Store the blocklists.
4596 easyList = combinedBlocklists.get(0);
4597 easyPrivacy = combinedBlocklists.get(1);
4598 fanboysAnnoyanceList = combinedBlocklists.get(2);
4599 fanboysSocialList = combinedBlocklists.get(3);
4600 ultraList = combinedBlocklists.get(4);
4601 ultraPrivacy = combinedBlocklists.get(5);
4603 // Check to see if the activity has been restarted with a saved state.
4604 if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) { // The activity has not been restarted or it was restarted on start to force the night theme.
4605 // Add the first tab.
4606 addNewTab("", true);
4607 } else { // The activity has been restarted.
4608 // Restore each tab. Once the minimum API >= 24, a `forEach()` command can be used.
4609 for (int i = 0; i < savedStateArrayList.size(); i++) {
4611 tabLayout.addTab(tabLayout.newTab());
4614 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4616 // Remove the lint warning below that the current tab might be null.
4617 assert newTab != null;
4619 // Set a custom view on the new tab.
4620 newTab.setCustomView(R.layout.tab_custom_view);
4622 // Add the new page.
4623 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4626 // Reset the saved state variables.
4627 savedStateArrayList = null;
4628 savedNestedScrollWebViewStateArrayList = null;
4630 // Restore the selected tab position.
4631 if (savedTabPosition == 0) { // The first tab is selected.
4632 // Set the first page as the current WebView.
4633 setCurrentWebView(0);
4634 } else { // the first tab is not selected.
4635 // Move to the selected tab.
4636 webViewPager.setCurrentItem(savedTabPosition);
4639 // Get the intent that started the app.
4640 Intent intent = getIntent();
4642 // Reset the intent. This prevents a duplicate tab from being created on restart.
4643 setIntent(new Intent());
4645 // Get the information from the intent.
4646 String intentAction = intent.getAction();
4647 Uri intentUriData = intent.getData();
4648 String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4650 // Determine if this is a web search.
4651 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4653 // 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.
4654 if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4655 // Get the shared preferences.
4656 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4658 // Create a URL string.
4661 // If the intent action is a web search, perform the search.
4662 if (isWebSearch) { // The intent is a web search.
4663 // Create an encoded URL string.
4664 String encodedUrlString;
4666 // Sanitize the search input and convert it to a search.
4668 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4669 } catch (UnsupportedEncodingException exception) {
4670 encodedUrlString = "";
4673 // Add the base search URL.
4674 url = searchURL + encodedUrlString;
4675 } else if (intentUriData != null) { // The intent contains a URL formatted as a URI.
4676 // Set the intent data as the URL.
4677 url = intentUriData.toString();
4678 } else { // The intent contains a string, which might be a URL.
4679 // Set the intent string as the URL.
4680 url = intentStringExtra;
4683 // Add a new tab if specified in the preferences.
4684 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
4685 // Set the loading new intent flag.
4686 loadingNewIntent = true;
4689 addNewTab(url, true);
4690 } else { // Load the URL in the current tab.
4692 loadUrl(currentWebView, url);
4698 public void addTab(View view) {
4699 // Add a new tab with a blank URL.
4700 addNewTab("", true);
4703 private void addNewTab(String url, boolean moveToTab) {
4704 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4705 urlEditText.clearFocus();
4707 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4708 int newTabNumber = tabLayout.getTabCount();
4711 tabLayout.addTab(tabLayout.newTab());
4714 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4716 // Remove the lint warning below that the current tab might be null.
4717 assert newTab != null;
4719 // Set a custom view on the new tab.
4720 newTab.setCustomView(R.layout.tab_custom_view);
4722 // Add the new WebView page.
4723 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4726 public void closeTab(View view) {
4727 // Run the command according to the number of tabs.
4728 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4729 // Close the current tab.
4731 } else { // There is only one tab open.
4736 private void closeCurrentTab() {
4737 // Get the current tab number.
4738 int currentTabNumber = tabLayout.getSelectedTabPosition();
4740 // Delete the current tab.
4741 tabLayout.removeTabAt(currentTabNumber);
4743 // 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,
4744 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4745 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4746 setCurrentWebView(currentTabNumber);
4750 private void exitFullScreenVideo() {
4751 // Re-enable the screen timeout.
4752 fullScreenVideoFrameLayout.setKeepScreenOn(false);
4754 // Unset the full screen video flag.
4755 displayingFullScreenVideo = false;
4757 // Remove all the views from the full screen video frame layout.
4758 fullScreenVideoFrameLayout.removeAllViews();
4760 // Hide the full screen video frame layout.
4761 fullScreenVideoFrameLayout.setVisibility(View.GONE);
4763 // Enable the sliding drawers.
4764 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4766 // Show the main content relative layout.
4767 mainContentRelativeLayout.setVisibility(View.VISIBLE);
4769 // Apply the appropriate full screen mode flags.
4770 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4771 // Hide the app bar if specified.
4773 // Hide the tab linear layout.
4774 tabsLinearLayout.setVisibility(View.GONE);
4776 // Hide the action bar.
4780 // Hide the banner ad in the free flavor.
4781 if (BuildConfig.FLAVOR.contentEquals("free")) {
4782 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
4783 View adView = findViewById(R.id.adview);
4785 // Hide the banner ad.
4786 AdHelper.hideAd(adView);
4789 /* Hide the system bars.
4790 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4791 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4792 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4793 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4795 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4796 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4797 } else { // Switch to normal viewing mode.
4798 // Remove the `SYSTEM_UI` flags from the root frame layout.
4799 rootFrameLayout.setSystemUiVisibility(0);
4802 // Reload the ad for the free flavor if not in full screen mode.
4803 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
4804 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
4805 View adView = findViewById(R.id.adview);
4808 AdHelper.loadAd(adView, this, this, getString(R.string.ad_unit_id));
4812 private void clearAndExit() {
4813 // Get a handle for the shared preferences.
4814 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4816 // Close the bookmarks cursor and database.
4817 bookmarksCursor.close();
4818 bookmarksDatabaseHelper.close();
4820 // Get the status of the clear everything preference.
4821 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4823 // Get a handle for the runtime.
4824 Runtime runtime = Runtime.getRuntime();
4826 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4827 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4828 String privateDataDirectoryString = getApplicationInfo().dataDir;
4831 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4832 // The command to remove cookies changed slightly in API 21.
4833 if (Build.VERSION.SDK_INT >= 21) {
4834 CookieManager.getInstance().removeAllCookies(null);
4836 CookieManager.getInstance().removeAllCookie();
4839 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4841 // Two commands must be used because `Runtime.exec()` does not like `*`.
4842 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4843 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4845 // Wait until the processes have finished.
4846 deleteCookiesProcess.waitFor();
4847 deleteCookiesJournalProcess.waitFor();
4848 } catch (Exception exception) {
4849 // Do nothing if an error is thrown.
4853 // Clear DOM storage.
4854 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4855 // Ask `WebStorage` to clear the DOM storage.
4856 WebStorage webStorage = WebStorage.getInstance();
4857 webStorage.deleteAllData();
4859 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4861 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4862 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4864 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4865 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4866 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4867 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4868 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4870 // Wait until the processes have finished.
4871 deleteLocalStorageProcess.waitFor();
4872 deleteIndexProcess.waitFor();
4873 deleteQuotaManagerProcess.waitFor();
4874 deleteQuotaManagerJournalProcess.waitFor();
4875 deleteDatabaseProcess.waitFor();
4876 } catch (Exception exception) {
4877 // Do nothing if an error is thrown.
4881 // Clear form data if the API < 26.
4882 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4883 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4884 webViewDatabase.clearFormData();
4886 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4888 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4889 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4890 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4892 // Wait until the processes have finished.
4893 deleteWebDataProcess.waitFor();
4894 deleteWebDataJournalProcess.waitFor();
4895 } catch (Exception exception) {
4896 // Do nothing if an error is thrown.
4900 // Clear the logcat.
4901 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4903 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
4904 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4906 // Wait for the process to finish.
4908 } catch (IOException|InterruptedException exception) {
4914 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4915 // Clear the cache from each WebView.
4916 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4917 // Get the WebView tab fragment.
4918 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4920 // Get the WebView fragment view.
4921 View webViewFragmentView = webViewTabFragment.getView();
4923 // Only clear the cache if the WebView exists.
4924 if (webViewFragmentView != null) {
4925 // Get the nested scroll WebView from the tab fragment.
4926 NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4928 // Clear the cache for this WebView.
4929 nestedScrollWebView.clearCache(true);
4933 // Manually delete the cache directories.
4935 // Delete the main cache directory.
4936 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4938 // Delete the secondary `Service Worker` cache directory.
4939 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4940 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4942 // Wait until the processes have finished.
4943 deleteCacheProcess.waitFor();
4944 deleteServiceWorkerProcess.waitFor();
4945 } catch (Exception exception) {
4946 // Do nothing if an error is thrown.
4950 // Wipe out each WebView.
4951 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4952 // Get the WebView tab fragment.
4953 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4955 // Get the WebView frame layout.
4956 FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4958 // Only wipe out the WebView if it exists.
4959 if (webViewFrameLayout != null) {
4960 // Get the nested scroll WebView from the tab fragment.
4961 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4963 // Clear SSL certificate preferences for this WebView.
4964 nestedScrollWebView.clearSslPreferences();
4966 // Clear the back/forward history for this WebView.
4967 nestedScrollWebView.clearHistory();
4969 // Remove all the views from the frame layout.
4970 webViewFrameLayout.removeAllViews();
4972 // Destroy the internal state of the WebView.
4973 nestedScrollWebView.destroy();
4977 // Clear the custom headers.
4978 customHeaders.clear();
4980 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4981 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4982 if (clearEverything) {
4984 // Delete the folder.
4985 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4987 // Wait until the process has finished.
4988 deleteAppWebviewProcess.waitFor();
4989 } catch (Exception exception) {
4990 // Do nothing if an error is thrown.
4994 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4995 if (Build.VERSION.SDK_INT >= 21) {
4996 finishAndRemoveTask();
5001 // Remove the terminated program from RAM. The status code is `0`.
5005 public void bookmarksBack(View view) {
5006 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
5007 // close the bookmarks drawer.
5008 drawerLayout.closeDrawer(GravityCompat.END);
5009 } else { // A subfolder is displayed.
5010 // Place the former parent folder in `currentFolder`.
5011 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
5013 // Load the new folder.
5014 loadBookmarksFolder();
5018 private void setCurrentWebView(int pageNumber) {
5019 // Stop the swipe to refresh indicator if it is running
5020 swipeRefreshLayout.setRefreshing(false);
5022 // Get the WebView tab fragment.
5023 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
5025 // Get the fragment view.
5026 View webViewFragmentView = webViewTabFragment.getView();
5028 // Set the current WebView if the fragment view is not null.
5029 if (webViewFragmentView != null) { // The fragment has been populated.
5030 // Store the current WebView.
5031 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
5033 // Update the status of swipe to refresh.
5034 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
5035 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5036 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
5037 } else { // Swipe to refresh is disabled.
5038 // Disable the swipe refresh layout.
5039 swipeRefreshLayout.setEnabled(false);
5042 // Get a handle for the cookie manager.
5043 CookieManager cookieManager = CookieManager.getInstance();
5045 // Set the cookie status.
5046 cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
5048 // Update the privacy icons. `true` redraws the icons in the app bar.
5049 updatePrivacyIcons(true);
5051 // Get a handle for the input method manager.
5052 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5054 // Remove the lint warning below that the input method manager might be null.
5055 assert inputMethodManager != null;
5057 // Get the current URL.
5058 String url = currentWebView.getUrl();
5060 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5061 if (!loadingNewIntent) { // A new intent is not being loaded.
5062 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5063 // Display the hint in the URL edit text.
5064 urlEditText.setText("");
5066 // Request focus for the URL text box.
5067 urlEditText.requestFocus();
5069 // Display the keyboard.
5070 inputMethodManager.showSoftInput(urlEditText, 0);
5071 } else { // The WebView has a loaded URL.
5072 // Clear the focus from the URL text box.
5073 urlEditText.clearFocus();
5075 // Hide the soft keyboard.
5076 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5078 // Display the current URL in the URL text box.
5079 urlEditText.setText(url);
5081 // Highlight the URL text.
5084 } else { // A new intent is being loaded.
5085 // Reset the loading new intent tracker.
5086 loadingNewIntent = false;
5089 // Set the background to indicate the domain settings status.
5090 if (currentWebView.getDomainSettingsApplied()) {
5091 // Get the current theme status.
5092 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5094 // Set a green background on the URL relative layout to indicate that custom domain settings are being used.
5095 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
5096 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_light_green, null));
5098 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.url_bar_background_dark_blue, null));
5101 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5103 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5104 // Create a handler to set the current WebView.
5105 Handler setCurrentWebViewHandler = new Handler();
5107 // Create a runnable to set the current WebView.
5108 Runnable setCurrentWebWebRunnable = () -> {
5109 // Set the current WebView.
5110 setCurrentWebView(pageNumber);
5113 // Try setting the current WebView again after 100 milliseconds.
5114 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5119 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5120 // Get a handle for the shared preferences.
5121 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5123 // Get the WebView theme.
5124 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5126 // Get the WebView theme entry values string array.
5127 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5129 // Apply the WebView theme if supported by the installed WebView.
5130 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5131 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5132 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5133 // Turn off the WebView dark mode.
5134 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5136 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5137 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5138 nestedScrollWebView.setVisibility(View.VISIBLE);
5139 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5140 // Turn on the WebView dark mode.
5141 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5142 } else { // The system default theme is selected.
5143 // Get the current system theme status.
5144 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5146 // Set the WebView theme according to the current system theme status.
5147 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
5148 // Turn off the WebView dark mode.
5149 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5151 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5152 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5153 nestedScrollWebView.setVisibility(View.VISIBLE);
5154 } else { // The system is in night mode.
5155 // Turn on the WebView dark mode.
5156 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5161 // Get a handle for the activity
5162 Activity activity = this;
5164 // Get a handle for the input method manager.
5165 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5167 // Instantiate the blocklist helper.
5168 BlocklistHelper blocklistHelper = new BlocklistHelper();
5170 // Remove the lint warning below that the input method manager might be null.
5171 assert inputMethodManager != null;
5173 // Initialize the favorite icon.
5174 nestedScrollWebView.initializeFavoriteIcon();
5176 // Set the app bar scrolling.
5177 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5179 // Allow pinch to zoom.
5180 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5182 // Hide zoom controls.
5183 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5185 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5186 if (Build.VERSION.SDK_INT >= 21) {
5187 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5190 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5191 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5193 // Explicitly disable geolocation.
5194 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5196 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5197 nestedScrollWebView.getSettings().setAllowFileAccess(true);
5199 // Create a double-tap gesture detector to toggle full-screen mode.
5200 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5201 // Override `onDoubleTap()`. All other events are handled using the default settings.
5203 public boolean onDoubleTap(MotionEvent event) {
5204 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5205 // Toggle the full screen browsing mode tracker.
5206 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5208 // Toggle the full screen browsing mode.
5209 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5210 // Hide the app bar if specified.
5212 // Close the find on page bar if it is visible.
5213 closeFindOnPage(null);
5215 // Hide the tab linear layout.
5216 tabsLinearLayout.setVisibility(View.GONE);
5218 // Hide the action bar.
5221 // Check to see if the app bar is normally scrolled.
5222 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5223 // Get the swipe refresh layout parameters.
5224 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5226 // Remove the off-screen scrolling layout.
5227 swipeRefreshLayoutParams.setBehavior(null);
5228 } else { // The app bar is not scrolled when it is displayed.
5229 // Remove the padding from the top of the swipe refresh layout.
5230 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5232 // The swipe refresh circle must be moved above the now removed status bar location.
5233 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5237 // Hide the banner ad in the free flavor.
5238 if (BuildConfig.FLAVOR.contentEquals("free")) {
5239 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5240 View adView = findViewById(R.id.adview);
5242 // Hide the banner ad.
5243 AdHelper.hideAd(adView);
5246 /* Hide the system bars.
5247 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5248 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5249 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5250 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5252 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5253 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5254 } else { // Switch to normal viewing mode.
5255 // Show the app bar if it was hidden.
5257 // Show the tab linear layout.
5258 tabsLinearLayout.setVisibility(View.VISIBLE);
5260 // Show the action bar.
5263 // Check to see if the app bar is normally scrolled.
5264 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
5265 // Get the swipe refresh layout parameters.
5266 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5268 // Add the off-screen scrolling layout.
5269 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5270 } else { // The app bar is not scrolled when it is displayed.
5271 // The swipe refresh layout must be manually moved below the app bar layout.
5272 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5274 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5275 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5279 // Show the banner ad in the free flavor.
5280 if (BuildConfig.FLAVOR.contentEquals("free")) {
5281 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5282 View adView = findViewById(R.id.adview);
5284 // Reload the ad. `getContext()` can be used instead of `getActivity.getApplicationContext()` once the minimum API >= 23.
5285 AdHelper.loadAd(adView, getApplicationContext(), activity, getString(R.string.ad_unit_id));
5288 // Remove the `SYSTEM_UI` flags from the root frame layout.
5289 rootFrameLayout.setSystemUiVisibility(0);
5292 // Consume the double-tap.
5294 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5300 // Pass all touch events on the WebView through the double-tap gesture detector.
5301 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5302 // Call `performClick()` on the view, which is required for accessibility.
5303 view.performClick();
5305 // Send the event to the gesture detector.
5306 return doubleTapGestureDetector.onTouchEvent(event);
5309 // Register the WebView for a context menu. This is used to see link targets and download images.
5310 registerForContextMenu(nestedScrollWebView);
5312 // Allow the downloading of files.
5313 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5314 // Define a formatted file size string.
5315 String formattedFileSizeString;
5317 // Process the content length if it contains data.
5318 if (contentLength > 0) { // The content length is greater than 0.
5319 // Format the content length as a string.
5320 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5321 } else { // The content length is not greater than 0.
5322 // Set the formatted file size string to be `unknown size`.
5323 formattedFileSizeString = getString(R.string.unknown_size);
5326 // Get the file name from the content disposition.
5327 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5329 // Prevent the dialog from displaying if the app window is not visible.
5330 // The download listener continues to function even when the WebView is paused. Attempting to display a dialog in that state leads to a crash.
5331 while (!activity.getWindow().isActive()) {
5333 // The window is not active. Wait 1 second.
5335 } catch (InterruptedException e) {
5340 // Instantiate the save dialog.
5341 DialogFragment saveDialogFragment = SaveWebpageDialog.saveWebpage(SaveWebpageDialog.SAVE_URL, downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5342 nestedScrollWebView.getAcceptCookies());
5344 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5345 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5348 // Update the find on page count.
5349 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5350 // Get a handle for `findOnPageCountTextView`.
5351 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5354 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5355 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5356 // Set `findOnPageCountTextView` to `0/0`.
5357 findOnPageCountTextView.setText(R.string.zero_of_zero);
5358 } else if (isDoneCounting) { // There are matches.
5359 // `activeMatchOrdinal` is zero-based.
5360 int activeMatch = activeMatchOrdinal + 1;
5362 // Build the match string.
5363 String matchString = activeMatch + "/" + numberOfMatches;
5365 // Set `findOnPageCountTextView`.
5366 findOnPageCountTextView.setText(matchString);
5371 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5372 // 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.
5373 if (Build.VERSION.SDK_INT >= 23) {
5374 nestedScrollWebView.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
5375 if (nestedScrollWebView.getSwipeToRefresh()) {
5376 // Only enable swipe to refresh if the WebView is scrolled to the top.
5377 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5379 // Disable swipe to refresh.
5380 swipeRefreshLayout.setEnabled(false);
5383 // Reinforce the system UI visibility flags if in full screen browsing mode.
5384 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5385 if (inFullScreenBrowsingMode) {
5386 /* Hide the system bars.
5387 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5388 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5389 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5390 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5392 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5393 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5397 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5398 if (nestedScrollWebView.getSwipeToRefresh()) {
5399 // Only enable swipe to refresh if the WebView is scrolled to the top.
5400 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5402 // Disable swipe to refresh.
5403 swipeRefreshLayout.setEnabled(false);
5407 // Reinforce the system UI visibility flags if in full screen browsing mode.
5408 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5409 if (inFullScreenBrowsingMode) {
5410 /* Hide the system bars.
5411 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5412 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5413 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5414 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5416 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5417 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5422 // Set the web chrome client.
5423 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5424 // Update the progress bar when a page is loading.
5426 public void onProgressChanged(WebView view, int progress) {
5427 // Update the progress bar.
5428 progressBar.setProgress(progress);
5430 // Set the visibility of the progress bar.
5431 if (progress < 100) {
5432 // Show the progress bar.
5433 progressBar.setVisibility(View.VISIBLE);
5435 // Hide the progress bar.
5436 progressBar.setVisibility(View.GONE);
5438 //Stop the swipe to refresh indicator if it is running
5439 swipeRefreshLayout.setRefreshing(false);
5441 // 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.
5442 nestedScrollWebView.setVisibility(View.VISIBLE);
5446 // Set the favorite icon when it changes.
5448 public void onReceivedIcon(WebView view, Bitmap icon) {
5449 // Only update the favorite icon if the website has finished loading.
5450 if (progressBar.getVisibility() == View.GONE) {
5451 // Store the new favorite icon.
5452 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5454 // Get the current page position.
5455 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5457 // Get the current tab.
5458 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5460 // Check to see if the tab has been populated.
5462 // Get the custom view from the tab.
5463 View tabView = tab.getCustomView();
5465 // Check to see if the custom tab view has been populated.
5466 if (tabView != null) {
5467 // Get the favorite icon image view from the tab.
5468 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5470 // Display the favorite icon in the tab.
5471 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5477 // Save a copy of the title when it changes.
5479 public void onReceivedTitle(WebView view, String title) {
5480 // Get the current page position.
5481 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5483 // Get the current tab.
5484 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5486 // Only populate the title text view if the tab has been fully created.
5488 // Get the custom view from the tab.
5489 View tabView = tab.getCustomView();
5491 // Only populate the title text view if the tab view has been fully populated.
5492 if (tabView != null) {
5493 // Get the title text view from the tab.
5494 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5496 // Set the title according to the URL.
5497 if (title.equals("about:blank")) {
5498 // Set the title to indicate a new tab.
5499 tabTitleTextView.setText(R.string.new_tab);
5501 // Set the title as the tab text.
5502 tabTitleTextView.setText(title);
5508 // Enter full screen video.
5510 public void onShowCustomView(View video, CustomViewCallback callback) {
5511 // Set the full screen video flag.
5512 displayingFullScreenVideo = true;
5514 // Pause the ad if this is the free flavor.
5515 if (BuildConfig.FLAVOR.contentEquals("free")) {
5516 // Get a handle for the ad view. This cannot be a class variable because it changes with each ad load.
5517 View adView = findViewById(R.id.adview);
5519 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5520 AdHelper.pauseAd(adView);
5523 // Hide the keyboard.
5524 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5526 // Hide the main content relative layout.
5527 mainContentRelativeLayout.setVisibility(View.GONE);
5529 /* Hide the system bars.
5530 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5531 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5532 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5533 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5535 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5536 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5538 // Disable the sliding drawers.
5539 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5541 // Add the video view to the full screen video frame layout.
5542 fullScreenVideoFrameLayout.addView(video);
5544 // Show the full screen video frame layout.
5545 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5547 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5548 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5551 // Exit full screen video.
5553 public void onHideCustomView() {
5554 // Exit the full screen video.
5555 exitFullScreenVideo();
5560 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5561 // Show the file chooser if the device is running API >= 21.
5562 if (Build.VERSION.SDK_INT >= 21) {
5563 // Store the file path callback.
5564 fileChooserCallback = filePathCallback;
5566 // Create an intent to open a chooser based on the file chooser parameters.
5567 Intent fileChooserIntent = fileChooserParams.createIntent();
5569 // Get a handle for the package manager.
5570 PackageManager packageManager = getPackageManager();
5572 // Check to see if the file chooser intent resolves to an installed package.
5573 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5574 // Start the file chooser intent.
5575 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5576 } else { // The file chooser intent will cause a crash.
5577 // Create a generic intent to open a chooser.
5578 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5580 // Request an openable file.
5581 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5583 // Set the file type to everything.
5584 genericFileChooserIntent.setType("*/*");
5586 // Start the generic file chooser intent.
5587 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5594 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5595 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5596 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5598 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5599 // Sanitize the url.
5600 url = sanitizeUrl(url);
5602 // Handle the URL according to the type.
5603 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5604 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5605 loadUrl(nestedScrollWebView, url);
5607 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5608 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5610 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5611 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5612 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5614 // Parse the url and set it as the data for the intent.
5615 emailIntent.setData(Uri.parse(url));
5617 // Open the email program in a new task instead of as part of Privacy Browser.
5618 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5622 startActivity(emailIntent);
5623 } catch (ActivityNotFoundException exception) {
5624 // Display a snackbar.
5625 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5629 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5631 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5632 // Open the dialer and load the phone number, but wait for the user to place the call.
5633 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5635 // Add the phone number to the intent.
5636 dialIntent.setData(Uri.parse(url));
5638 // Open the dialer in a new task instead of as part of Privacy Browser.
5639 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5643 startActivity(dialIntent);
5644 } catch (ActivityNotFoundException exception) {
5645 // Display a snackbar.
5646 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
5649 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5651 } else { // Load a system chooser to select an app that can handle the URL.
5652 // Open an app that can handle the URL.
5653 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5655 // Add the URL to the intent.
5656 genericIntent.setData(Uri.parse(url));
5658 // List all apps that can handle the URL instead of just opening the first one.
5659 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5661 // Open the app in a new task instead of as part of Privacy Browser.
5662 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5664 // Start the app or display a snackbar if no app is available to handle the URL.
5666 startActivity(genericIntent);
5667 } catch (ActivityNotFoundException exception) {
5668 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5671 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5676 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5678 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5679 // Check to see if the resource request is for the main URL.
5680 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5681 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5685 // 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.
5686 while (ultraPrivacy == null) {
5687 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5688 synchronized (this) {
5690 // Check to see if the blocklists have been populated after 100 ms.
5692 } catch (InterruptedException exception) {
5698 // Sanitize the URL.
5699 url = sanitizeUrl(url);
5701 // Create an empty web resource response to be used if the resource request is blocked.
5702 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5704 // Reset the whitelist results tracker.
5705 String[] whitelistResultStringArray = null;
5707 // Initialize the third party request tracker.
5708 boolean isThirdPartyRequest = false;
5710 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5711 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5713 // Store a copy of the current domain for use in later requests.
5714 String currentDomain = currentBaseDomain;
5716 // Nobody is happy when comparing null strings.
5717 if ((currentBaseDomain != null) && (url != null)) {
5718 // Convert the request URL to a URI.
5719 Uri requestUri = Uri.parse(url);
5721 // Get the request host name.
5722 String requestBaseDomain = requestUri.getHost();
5724 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5725 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5726 // Determine the current base domain.
5727 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5728 // Remove the first subdomain.
5729 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5732 // Determine the request base domain.
5733 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5734 // Remove the first subdomain.
5735 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5738 // Update the third party request tracker.
5739 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5743 // Get the current WebView page position.
5744 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5746 // Determine if the WebView is currently displayed.
5747 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5749 // Block third-party requests if enabled.
5750 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5751 // Add the result to the resource requests.
5752 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5754 // Increment the blocked requests counters.
5755 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5756 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5758 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5759 if (webViewDisplayed) {
5760 // Updating the UI must be run from the UI thread.
5761 activity.runOnUiThread(() -> {
5762 // Update the menu item titles.
5763 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5765 // Update the options menu if it has been populated.
5766 if (optionsMenu != null) {
5767 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5768 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5769 getString(R.string.block_all_third_party_requests));
5774 // Return an empty web resource response.
5775 return emptyWebResourceResponse;
5778 // Check UltraList if it is enabled.
5779 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5780 // Check the URL against UltraList.
5781 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5783 // Process the UltraList results.
5784 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5785 // Add the result to the resource requests.
5786 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5788 // Increment the blocked requests counters.
5789 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5790 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5792 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5793 if (webViewDisplayed) {
5794 // Updating the UI must be run from the UI thread.
5795 activity.runOnUiThread(() -> {
5796 // Update the menu item titles.
5797 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5799 // Update the options menu if it has been populated.
5800 if (optionsMenu != null) {
5801 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5802 optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5807 // The resource request was blocked. Return an empty web resource response.
5808 return emptyWebResourceResponse;
5809 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5810 // Add a whitelist entry to the resource requests array.
5811 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5813 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5818 // Check UltraPrivacy if it is enabled.
5819 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5820 // Check the URL against UltraPrivacy.
5821 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5823 // Process the UltraPrivacy results.
5824 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5825 // Add the result to the resource requests.
5826 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5827 ultraPrivacyResults[5]});
5829 // Increment the blocked requests counters.
5830 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5831 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5833 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5834 if (webViewDisplayed) {
5835 // Updating the UI must be run from the UI thread.
5836 activity.runOnUiThread(() -> {
5837 // Update the menu item titles.
5838 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5840 // Update the options menu if it has been populated.
5841 if (optionsMenu != null) {
5842 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5843 optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5848 // The resource request was blocked. Return an empty web resource response.
5849 return emptyWebResourceResponse;
5850 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5851 // Add a whitelist entry to the resource requests array.
5852 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5853 ultraPrivacyResults[5]});
5855 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5860 // Check EasyList if it is enabled.
5861 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
5862 // Check the URL against EasyList.
5863 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5865 // Process the EasyList results.
5866 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5867 // Add the result to the resource requests.
5868 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5870 // Increment the blocked requests counters.
5871 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5872 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5874 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5875 if (webViewDisplayed) {
5876 // Updating the UI must be run from the UI thread.
5877 activity.runOnUiThread(() -> {
5878 // Update the menu item titles.
5879 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5881 // Update the options menu if it has been populated.
5882 if (optionsMenu != null) {
5883 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5884 optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5889 // The resource request was blocked. Return an empty web resource response.
5890 return emptyWebResourceResponse;
5891 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5892 // Update the whitelist result string array tracker.
5893 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5897 // Check EasyPrivacy if it is enabled.
5898 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
5899 // Check the URL against EasyPrivacy.
5900 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5902 // Process the EasyPrivacy results.
5903 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5904 // Add the result to the resource requests.
5905 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5906 easyPrivacyResults[5]});
5908 // Increment the blocked requests counters.
5909 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5910 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5912 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5913 if (webViewDisplayed) {
5914 // Updating the UI must be run from the UI thread.
5915 activity.runOnUiThread(() -> {
5916 // Update the menu item titles.
5917 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5919 // Update the options menu if it has been populated.
5920 if (optionsMenu != null) {
5921 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5922 optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5927 // The resource request was blocked. Return an empty web resource response.
5928 return emptyWebResourceResponse;
5929 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5930 // Update the whitelist result string array tracker.
5931 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5935 // Check Fanboy’s Annoyance List if it is enabled.
5936 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5937 // Check the URL against Fanboy's Annoyance List.
5938 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5940 // Process the Fanboy's Annoyance List results.
5941 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5942 // Add the result to the resource requests.
5943 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5944 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5946 // Increment the blocked requests counters.
5947 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5948 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5950 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5951 if (webViewDisplayed) {
5952 // Updating the UI must be run from the UI thread.
5953 activity.runOnUiThread(() -> {
5954 // Update the menu item titles.
5955 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5957 // Update the options menu if it has been populated.
5958 if (optionsMenu != null) {
5959 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5960 optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5961 getString(R.string.fanboys_annoyance_list));
5966 // The resource request was blocked. Return an empty web resource response.
5967 return emptyWebResourceResponse;
5968 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5969 // Update the whitelist result string array tracker.
5970 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5971 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5973 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5974 // Check the URL against Fanboy's Annoyance List.
5975 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5977 // Process the Fanboy's Social Blocking List results.
5978 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5979 // Add the result to the resource requests.
5980 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5981 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5983 // Increment the blocked requests counters.
5984 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5985 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5987 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5988 if (webViewDisplayed) {
5989 // Updating the UI must be run from the UI thread.
5990 activity.runOnUiThread(() -> {
5991 // Update the menu item titles.
5992 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5994 // Update the options menu if it has been populated.
5995 if (optionsMenu != null) {
5996 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5997 optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5998 getString(R.string.fanboys_social_blocking_list));
6003 // The resource request was blocked. Return an empty web resource response.
6004 return emptyWebResourceResponse;
6005 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
6006 // Update the whitelist result string array tracker.
6007 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
6008 fanboysSocialListResults[4], fanboysSocialListResults[5]};
6012 // Add the request to the log because it hasn't been processed by any of the previous checks.
6013 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
6014 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
6015 } else { // The request didn't match any blocklist entry. Log it as a default request.
6016 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
6019 // The resource request has not been blocked. `return null` loads the requested resource.
6023 // Handle HTTP authentication requests.
6025 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
6026 // Store the handler.
6027 nestedScrollWebView.setHttpAuthHandler(handler);
6029 // Instantiate an HTTP authentication dialog.
6030 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
6032 // Show the HTTP authentication dialog.
6033 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
6037 public void onPageStarted(WebView view, String url, Bitmap favicon) {
6038 // Get the preferences.
6039 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
6041 // 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.
6042 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6043 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6044 swipeRefreshLayout.setPadding(0, 0, 0, 0);
6046 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6047 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6049 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6050 appBarHeight = appBarLayout.getHeight();
6052 // The swipe refresh layout must be manually moved below the app bar layout.
6053 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6055 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6056 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6059 // Reset the list of resource requests.
6060 nestedScrollWebView.clearResourceRequests();
6062 // Reset the requests counters.
6063 nestedScrollWebView.resetRequestsCounters();
6065 // Get the current page position.
6066 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6068 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6069 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6070 // Display the formatted URL text.
6071 urlEditText.setText(url);
6073 // Apply text highlighting to `urlTextBox`.
6076 // Hide the keyboard.
6077 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6080 // Reset the list of host IP addresses.
6081 nestedScrollWebView.clearCurrentIpAddresses();
6083 // Get a URI for the current URL.
6084 Uri currentUri = Uri.parse(url);
6086 // Get the IP addresses for the host.
6087 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6089 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6090 if (optionsMenu != null) {
6092 optionsRefreshMenuItem.setTitle(R.string.stop);
6094 // Get the app bar and theme preferences.
6095 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6097 // If the icon is displayed in the AppBar, set it according to the theme.
6098 if (displayAdditionalAppBarIcons) {
6099 // Get the current theme status.
6100 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6102 // Set the stop icon according to the theme.
6103 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6104 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_day);
6106 optionsRefreshMenuItem.setIcon(R.drawable.close_blue_night);
6113 public void onPageFinished(WebView view, String url) {
6114 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6115 if (nestedScrollWebView.getAcceptCookies() && Build.VERSION.SDK_INT >= 21) {
6116 CookieManager.getInstance().flush();
6119 // Update the Refresh menu item if the options menu has been created.
6120 if (optionsMenu != null) {
6121 // Reset the Refresh title.
6122 optionsRefreshMenuItem.setTitle(R.string.refresh);
6124 // Get the app bar and theme preferences.
6125 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6127 // If the icon is displayed in the app bar, reset it according to the theme.
6128 if (displayAdditionalAppBarIcons) {
6129 // Get the current theme status.
6130 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6132 // Set the icon according to the theme.
6133 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
6134 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6136 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6141 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6142 if (incognitoModeEnabled) {
6143 // Clear the cache. `true` includes disk files.
6144 nestedScrollWebView.clearCache(true);
6146 // Clear the back/forward history.
6147 nestedScrollWebView.clearHistory();
6149 // Manually delete cache folders.
6151 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6152 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6153 String privateDataDirectoryString = getApplicationInfo().dataDir;
6155 // Delete the main cache directory.
6156 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6158 // Delete the secondary `Service Worker` cache directory.
6159 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6160 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6161 } catch (IOException exception) {
6162 // Do nothing if an error is thrown.
6165 // Clear the logcat.
6167 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
6168 Runtime.getRuntime().exec("logcat -b all -c");
6169 } catch (IOException exception) {
6174 // Get the current page position.
6175 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6177 // 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.
6178 String currentUrl = nestedScrollWebView.getUrl();
6180 // Get the current tab.
6181 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6183 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6184 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6185 // Probably some sort of race condition when Privacy Browser is being resumed.
6186 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6187 // Check to see if the URL is `about:blank`.
6188 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6189 // Display the hint in the URL edit text.
6190 urlEditText.setText("");
6192 // Request focus for the URL text box.
6193 urlEditText.requestFocus();
6195 // Display the keyboard.
6196 inputMethodManager.showSoftInput(urlEditText, 0);
6198 // Apply the domain settings. This clears any settings from the previous domain.
6199 applyDomainSettings(nestedScrollWebView, "", true, false, false);
6201 // Only populate the title text view if the tab has been fully created.
6203 // Get the custom view from the tab.
6204 View tabView = tab.getCustomView();
6206 // Remove the incorrect warning below that the current tab view might be null.
6207 assert tabView != null;
6209 // Get the title text view from the tab.
6210 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6212 // Set the title as the tab text.
6213 tabTitleTextView.setText(R.string.new_tab);
6215 } else { // The WebView has loaded a webpage.
6216 // Update the URL edit text if it is not currently being edited.
6217 if (!urlEditText.hasFocus()) {
6218 // 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.
6219 String sanitizedUrl = sanitizeUrl(currentUrl);
6221 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6222 urlEditText.setText(sanitizedUrl);
6224 // Apply text highlighting to the URL.
6228 // Only populate the title text view if the tab has been fully created.
6230 // Get the custom view from the tab.
6231 View tabView = tab.getCustomView();
6233 // Remove the incorrect warning below that the current tab view might be null.
6234 assert tabView != null;
6236 // Get the title text view from the tab.
6237 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6239 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6240 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6246 // Handle SSL Certificate errors.
6248 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6249 // Get the current website SSL certificate.
6250 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6252 // Extract the individual pieces of information from the current website SSL certificate.
6253 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6254 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6255 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6256 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6257 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6258 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6259 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6260 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6262 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6263 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6264 // Get the pinned SSL certificate.
6265 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6267 // Extract the arrays from the array list.
6268 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6269 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6271 // Check if the current SSL certificate matches the pinned certificate.
6272 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6273 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6274 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6275 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6277 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6280 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6281 // Store the SSL error handler.
6282 nestedScrollWebView.setSslErrorHandler(handler);
6284 // Prevent the dialog from displaying if the app window is not visible.
6285 // 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.
6286 while (!activity.getWindow().isActive()) {
6288 // The window is not active. Wait 1 second.
6290 } catch (InterruptedException e) {
6295 // Instantiate an SSL certificate error alert dialog.
6296 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6298 // Show the SSL certificate error dialog.
6299 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6304 // Check to see if the state is being restored.
6305 if (restoringState) { // The state is being restored.
6306 // Resume the nested scroll WebView JavaScript timers.
6307 nestedScrollWebView.resumeTimers();
6308 } else if (pageNumber == 0) { // The first page is being loaded.
6309 // Set this nested scroll WebView as the current WebView.
6310 currentWebView = nestedScrollWebView;
6312 // Initialize the URL to load string.
6313 String urlToLoadString;
6315 // Get the intent that started the app.
6316 Intent launchingIntent = getIntent();
6318 // Reset the intent. This prevents a duplicate tab from being created on restart.
6319 setIntent(new Intent());
6321 // Get the information from the intent.
6322 String launchingIntentAction = launchingIntent.getAction();
6323 Uri launchingIntentUriData = launchingIntent.getData();
6324 String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6326 // Parse the launching intent URL.
6327 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6328 // Create an encoded URL string.
6329 String encodedUrlString;
6331 // Sanitize the search input and convert it to a search.
6333 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6334 } catch (UnsupportedEncodingException exception) {
6335 encodedUrlString = "";
6338 // Store the web search as the URL to load.
6339 urlToLoadString = searchURL + encodedUrlString;
6340 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
6341 // Store the URI as a URL.
6342 urlToLoadString = launchingIntentUriData.toString();
6343 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
6345 urlToLoadString = launchingIntentStringExtra;
6346 } else if (!url.equals("")) { // The activity has been restarted.
6347 // Load the saved URL.
6348 urlToLoadString = url;
6349 } else { // The is no URL in the intent.
6350 // Store the homepage to be loaded.
6351 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6354 // Load the website if not waiting for the proxy.
6355 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6356 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6357 } else { // Load the URL.
6358 loadUrl(nestedScrollWebView, urlToLoadString);
6361 // 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.
6362 // 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.
6363 setIntent(new Intent());
6364 } else { // This is not the first tab.
6366 loadUrl(nestedScrollWebView, url);
6368 // Set the focus and display the keyboard if the URL is blank.
6369 if (url.equals("")) {
6370 // Request focus for the URL text box.
6371 urlEditText.requestFocus();
6373 // Create a display keyboard handler.
6374 Handler displayKeyboardHandler = new Handler();
6376 // Create a display keyboard runnable.
6377 Runnable displayKeyboardRunnable = () -> {
6378 // Display the keyboard.
6379 inputMethodManager.showSoftInput(urlEditText, 0);
6382 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6383 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);