2 * Copyright © 2015-2020 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.database.Cursor;
41 import android.graphics.Bitmap;
42 import android.graphics.BitmapFactory;
43 import android.graphics.Typeface;
44 import android.graphics.drawable.BitmapDrawable;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.net.http.SslCertificate;
48 import android.net.http.SslError;
49 import android.os.Build;
50 import android.os.Bundle;
51 import android.os.Handler;
52 import android.os.Message;
53 import android.preference.PreferenceManager;
54 import android.print.PrintDocumentAdapter;
55 import android.print.PrintManager;
56 import android.text.Editable;
57 import android.text.Spanned;
58 import android.text.TextWatcher;
59 import android.text.style.ForegroundColorSpan;
60 import android.util.Patterns;
61 import android.view.ContextMenu;
62 import android.view.GestureDetector;
63 import android.view.KeyEvent;
64 import android.view.Menu;
65 import android.view.MenuItem;
66 import android.view.MotionEvent;
67 import android.view.View;
68 import android.view.ViewGroup;
69 import android.view.WindowManager;
70 import android.view.inputmethod.InputMethodManager;
71 import android.webkit.CookieManager;
72 import android.webkit.HttpAuthHandler;
73 import android.webkit.SslErrorHandler;
74 import android.webkit.ValueCallback;
75 import android.webkit.WebBackForwardList;
76 import android.webkit.WebChromeClient;
77 import android.webkit.WebResourceResponse;
78 import android.webkit.WebSettings;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.ArrayAdapter;
84 import android.widget.CursorAdapter;
85 import android.widget.EditText;
86 import android.widget.FrameLayout;
87 import android.widget.ImageView;
88 import android.widget.LinearLayout;
89 import android.widget.ListView;
90 import android.widget.ProgressBar;
91 import android.widget.RadioButton;
92 import android.widget.RelativeLayout;
93 import android.widget.TextView;
95 import androidx.annotation.NonNull;
96 import androidx.appcompat.app.ActionBar;
97 import androidx.appcompat.app.ActionBarDrawerToggle;
98 import androidx.appcompat.app.AppCompatActivity;
99 import androidx.appcompat.widget.Toolbar;
100 import androidx.coordinatorlayout.widget.CoordinatorLayout;
101 import androidx.core.app.ActivityCompat;
102 import androidx.core.content.ContextCompat;
103 import androidx.core.view.GravityCompat;
104 import androidx.drawerlayout.widget.DrawerLayout;
105 import androidx.fragment.app.DialogFragment;
106 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
107 import androidx.viewpager.widget.ViewPager;
109 import com.google.android.material.appbar.AppBarLayout;
110 import com.google.android.material.floatingactionbutton.FloatingActionButton;
111 import com.google.android.material.navigation.NavigationView;
112 import com.google.android.material.snackbar.Snackbar;
113 import com.google.android.material.tabs.TabLayout;
115 import com.stoutner.privacybrowser.BuildConfig;
116 import com.stoutner.privacybrowser.R;
117 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
118 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
119 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
120 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
121 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
122 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
123 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
124 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
125 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
126 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
127 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
128 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
129 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
130 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
131 import com.stoutner.privacybrowser.dialogs.OpenDialog;
132 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
133 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
134 import com.stoutner.privacybrowser.dialogs.SaveDialog;
135 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
136 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
137 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
138 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
139 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
140 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
141 import com.stoutner.privacybrowser.helpers.AdHelper;
142 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
143 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
144 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
145 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
146 import com.stoutner.privacybrowser.helpers.FileNameHelper;
147 import com.stoutner.privacybrowser.helpers.ProxyHelper;
148 import com.stoutner.privacybrowser.views.NestedScrollWebView;
150 import java.io.ByteArrayInputStream;
151 import java.io.ByteArrayOutputStream;
153 import java.io.IOException;
154 import java.io.UnsupportedEncodingException;
155 import java.net.MalformedURLException;
157 import java.net.URLDecoder;
158 import java.net.URLEncoder;
159 import java.text.NumberFormat;
160 import java.util.ArrayList;
161 import java.util.Date;
162 import java.util.HashMap;
163 import java.util.HashSet;
164 import java.util.List;
165 import java.util.Map;
166 import java.util.Objects;
167 import java.util.Set;
169 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
170 EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener,
171 OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveWebpageListener,
172 StoragePermissionDialog.StoragePermissionDialogListener, UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
174 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
175 public static String orbotStatus = "unknown";
177 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
178 public static WebViewPagerAdapter webViewPagerAdapter;
180 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
181 public static boolean loadUrlOnRestart;
182 public static String urlToLoadOnRestart;
184 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
185 public static boolean restartFromBookmarksActivity;
187 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
188 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
189 public static String currentBookmarksFolder;
191 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
192 public final static int UNRECOGNIZED_USER_AGENT = -1;
193 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
194 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
195 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
196 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
197 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
199 // Start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
200 public final static int BROWSE_OPEN_REQUEST_CODE = 0;
201 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 1;
202 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 2;
204 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
205 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
206 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
207 public static String proxyMode = ProxyHelper.NONE;
210 // The permission result request codes are used in `onCreateContextMenu()`, `onRequestPermissionResult()`, `onSaveWebpage()`, `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
211 private final int PERMISSION_OPEN_REQUEST_CODE = 0;
212 private final int PERMISSION_SAVE_URL_REQUEST_CODE = 1;
213 private final int PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE = 2;
214 private final int PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE = 3;
216 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
217 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
218 private NestedScrollWebView currentWebView;
220 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
221 private final Map<String, String> customHeaders = new HashMap<>();
223 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
224 private String searchURL;
226 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
227 private Menu optionsMenu;
229 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
230 private ArrayList<List<String[]>> easyList;
231 private ArrayList<List<String[]>> easyPrivacy;
232 private ArrayList<List<String[]>> fanboysAnnoyanceList;
233 private ArrayList<List<String[]>> fanboysSocialList;
234 private ArrayList<List<String[]>> ultraList;
235 private ArrayList<List<String[]>> ultraPrivacy;
237 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
238 private String webViewDefaultUserAgent;
240 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
241 private boolean incognitoModeEnabled;
243 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
244 private boolean fullScreenBrowsingModeEnabled;
246 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
247 private boolean inFullScreenBrowsingMode;
249 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
250 private boolean hideAppBar;
251 private boolean scrollAppBar;
253 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
254 private boolean loadingNewIntent;
256 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
257 private boolean reapplyDomainSettingsOnRestart;
259 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
260 private boolean reapplyAppSettingsOnRestart;
262 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
263 private boolean displayingFullScreenVideo;
265 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
266 private BroadcastReceiver orbotStatusBroadcastReceiver;
268 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
269 private boolean waitingForProxy = false;
271 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
272 private ActionBarDrawerToggle actionBarDrawerToggle;
274 // The color spans are used in `onCreate()` and `highlightUrlText()`.
275 private ForegroundColorSpan redColorSpan;
276 private ForegroundColorSpan initialGrayColorSpan;
277 private ForegroundColorSpan finalGrayColorSpan;
279 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
280 private int drawerHeaderPaddingLeftAndRight;
281 private int drawerHeaderPaddingTop;
282 private int drawerHeaderPaddingBottom;
284 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
285 // and `loadBookmarksFolder()`.
286 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
288 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
289 private Cursor bookmarksCursor;
291 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
292 private CursorAdapter bookmarksCursorAdapter;
294 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
295 private String oldFolderNameString;
297 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
298 private ValueCallback<Uri[]> fileChooserCallback;
300 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
301 private int defaultProgressViewStartOffset;
302 private int defaultProgressViewEndOffset;
304 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
305 private int swipeRefreshLayoutPaddingTop;
307 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
308 private boolean sanitizeGoogleAnalytics;
309 private boolean sanitizeFacebookClickIds;
310 private boolean sanitizeTwitterAmpRedirects;
312 // The file path strings are used in `onSaveWebpage()` and `onRequestPermissionResult()`
313 private String openFilePath;
314 private String saveWebpageUrl;
315 private String saveWebpageFilePath;
318 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
319 @SuppressLint("ClickableViewAccessibility")
320 protected void onCreate(Bundle savedInstanceState) {
321 // 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.
322 if (Build.VERSION.SDK_INT >= 21) {
323 WebView.enableSlowWholeDocumentDraw();
326 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
327 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
329 // Get a handle for the shared preferences.
330 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
332 // Get the theme and screenshot preferences.
333 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
334 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
336 // Disable screenshots if not allowed.
337 if (!allowScreenshots) {
338 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
341 // Set the activity theme.
343 setTheme(R.style.PrivacyBrowserDark);
345 setTheme(R.style.PrivacyBrowserLight);
348 // Run the default commands.
349 super.onCreate(savedInstanceState);
351 // Set the content view.
352 setContentView(R.layout.main_framelayout);
354 // Get handles for the views that need to be modified.
355 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
356 Toolbar toolbar = findViewById(R.id.toolbar);
357 ViewPager webViewPager = findViewById(R.id.webviewpager);
359 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
360 setSupportActionBar(toolbar);
362 // Get a handle for the action bar.
363 ActionBar actionBar = getSupportActionBar();
365 // This is needed to get rid of the Android Studio warning that the action bar might be null.
366 assert actionBar != null;
368 // Add the custom layout, which shows the URL text bar.
369 actionBar.setCustomView(R.layout.url_app_bar);
370 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
372 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
373 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
375 // Create the hamburger icon at the start of the AppBar.
376 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
378 // Initialize the web view pager adapter.
379 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
381 // Set the pager adapter on the web view pager.
382 webViewPager.setAdapter(webViewPagerAdapter);
384 // Store up to 100 tabs in memory.
385 webViewPager.setOffscreenPageLimit(100);
387 // Populate the blocklists.
388 new PopulateBlocklists(this, this).execute();
392 protected void onNewIntent(Intent intent) {
393 // Run the default commands.
394 super.onNewIntent(intent);
396 // Replace the intent that started the app with this one.
399 // Process the intent here if Privacy Browser is fully initialized. If the process has been killed by the system while sitting in the background, this will be handled in `initializeWebView()`.
400 if (ultraPrivacy != null) {
401 // Get the information from the intent.
402 String intentAction = intent.getAction();
403 Uri intentUriData = intent.getData();
405 // Determine if this is a web search.
406 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
408 // 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.
409 if (intentUriData != null || isWebSearch) {
410 // Get the shared preferences.
411 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
413 // Create a URL string.
416 // If the intent action is a web search, perform the search.
418 // Create an encoded URL string.
419 String encodedUrlString;
421 // Sanitize the search input and convert it to a search.
423 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
424 } catch (UnsupportedEncodingException exception) {
425 encodedUrlString = "";
428 // Add the base search URL.
429 url = searchURL + encodedUrlString;
430 } else { // The intent should contain a URL.
431 // Set the intent data as the URL.
432 url = intentUriData.toString();
435 // Add a new tab if specified in the preferences.
436 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
437 // Set the loading new intent flag.
438 loadingNewIntent = true;
441 addNewTab(url, true);
442 } else { // Load the URL in the current tab.
444 loadUrl(currentWebView, url);
447 // Get a handle for the drawer layout.
448 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
450 // Close the navigation drawer if it is open.
451 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
452 drawerLayout.closeDrawer(GravityCompat.START);
455 // Close the bookmarks drawer if it is open.
456 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
457 drawerLayout.closeDrawer(GravityCompat.END);
464 public void onRestart() {
465 // Run the default commands.
468 // Apply the app settings if returning from the Settings activity.
469 if (reapplyAppSettingsOnRestart) {
470 // Reset the reapply app settings on restart tracker.
471 reapplyAppSettingsOnRestart = false;
473 // Apply the app settings.
477 // Apply the domain settings if returning from the settings or domains activity.
478 if (reapplyDomainSettingsOnRestart) {
479 // Reset the reapply domain settings on restart tracker.
480 reapplyDomainSettingsOnRestart = false;
482 // Reapply the domain settings for each tab.
483 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
484 // Get the WebView tab fragment.
485 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
487 // Get the fragment view.
488 View fragmentView = webViewTabFragment.getView();
490 // Only reload the WebViews if they exist.
491 if (fragmentView != null) {
492 // Get the nested scroll WebView from the tab fragment.
493 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
495 // Reset the current domain name so the domain settings will be reapplied.
496 nestedScrollWebView.resetCurrentDomainName();
498 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
499 if (nestedScrollWebView.getUrl() != null) {
500 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
506 // Load the URL on restart (used when loading a bookmark).
507 if (loadUrlOnRestart) {
508 // Load the specified URL.
509 loadUrl(currentWebView, urlToLoadOnRestart);
511 // Reset the load on restart tracker.
512 loadUrlOnRestart = false;
515 // Update the bookmarks drawer if returning from the Bookmarks activity.
516 if (restartFromBookmarksActivity) {
517 // Get a handle for the drawer layout.
518 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
520 // Close the bookmarks drawer.
521 drawerLayout.closeDrawer(GravityCompat.END);
523 // Reload the bookmarks drawer.
524 loadBookmarksFolder();
526 // Reset `restartFromBookmarksActivity`.
527 restartFromBookmarksActivity = false;
530 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
531 updatePrivacyIcons(true);
534 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
536 public void onResume() {
537 // Run the default commands.
540 // Resume any WebViews.
541 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
542 // Get the WebView tab fragment.
543 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
545 // Get the fragment view.
546 View fragmentView = webViewTabFragment.getView();
548 // Only resume the WebViews if they exist (they won't when the app is first created).
549 if (fragmentView != null) {
550 // Get the nested scroll WebView from the tab fragment.
551 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
553 // Resume the nested scroll WebView JavaScript timers.
554 nestedScrollWebView.resumeTimers();
556 // Resume the nested scroll WebView.
557 nestedScrollWebView.onResume();
561 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
562 if (!proxyMode.equals(ProxyHelper.NONE)) {
566 // Reapply any system UI flags and the ad in the free flavor.
567 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
568 // Get a handle for the root frame layouts.
569 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
571 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
572 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
574 /* Hide the system bars.
575 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
576 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
577 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
578 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
580 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
581 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
582 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
584 AdHelper.resumeAd(findViewById(R.id.adview));
589 public void onPause() {
590 // Run the default commands.
593 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
594 // Get the WebView tab fragment.
595 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
597 // Get the fragment view.
598 View fragmentView = webViewTabFragment.getView();
600 // Only pause the WebViews if they exist (they won't when the app is first created).
601 if (fragmentView != null) {
602 // Get the nested scroll WebView from the tab fragment.
603 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
605 // Pause the nested scroll WebView.
606 nestedScrollWebView.onPause();
608 // Pause the nested scroll WebView JavaScript timers.
609 nestedScrollWebView.pauseTimers();
613 // Pause the ad or it will continue to consume resources in the background on the free flavor.
614 if (BuildConfig.FLAVOR.contentEquals("free")) {
616 AdHelper.pauseAd(findViewById(R.id.adview));
621 public void onDestroy() {
622 // Unregister the orbot status broadcast receiver.
623 this.unregisterReceiver(orbotStatusBroadcastReceiver);
625 // Close the bookmarks cursor and database.
626 bookmarksCursor.close();
627 bookmarksDatabaseHelper.close();
629 // Run the default commands.
634 public boolean onCreateOptionsMenu(Menu menu) {
635 // Inflate the menu. This adds items to the action bar if it is present.
636 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
638 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
641 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
642 updatePrivacyIcons(false);
644 // Get handles for the menu items.
645 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
646 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
647 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
648 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
649 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
650 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
651 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
653 // Only display third-party cookies if API >= 21
654 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
656 // Only display the form data menu items if the API < 26.
657 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
658 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
660 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
661 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
663 // Only show Ad Consent if this is the free flavor.
664 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
666 // Get the shared preferences.
667 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
669 // Get the dark theme and app bar preferences..
670 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
671 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
673 // 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.
674 if (displayAdditionalAppBarIcons) {
675 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
676 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
677 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
678 } else { //Do not display the additional icons.
679 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
680 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
681 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
684 // Replace Refresh with Stop if a URL is already loading.
685 if (currentWebView != null && currentWebView.getProgress() != 100) {
687 refreshMenuItem.setTitle(R.string.stop);
689 // If the icon is displayed in the AppBar, set it according to the theme.
690 if (displayAdditionalAppBarIcons) {
692 refreshMenuItem.setIcon(R.drawable.close_dark);
694 refreshMenuItem.setIcon(R.drawable.close_light);
704 public boolean onPrepareOptionsMenu(Menu menu) {
705 // Get handles for the menu items.
706 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
707 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
708 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
709 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
710 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
711 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
712 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
713 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
714 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
715 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
716 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
717 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
718 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
719 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
720 MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
721 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
722 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
723 MenuItem proxyMenuItem = menu.findItem(R.id.proxy);
724 MenuItem userAgentMenuItem = menu.findItem(R.id.user_agent);
725 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
726 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
727 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
728 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
729 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
731 // Get a handle for the cookie manager.
732 CookieManager cookieManager = CookieManager.getInstance();
734 // Initialize the current user agent string and the font size.
735 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
738 // 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.
739 if (currentWebView != null) {
740 // Set the add or edit domain text.
741 if (currentWebView.getDomainSettingsApplied()) {
742 addOrEditDomain.setTitle(R.string.edit_domain_settings);
744 addOrEditDomain.setTitle(R.string.add_domain_settings);
747 // Get the current user agent from the WebView.
748 currentUserAgent = currentWebView.getSettings().getUserAgentString();
750 // Get the current font size from the
751 fontSize = currentWebView.getSettings().getTextZoom();
753 // Set the status of the menu item checkboxes.
754 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
755 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
756 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
757 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
758 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
759 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
760 ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
761 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
762 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
763 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
764 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
765 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
766 nightModeMenuItem.setChecked(currentWebView.getNightMode());
768 // Initialize the display names for the blocklists with the number of blocked requests.
769 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
770 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
771 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
772 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
773 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
774 ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
775 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
776 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
778 // Only modify third-party cookies if the API >= 21.
779 if (Build.VERSION.SDK_INT >= 21) {
780 // Set the status of the third-party cookies checkbox.
781 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
783 // Enable third-party cookies if first-party cookies are enabled.
784 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
787 // Enable DOM Storage if JavaScript is enabled.
788 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
791 // Set the checked status of the first party cookies menu item.
792 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
794 // Enable Clear Cookies if there are any.
795 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
797 // 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`.
798 String privateDataDirectoryString = getApplicationInfo().dataDir;
800 // Get a count of the number of files in the Local Storage directory.
801 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
802 int localStorageDirectoryNumberOfFiles = 0;
803 if (localStorageDirectory.exists()) {
804 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
805 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
808 // Get a count of the number of files in the IndexedDB directory.
809 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
810 int indexedDBDirectoryNumberOfFiles = 0;
811 if (indexedDBDirectory.exists()) {
812 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
813 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
816 // Enable Clear DOM Storage if there is any.
817 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
819 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
820 if (Build.VERSION.SDK_INT < 26) {
821 // Get the WebView database.
822 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
824 // Enable the clear form data menu item if there is anything to clear.
825 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
828 // Enable Clear Data if any of the submenu items are enabled.
829 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
831 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
832 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
834 // Set the proxy title and check the applied proxy.
836 case ProxyHelper.NONE:
837 // Set the proxy title.
838 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
840 // Check the proxy None radio button.
841 menu.findItem(R.id.proxy_none).setChecked(true);
844 case ProxyHelper.TOR:
845 // Set the proxy title.
846 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
848 // Check the proxy Tor radio button.
849 menu.findItem(R.id.proxy_tor).setChecked(true);
852 case ProxyHelper.I2P:
853 // Set the proxy title.
854 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
856 // Check the proxy I2P radio button.
857 menu.findItem(R.id.proxy_i2p).setChecked(true);
860 case ProxyHelper.CUSTOM:
861 // Set the proxy title.
862 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
864 // Check the proxy Custom radio button.
865 menu.findItem(R.id.proxy_custom).setChecked(true);
869 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
870 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
871 // Update the user agent menu item title.
872 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
874 // Select the Privacy Browser radio box.
875 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
876 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
877 // Update the user agent menu item title.
878 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
880 // Select the WebView Default radio box.
881 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
882 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
883 // Update the user agent menu item title.
884 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
886 // Select the Firefox on Android radio box.
887 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
888 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
889 // Update the user agent menu item title.
890 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
892 // Select the Chrome on Android radio box.
893 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
894 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
895 // Update the user agent menu item title.
896 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
898 // Select the Safari on iOS radio box.
899 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
900 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
901 // Update the user agent menu item title.
902 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
904 // Select the Firefox on Linux radio box.
905 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
906 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
907 // Update the user agent menu item title.
908 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
910 // Select the Chromium on Linux radio box.
911 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
912 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
913 // Update the user agent menu item title.
914 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
916 // Select the Firefox on Windows radio box.
917 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
918 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
919 // Update the user agent menu item title.
920 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
922 // Select the Chrome on Windows radio box.
923 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
924 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
925 // Update the user agent menu item title.
926 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
928 // Select the Edge on Windows radio box.
929 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
930 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
931 // Update the user agent menu item title.
932 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
934 // Select the Internet on Windows radio box.
935 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
936 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
937 // Update the user agent menu item title.
938 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
940 // Select the Safari on macOS radio box.
941 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
942 } else { // Custom user agent.
943 // Update the user agent menu item title.
944 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
946 // Select the Custom radio box.
947 menu.findItem(R.id.user_agent_custom).setChecked(true);
950 // Set the font size title.
951 fontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
953 // Run all the other default commands.
954 super.onPrepareOptionsMenu(menu);
961 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
962 @SuppressLint("SetJavaScriptEnabled")
963 public boolean onOptionsItemSelected(MenuItem menuItem) {
964 // Get the selected menu item ID.
965 int menuItemId = menuItem.getItemId();
967 // Get a handle for the shared preferences.
968 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
970 // Get a handle for the cookie manager.
971 CookieManager cookieManager = CookieManager.getInstance();
973 // Run the commands that correlate to the selected menu item.
974 switch (menuItemId) {
975 case R.id.toggle_javascript:
976 // Toggle the JavaScript status.
977 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
979 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
980 updatePrivacyIcons(true);
982 // Display a `Snackbar`.
983 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
984 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
985 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
986 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
987 } else { // Privacy mode.
988 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
991 // Reload the current WebView.
992 currentWebView.reload();
994 // Consume the event.
998 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
999 // Reload the current WebView.
1000 currentWebView.reload();
1001 } else { // The stop button was pushed.
1002 // Stop the loading of the WebView.
1003 currentWebView.stopLoading();
1006 // Consume the event.
1009 case R.id.bookmarks:
1010 // Get a handle for the drawer layout.
1011 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1013 // Open the bookmarks drawer.
1014 drawerLayout.openDrawer(GravityCompat.END);
1016 // Consume the event.
1019 case R.id.toggle_first_party_cookies:
1020 // Switch the first-party cookie status.
1021 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1023 // Store the first-party cookie status.
1024 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1026 // Update the menu checkbox.
1027 menuItem.setChecked(cookieManager.acceptCookie());
1029 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1030 updatePrivacyIcons(true);
1032 // Display a snackbar.
1033 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1034 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1035 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1036 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1037 } else { // Privacy mode.
1038 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1041 // Reload the current WebView.
1042 currentWebView.reload();
1044 // Consume the event.
1047 case R.id.toggle_third_party_cookies:
1048 if (Build.VERSION.SDK_INT >= 21) {
1049 // Switch the status of thirdPartyCookiesEnabled.
1050 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1052 // Update the menu checkbox.
1053 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1055 // Display a snackbar.
1056 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1057 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1059 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1062 // Reload the current WebView.
1063 currentWebView.reload();
1064 } // Else do nothing because SDK < 21.
1066 // Consume the event.
1069 case R.id.toggle_dom_storage:
1070 // Toggle the status of domStorageEnabled.
1071 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1073 // Update the menu checkbox.
1074 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1076 // Update the privacy icon. `true` refreshes the app bar icons.
1077 updatePrivacyIcons(true);
1079 // Display a snackbar.
1080 if (currentWebView.getSettings().getDomStorageEnabled()) {
1081 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1083 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1086 // Reload the current WebView.
1087 currentWebView.reload();
1089 // Consume the event.
1092 // Form data can be removed once the minimum API >= 26.
1093 case R.id.toggle_save_form_data:
1094 // Switch the status of saveFormDataEnabled.
1095 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1097 // Update the menu checkbox.
1098 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1100 // Display a snackbar.
1101 if (currentWebView.getSettings().getSaveFormData()) {
1102 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1104 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1107 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1108 updatePrivacyIcons(true);
1110 // Reload the current WebView.
1111 currentWebView.reload();
1113 // Consume the event.
1116 case R.id.clear_cookies:
1117 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1118 .setAction(R.string.undo, v -> {
1119 // Do nothing because everything will be handled by `onDismissed()` below.
1121 .addCallback(new Snackbar.Callback() {
1122 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1124 public void onDismissed(Snackbar snackbar, int event) {
1125 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1126 // Delete the cookies, which command varies by SDK.
1127 if (Build.VERSION.SDK_INT < 21) {
1128 cookieManager.removeAllCookie();
1130 cookieManager.removeAllCookies(null);
1137 // Consume the event.
1140 case R.id.clear_dom_storage:
1141 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1142 .setAction(R.string.undo, v -> {
1143 // Do nothing because everything will be handled by `onDismissed()` below.
1145 .addCallback(new Snackbar.Callback() {
1146 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1148 public void onDismissed(Snackbar snackbar, int event) {
1149 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1150 // Delete the DOM Storage.
1151 WebStorage webStorage = WebStorage.getInstance();
1152 webStorage.deleteAllData();
1154 // Initialize a handler to manually delete the DOM storage files and directories.
1155 Handler deleteDomStorageHandler = new Handler();
1157 // Setup a runnable to manually delete the DOM storage files and directories.
1158 Runnable deleteDomStorageRunnable = () -> {
1160 // Get a handle for the runtime.
1161 Runtime runtime = Runtime.getRuntime();
1163 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1164 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1165 String privateDataDirectoryString = getApplicationInfo().dataDir;
1167 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1168 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1170 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1171 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1172 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1173 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1174 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1176 // Wait for the processes to finish.
1177 deleteLocalStorageProcess.waitFor();
1178 deleteIndexProcess.waitFor();
1179 deleteQuotaManagerProcess.waitFor();
1180 deleteQuotaManagerJournalProcess.waitFor();
1181 deleteDatabasesProcess.waitFor();
1182 } catch (Exception exception) {
1183 // Do nothing if an error is thrown.
1187 // Manually delete the DOM storage files after 200 milliseconds.
1188 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1194 // Consume the event.
1197 // Form data can be remove once the minimum API >= 26.
1198 case R.id.clear_form_data:
1199 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1200 .setAction(R.string.undo, v -> {
1201 // Do nothing because everything will be handled by `onDismissed()` below.
1203 .addCallback(new Snackbar.Callback() {
1204 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1206 public void onDismissed(Snackbar snackbar, int event) {
1207 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1208 // Delete the form data.
1209 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1210 mainWebViewDatabase.clearFormData();
1216 // Consume the event.
1220 // Toggle the EasyList status.
1221 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1223 // Update the menu checkbox.
1224 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1226 // Reload the current WebView.
1227 currentWebView.reload();
1229 // Consume the event.
1232 case R.id.easyprivacy:
1233 // Toggle the EasyPrivacy status.
1234 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1236 // Update the menu checkbox.
1237 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1239 // Reload the current WebView.
1240 currentWebView.reload();
1242 // Consume the event.
1245 case R.id.fanboys_annoyance_list:
1246 // Toggle Fanboy's Annoyance List status.
1247 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1249 // Update the menu checkbox.
1250 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1252 // Update the staus of Fanboy's Social Blocking List.
1253 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1254 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1256 // Reload the current WebView.
1257 currentWebView.reload();
1259 // Consume the event.
1262 case R.id.fanboys_social_blocking_list:
1263 // Toggle Fanboy's Social Blocking List status.
1264 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1266 // Update the menu checkbox.
1267 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1269 // Reload the current WebView.
1270 currentWebView.reload();
1272 // Consume the event.
1275 case R.id.ultralist:
1276 // Toggle the UltraList status.
1277 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1279 // Update the menu checkbox.
1280 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1282 // Reload the current WebView.
1283 currentWebView.reload();
1285 // Consume the event.
1288 case R.id.ultraprivacy:
1289 // Toggle the UltraPrivacy status.
1290 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1292 // Update the menu checkbox.
1293 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1295 // Reload the current WebView.
1296 currentWebView.reload();
1298 // Consume the event.
1301 case R.id.block_all_third_party_requests:
1302 //Toggle the third-party requests blocker status.
1303 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1305 // Update the menu checkbox.
1306 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1308 // Reload the current WebView.
1309 currentWebView.reload();
1311 // Consume the event.
1314 case R.id.proxy_none:
1315 // Update the proxy mode.
1316 proxyMode = ProxyHelper.NONE;
1318 // Apply the proxy mode.
1321 // Consume the event.
1324 case R.id.proxy_tor:
1325 // Update the proxy mode.
1326 proxyMode = ProxyHelper.TOR;
1328 // Apply the proxy mode.
1331 // Consume the event.
1334 case R.id.proxy_i2p:
1335 // Update the proxy mode.
1336 proxyMode = ProxyHelper.I2P;
1338 // Apply the proxy mode.
1341 // Consume the event.
1344 case R.id.proxy_custom:
1345 // Update the proxy mode.
1346 proxyMode = ProxyHelper.CUSTOM;
1348 // Apply the proxy mode.
1351 // Consume the event.
1354 case R.id.user_agent_privacy_browser:
1355 // Update the user agent.
1356 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1358 // Reload the current WebView.
1359 currentWebView.reload();
1361 // Consume the event.
1364 case R.id.user_agent_webview_default:
1365 // Update the user agent.
1366 currentWebView.getSettings().setUserAgentString("");
1368 // Reload the current WebView.
1369 currentWebView.reload();
1371 // Consume the event.
1374 case R.id.user_agent_firefox_on_android:
1375 // Update the user agent.
1376 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1378 // Reload the current WebView.
1379 currentWebView.reload();
1381 // Consume the event.
1384 case R.id.user_agent_chrome_on_android:
1385 // Update the user agent.
1386 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1388 // Reload the current WebView.
1389 currentWebView.reload();
1391 // Consume the event.
1394 case R.id.user_agent_safari_on_ios:
1395 // Update the user agent.
1396 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1398 // Reload the current WebView.
1399 currentWebView.reload();
1401 // Consume the event.
1404 case R.id.user_agent_firefox_on_linux:
1405 // Update the user agent.
1406 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1408 // Reload the current WebView.
1409 currentWebView.reload();
1411 // Consume the event.
1414 case R.id.user_agent_chromium_on_linux:
1415 // Update the user agent.
1416 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1418 // Reload the current WebView.
1419 currentWebView.reload();
1421 // Consume the event.
1424 case R.id.user_agent_firefox_on_windows:
1425 // Update the user agent.
1426 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1428 // Reload the current WebView.
1429 currentWebView.reload();
1431 // Consume the event.
1434 case R.id.user_agent_chrome_on_windows:
1435 // Update the user agent.
1436 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1438 // Reload the current WebView.
1439 currentWebView.reload();
1441 // Consume the event.
1444 case R.id.user_agent_edge_on_windows:
1445 // Update the user agent.
1446 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1448 // Reload the current WebView.
1449 currentWebView.reload();
1451 // Consume the event.
1454 case R.id.user_agent_internet_explorer_on_windows:
1455 // Update the user agent.
1456 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1458 // Reload the current WebView.
1459 currentWebView.reload();
1461 // Consume the event.
1464 case R.id.user_agent_safari_on_macos:
1465 // Update the user agent.
1466 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1468 // Reload the current WebView.
1469 currentWebView.reload();
1471 // Consume the event.
1474 case R.id.user_agent_custom:
1475 // Update the user agent.
1476 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1478 // Reload the current WebView.
1479 currentWebView.reload();
1481 // Consume the event.
1484 case R.id.font_size:
1485 // Instantiate the font size dialog.
1486 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1488 // Show the font size dialog.
1489 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1491 // Consume the event.
1494 case R.id.swipe_to_refresh:
1495 // Toggle the stored status of swipe to refresh.
1496 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1498 // Get a handle for the swipe refresh layout.
1499 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1501 // Update the swipe refresh layout.
1502 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1503 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1504 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1505 } else { // Swipe to refresh is disabled.
1506 // Disable the swipe refresh layout.
1507 swipeRefreshLayout.setEnabled(false);
1510 // Consume the event.
1513 case R.id.wide_viewport:
1514 // Toggle the viewport.
1515 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1517 // Consume the event.
1520 case R.id.display_images:
1521 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1522 // Disable loading of images.
1523 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1525 // Reload the website to remove existing images.
1526 currentWebView.reload();
1527 } else { // Images are not currently loaded automatically.
1528 // Enable loading of images. Missing images will be loaded without the need for a reload.
1529 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1532 // Consume the event.
1535 case R.id.night_mode:
1536 // Toggle night mode.
1537 currentWebView.setNightMode(!currentWebView.getNightMode());
1539 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1540 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1541 // Enable JavaScript.
1542 currentWebView.getSettings().setJavaScriptEnabled(true);
1543 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1544 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1545 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1546 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1547 // Apply the JavaScript preference.
1548 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1551 // Update the privacy icons.
1552 updatePrivacyIcons(false);
1554 // Reload the website.
1555 currentWebView.reload();
1557 // Consume the event.
1560 case R.id.find_on_page:
1561 // Get a handle for the views.
1562 Toolbar toolbar = findViewById(R.id.toolbar);
1563 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1564 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1566 // Set the minimum height of the find on page linear layout to match the toolbar.
1567 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1569 // Hide the toolbar.
1570 toolbar.setVisibility(View.GONE);
1572 // Show the find on page linear layout.
1573 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1575 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1576 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1577 findOnPageEditText.postDelayed(() -> {
1578 // Set the focus on `findOnPageEditText`.
1579 findOnPageEditText.requestFocus();
1581 // Get a handle for the input method manager.
1582 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1584 // Remove the lint warning below that the input method manager might be null.
1585 assert inputMethodManager != null;
1587 // Display the keyboard. `0` sets no input flags.
1588 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1591 // Consume the event.
1595 // Get a print manager instance.
1596 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1598 // Remove the lint error below that print manager might be null.
1599 assert printManager != null;
1601 // Create a print document adapter from the current WebView.
1602 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1604 // Print the document.
1605 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1607 // Consume the event.
1611 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1612 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1613 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1615 // Consume the event.
1618 case R.id.save_as_archive:
1619 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1620 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_AS_ARCHIVE, currentWebView.getSettings().getUserAgentString(),
1621 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1623 // Consume the event.
1626 case R.id.save_as_image:
1627 // Prepare the save dialog. The dialog will be displayed once the file size adn the content disposition have been acquired.
1628 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_AS_IMAGE, currentWebView.getSettings().getUserAgentString(),
1629 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1631 // Consume the event.
1634 case R.id.add_to_homescreen:
1635 // Instantiate the create home screen shortcut dialog.
1636 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1637 currentWebView.getFavoriteOrDefaultIcon());
1639 // Show the create home screen shortcut dialog.
1640 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1642 // Consume the event.
1645 case R.id.view_source:
1646 // Create an intent to launch the view source activity.
1647 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1649 // Add the variables to the intent.
1650 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1651 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1654 startActivity(viewSourceIntent);
1656 // Consume the event.
1659 case R.id.share_url:
1660 // Setup the share string.
1661 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1663 // Create the share intent.
1664 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1665 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1666 shareIntent.setType("text/plain");
1669 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1671 // Consume the event.
1674 case R.id.open_with_app:
1675 // Open the URL with an outside app.
1676 openWithApp(currentWebView.getUrl());
1678 // Consume the event.
1681 case R.id.open_with_browser:
1682 // Open the URL with an outside browser.
1683 openWithBrowser(currentWebView.getUrl());
1685 // Consume the event.
1688 case R.id.add_or_edit_domain:
1689 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1690 // Reapply the domain settings on returning to `MainWebViewActivity`.
1691 reapplyDomainSettingsOnRestart = true;
1693 // Create an intent to launch the domains activity.
1694 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1696 // Add the extra information to the intent.
1697 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1698 domainsIntent.putExtra("close_on_back", true);
1699 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1701 // Get the current certificate.
1702 SslCertificate sslCertificate = currentWebView.getCertificate();
1704 // Check to see if the SSL certificate is populated.
1705 if (sslCertificate != null) {
1706 // Extract the certificate to strings.
1707 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1708 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1709 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1710 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1711 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1712 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1713 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1714 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1716 // Add the certificate to the intent.
1717 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1718 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1719 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1720 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1721 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1722 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1723 domainsIntent.putExtra("ssl_start_date", startDateLong);
1724 domainsIntent.putExtra("ssl_end_date", endDateLong);
1727 // Check to see if the current IP addresses have been received.
1728 if (currentWebView.hasCurrentIpAddresses()) {
1729 // Add the current IP addresses to the intent.
1730 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1734 startActivity(domainsIntent);
1735 } else { // Add a new domain.
1736 // Apply the new domain settings on returning to `MainWebViewActivity`.
1737 reapplyDomainSettingsOnRestart = true;
1739 // Get the current domain
1740 Uri currentUri = Uri.parse(currentWebView.getUrl());
1741 String currentDomain = currentUri.getHost();
1743 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1744 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1746 // Create the domain and store the database ID.
1747 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1749 // Create an intent to launch the domains activity.
1750 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1752 // Add the extra information to the intent.
1753 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1754 domainsIntent.putExtra("close_on_back", true);
1755 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1757 // Get the current certificate.
1758 SslCertificate sslCertificate = currentWebView.getCertificate();
1760 // Check to see if the SSL certificate is populated.
1761 if (sslCertificate != null) {
1762 // Extract the certificate to strings.
1763 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1764 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1765 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1766 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1767 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1768 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1769 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1770 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1772 // Add the certificate to the intent.
1773 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1774 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1775 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1776 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1777 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1778 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1779 domainsIntent.putExtra("ssl_start_date", startDateLong);
1780 domainsIntent.putExtra("ssl_end_date", endDateLong);
1783 // Check to see if the current IP addresses have been received.
1784 if (currentWebView.hasCurrentIpAddresses()) {
1785 // Add the current IP addresses to the intent.
1786 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1790 startActivity(domainsIntent);
1793 // Consume the event.
1796 case R.id.ad_consent:
1797 // Instantiate the ad consent dialog.
1798 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1800 // Display the ad consent dialog.
1801 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1803 // Consume the event.
1807 // Don't consume the event.
1808 return super.onOptionsItemSelected(menuItem);
1812 // removeAllCookies is deprecated, but it is required for API < 21.
1814 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1815 // Get the menu item ID.
1816 int menuItemId = menuItem.getItemId();
1818 // Get a handle for the shared preferences.
1819 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1821 // Run the commands that correspond to the selected menu item.
1822 switch (menuItemId) {
1823 case R.id.clear_and_exit:
1824 // Clear and exit Privacy Browser.
1829 // Load the homepage.
1830 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1834 if (currentWebView.canGoBack()) {
1835 // Get the current web back forward list.
1836 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1838 // Get the previous entry URL.
1839 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1841 // Apply the domain settings.
1842 applyDomainSettings(currentWebView, previousUrl, false, false);
1844 // Load the previous website in the history.
1845 currentWebView.goBack();
1850 if (currentWebView.canGoForward()) {
1851 // Get the current web back forward list.
1852 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1854 // Get the next entry URL.
1855 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1857 // Apply the domain settings.
1858 applyDomainSettings(currentWebView, nextUrl, false, false);
1860 // Load the next website in the history.
1861 currentWebView.goForward();
1866 // Instantiate the URL history dialog.
1867 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1869 // Show the URL history dialog.
1870 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1874 // Instantiate the open file dialog.
1875 DialogFragment openDialogFragment = new OpenDialog();
1877 // Show the open file dialog.
1878 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1882 // Populate the resource requests.
1883 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1885 // Create an intent to launch the Requests activity.
1886 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1888 // Add the block third-party requests status to the intent.
1889 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1892 startActivity(requestsIntent);
1895 case R.id.downloads:
1896 // Launch the system Download Manager.
1897 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1899 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1900 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1903 startActivity(downloadManagerIntent);
1907 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1908 reapplyDomainSettingsOnRestart = true;
1910 // Launch the domains activity.
1911 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1913 // Add the extra information to the intent.
1914 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1916 // Get the current certificate.
1917 SslCertificate sslCertificate = currentWebView.getCertificate();
1919 // Check to see if the SSL certificate is populated.
1920 if (sslCertificate != null) {
1921 // Extract the certificate to strings.
1922 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1923 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1924 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1925 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1926 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1927 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1928 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1929 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1931 // Add the certificate to the intent.
1932 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1933 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1934 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1935 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1936 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1937 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1938 domainsIntent.putExtra("ssl_start_date", startDateLong);
1939 domainsIntent.putExtra("ssl_end_date", endDateLong);
1942 // Check to see if the current IP addresses have been received.
1943 if (currentWebView.hasCurrentIpAddresses()) {
1944 // Add the current IP addresses to the intent.
1945 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1949 startActivity(domainsIntent);
1953 // Set the flag to reapply app settings on restart when returning from Settings.
1954 reapplyAppSettingsOnRestart = true;
1956 // Set the flag to reapply the domain settings on restart when returning from Settings.
1957 reapplyDomainSettingsOnRestart = true;
1959 // Launch the settings activity.
1960 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1961 startActivity(settingsIntent);
1964 case R.id.import_export:
1965 // Launch the import/export activity.
1966 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1967 startActivity(importExportIntent);
1971 // Launch the logcat activity.
1972 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1973 startActivity(logcatIntent);
1977 // Launch `GuideActivity`.
1978 Intent guideIntent = new Intent(this, GuideActivity.class);
1979 startActivity(guideIntent);
1983 // Create an intent to launch the about activity.
1984 Intent aboutIntent = new Intent(this, AboutActivity.class);
1986 // Create a string array for the blocklist versions.
1987 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],
1988 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
1990 // Add the blocklist versions to the intent.
1991 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
1994 startActivity(aboutIntent);
1998 // Get a handle for the drawer layout.
1999 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2001 // Close the navigation drawer.
2002 drawerLayout.closeDrawer(GravityCompat.START);
2007 public void onPostCreate(Bundle savedInstanceState) {
2008 // Run the default commands.
2009 super.onPostCreate(savedInstanceState);
2011 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2012 actionBarDrawerToggle.syncState();
2016 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2017 // Run the default commands.
2018 super.onConfigurationChanged(newConfig);
2020 // Get the status bar pixel size.
2021 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2022 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2024 // Get the resource density.
2025 float screenDensity = getResources().getDisplayMetrics().density;
2027 // Recalculate the drawer header padding.
2028 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2029 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2030 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2032 // Reload the ad for the free flavor if not in full screen mode.
2033 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2034 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2035 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2038 // `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:
2039 // https://code.google.com/p/android/issues/detail?id=20493#c8
2040 // ActivityCompat.invalidateOptionsMenu(this);
2044 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2045 // Store the hit test result.
2046 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2048 // Define the URL strings.
2049 final String imageUrl;
2050 final String linkUrl;
2052 // Get handles for the system managers.
2053 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2055 // Remove the lint errors below that the clipboard manager might be null.
2056 assert clipboardManager != null;
2058 // Process the link according to the type.
2059 switch (hitTestResult.getType()) {
2060 // `SRC_ANCHOR_TYPE` is a link.
2061 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2062 // Get the target URL.
2063 linkUrl = hitTestResult.getExtra();
2065 // Set the target URL as the title of the `ContextMenu`.
2066 menu.setHeaderTitle(linkUrl);
2068 // Add an Open in New Tab entry.
2069 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2070 // Load the link URL in a new tab and move to it.
2071 addNewTab(linkUrl, true);
2073 // Consume the event.
2077 // Add an Open in Background entry.
2078 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2079 // Load the link URL in a new tab but do not move to it.
2080 addNewTab(linkUrl, false);
2082 // Consume the event.
2086 // Add an Open with App entry.
2087 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2088 openWithApp(linkUrl);
2090 // Consume the event.
2094 // Add an Open with Browser entry.
2095 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2096 openWithBrowser(linkUrl);
2098 // Consume the event.
2102 // Add a Copy URL entry.
2103 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2104 // Save the link URL in a `ClipData`.
2105 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2107 // Set the `ClipData` as the clipboard's primary clip.
2108 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2110 // Consume the event.
2114 // Add a Save URL entry.
2115 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2116 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2117 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2118 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2120 // Consume the event.
2124 // Add an empty Cancel entry, which by default closes the context menu.
2125 menu.add(R.string.cancel);
2128 // `IMAGE_TYPE` is an image.
2129 case WebView.HitTestResult.IMAGE_TYPE:
2130 // Get the image URL.
2131 imageUrl = hitTestResult.getExtra();
2133 // Set the image URL as the title of the context menu.
2134 menu.setHeaderTitle(imageUrl);
2136 // Add an Open in New Tab entry.
2137 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2138 // Load the image in a new tab.
2139 addNewTab(imageUrl, true);
2141 // Consume the event.
2145 // Add an Open with App entry.
2146 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2147 // Open the image URL with an external app.
2148 openWithApp(imageUrl);
2150 // Consume the event.
2154 // Add an Open with Browser entry.
2155 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2156 // Open the image URL with an external browser.
2157 openWithBrowser(imageUrl);
2159 // Consume the event.
2163 // Add a View Image entry.
2164 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2165 // Load the image in the current tab.
2166 loadUrl(currentWebView, imageUrl);
2168 // Consume the event.
2172 // Add a Save Image entry.
2173 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2174 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2175 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2176 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2178 // Consume the event.
2182 // Add a Copy URL entry.
2183 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2184 // Save the image URL in a clip data.
2185 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2187 // Set the clip data as the clipboard's primary clip.
2188 clipboardManager.setPrimaryClip(imageTypeClipData);
2190 // Consume the event.
2194 // Add an empty Cancel entry, which by default closes the context menu.
2195 menu.add(R.string.cancel);
2198 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2199 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2200 // Get the image URL.
2201 imageUrl = hitTestResult.getExtra();
2203 // Instantiate a handler.
2204 Handler handler = new Handler();
2206 // Get a message from the handler.
2207 Message message = handler.obtainMessage();
2209 // Request the image details from the last touched node be returned in the message.
2210 currentWebView.requestFocusNodeHref(message);
2212 // Get the link URL from the message data.
2213 linkUrl = message.getData().getString("url");
2215 // Set the link URL as the title of the context menu.
2216 menu.setHeaderTitle(linkUrl);
2218 // Add an Open in New Tab entry.
2219 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2220 // Load the link URL in a new tab and move to it.
2221 addNewTab(linkUrl, true);
2223 // Consume the event.
2227 // Add an Open in Background entry.
2228 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2229 // Lod the link URL in a new tab but do not move to it.
2230 addNewTab(linkUrl, false);
2232 // Consume the event.
2236 // Add an Open Image in New Tab entry.
2237 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2238 // Load the image in a new tab and move to it.
2239 addNewTab(imageUrl, true);
2241 // Consume the event.
2245 // Add an Open with App entry.
2246 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2247 // Open the link URL with an external app.
2248 openWithApp(linkUrl);
2250 // Consume the event.
2254 // Add an Open with Browser entry.
2255 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2256 // Open the link URL with an external browser.
2257 openWithBrowser(linkUrl);
2259 // Consume the event.
2263 // Add a View Image entry.
2264 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2265 // View the image in the current tab.
2266 loadUrl(currentWebView, imageUrl);
2268 // Consume the event.
2272 // Add a Save Image entry.
2273 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2274 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2275 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2276 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2278 // Consume the event.
2282 // Add a Copy URL entry.
2283 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2284 // Save the link URL in a clip data.
2285 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2287 // Set the clip data as the clipboard's primary clip.
2288 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2290 // Consume the event.
2294 // Add a Save URL entry.
2295 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2296 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2297 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2298 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2300 // Consume the event.
2304 // Add an empty Cancel entry, which by default closes the context menu.
2305 menu.add(R.string.cancel);
2308 case WebView.HitTestResult.EMAIL_TYPE:
2309 // Get the target URL.
2310 linkUrl = hitTestResult.getExtra();
2312 // Set the target URL as the title of the `ContextMenu`.
2313 menu.setHeaderTitle(linkUrl);
2315 // Add a Write Email entry.
2316 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2317 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2318 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2320 // Parse the url and set it as the data for the `Intent`.
2321 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2323 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2324 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2327 startActivity(emailIntent);
2329 // Consume the event.
2333 // Add a Copy Email Address entry.
2334 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2335 // Save the email address in a `ClipData`.
2336 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2338 // Set the `ClipData` as the clipboard's primary clip.
2339 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2341 // Consume the event.
2345 // Add an empty Cancel entry, which by default closes the context menu.
2346 menu.add(R.string.cancel);
2352 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2353 // Get a handle for the bookmarks list view.
2354 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2357 Dialog dialog = dialogFragment.getDialog();
2359 // Remove the incorrect lint warning below that the dialog might be null.
2360 assert dialog != null;
2362 // Get the views from the dialog fragment.
2363 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2364 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2366 // Extract the strings from the edit texts.
2367 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2368 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2370 // Create a favorite icon byte array output stream.
2371 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2373 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2374 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2376 // Convert the favorite icon byte array stream to a byte array.
2377 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2379 // Display the new bookmark below the current items in the (0 indexed) list.
2380 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2382 // Create the bookmark.
2383 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2385 // Update the bookmarks cursor with the current contents of this folder.
2386 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2388 // Update the list view.
2389 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2391 // Scroll to the new bookmark.
2392 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2396 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2397 // Get a handle for the bookmarks list view.
2398 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2401 Dialog dialog = dialogFragment.getDialog();
2403 // Remove the incorrect lint warning below that the dialog might be null.
2404 assert dialog != null;
2406 // Get handles for the views in the dialog fragment.
2407 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2408 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2409 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2411 // Get new folder name string.
2412 String folderNameString = createFolderNameEditText.getText().toString();
2414 // Create a folder icon bitmap.
2415 Bitmap folderIconBitmap;
2417 // Set the folder icon bitmap according to the dialog.
2418 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2419 // Get the default folder icon drawable.
2420 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2422 // Convert the folder icon drawable to a bitmap drawable.
2423 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2425 // Convert the folder icon bitmap drawable to a bitmap.
2426 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2427 } else { // Use the WebView favorite icon.
2428 // Copy the favorite icon bitmap to the folder icon bitmap.
2429 folderIconBitmap = favoriteIconBitmap;
2432 // Create a folder icon byte array output stream.
2433 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2435 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2436 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2438 // Convert the folder icon byte array stream to a byte array.
2439 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2441 // Move all the bookmarks down one in the display order.
2442 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2443 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2444 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2447 // Create the folder, which will be placed at the top of the `ListView`.
2448 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2450 // Update the bookmarks cursor with the current contents of this folder.
2451 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2453 // Update the `ListView`.
2454 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2456 // Scroll to the new folder.
2457 bookmarksListView.setSelection(0);
2461 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2463 Dialog dialog = dialogFragment.getDialog();
2465 // Remove the incorrect lint warning below that the dialog might be null.
2466 assert dialog != null;
2468 // Get handles for the views from the dialog.
2469 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
2470 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
2471 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2473 // Store the bookmark strings.
2474 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2475 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2477 // Update the bookmark.
2478 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2479 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2480 } else { // Update the bookmark using the `WebView` favorite icon.
2481 // Create a favorite icon byte array output stream.
2482 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2484 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2485 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2487 // Convert the favorite icon byte array stream to a byte array.
2488 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2490 // Update the bookmark and the favorite icon.
2491 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2494 // Update the bookmarks cursor with the current contents of this folder.
2495 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2497 // Update the list view.
2498 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2502 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2504 Dialog dialog = dialogFragment.getDialog();
2506 // Remove the incorrect lint warning below that the dialog might be null.
2507 assert dialog != null;
2509 // Get handles for the views from `dialogFragment`.
2510 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2511 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2512 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2513 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2515 // Get the new folder name.
2516 String newFolderNameString = editFolderNameEditText.getText().toString();
2518 // Check if the favorite icon has changed.
2519 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2520 // Update the name in the database.
2521 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2522 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2523 // Create the new folder icon Bitmap.
2524 Bitmap folderIconBitmap;
2526 // Populate the new folder icon bitmap.
2527 if (defaultFolderIconRadioButton.isChecked()) {
2528 // Get the default folder icon drawable.
2529 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2531 // Convert the folder icon drawable to a bitmap drawable.
2532 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2534 // Convert the folder icon bitmap drawable to a bitmap.
2535 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2536 } else { // Use the `WebView` favorite icon.
2537 // Copy the favorite icon bitmap to the folder icon bitmap.
2538 folderIconBitmap = favoriteIconBitmap;
2541 // Create a folder icon byte array output stream.
2542 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2544 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2545 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2547 // Convert the folder icon byte array stream to a byte array.
2548 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2550 // Update the folder icon in the database.
2551 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2552 } else { // The folder icon and the name have changed.
2553 // Get the new folder icon `Bitmap`.
2554 Bitmap folderIconBitmap;
2555 if (defaultFolderIconRadioButton.isChecked()) {
2556 // Get the default folder icon drawable.
2557 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2559 // Convert the folder icon drawable to a bitmap drawable.
2560 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2562 // Convert the folder icon bitmap drawable to a bitmap.
2563 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2564 } else { // Use the `WebView` favorite icon.
2565 // Copy the favorite icon bitmap to the folder icon bitmap.
2566 folderIconBitmap = favoriteIconBitmap;
2569 // Create a folder icon byte array output stream.
2570 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2572 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2573 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2575 // Convert the folder icon byte array stream to a byte array.
2576 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2578 // Update the folder name and icon in the database.
2579 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2582 // Update the bookmarks cursor with the current contents of this folder.
2583 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2585 // Update the `ListView`.
2586 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2589 // Override `onBackPressed` to handle the navigation drawer and and the WebViews.
2591 public void onBackPressed() {
2592 // Get a handle for the drawer layout and the tab layout.
2593 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2594 TabLayout tabLayout = findViewById(R.id.tablayout);
2596 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2597 // Close the navigation drawer.
2598 drawerLayout.closeDrawer(GravityCompat.START);
2599 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2600 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2601 // close the bookmarks drawer.
2602 drawerLayout.closeDrawer(GravityCompat.END);
2603 } else { // A subfolder is displayed.
2604 // Place the former parent folder in `currentFolder`.
2605 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2607 // Load the new folder.
2608 loadBookmarksFolder();
2610 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2611 // Get a handle for the layouts.
2612 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2613 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2614 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2616 // Re-enable the screen timeout.
2617 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2619 // Unset the full screen video flag.
2620 displayingFullScreenVideo = false;
2622 // Remove all the views from the full screen video frame layout.
2623 fullScreenVideoFrameLayout.removeAllViews();
2625 // Hide the full screen video frame layout.
2626 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2628 // Enable the sliding drawers.
2629 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2631 // Show the main content relative layout.
2632 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2634 // Apply the appropriate full screen mode flags.
2635 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2636 // Hide the app bar if specified.
2638 // Get handles for the views.
2639 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
2640 ActionBar actionBar = getSupportActionBar();
2642 // Remove the incorrect lint warning below that the action bar might be null.
2643 assert actionBar != null;
2645 // Hide the tab linear layout.
2646 tabsLinearLayout.setVisibility(View.GONE);
2648 // Hide the action bar.
2652 // Hide the banner ad in the free flavor.
2653 if (BuildConfig.FLAVOR.contentEquals("free")) {
2654 AdHelper.hideAd(findViewById(R.id.adview));
2657 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
2658 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2660 /* Hide the system bars.