2 * Copyright © 2015-2019 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.Environment;
52 import android.os.Handler;
53 import android.os.Message;
54 import android.preference.PreferenceManager;
55 import android.print.PrintDocumentAdapter;
56 import android.print.PrintManager;
57 import android.text.Editable;
58 import android.text.Spanned;
59 import android.text.TextWatcher;
60 import android.text.style.ForegroundColorSpan;
61 import android.util.Patterns;
62 import android.view.ContextMenu;
63 import android.view.GestureDetector;
64 import android.view.KeyEvent;
65 import android.view.Menu;
66 import android.view.MenuItem;
67 import android.view.MotionEvent;
68 import android.view.View;
69 import android.view.ViewGroup;
70 import android.view.WindowManager;
71 import android.view.inputmethod.InputMethodManager;
72 import android.webkit.CookieManager;
73 import android.webkit.HttpAuthHandler;
74 import android.webkit.SslErrorHandler;
75 import android.webkit.ValueCallback;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebSettings;
80 import android.webkit.WebStorage;
81 import android.webkit.WebView;
82 import android.webkit.WebViewClient;
83 import android.webkit.WebViewDatabase;
84 import android.widget.ArrayAdapter;
85 import android.widget.CursorAdapter;
86 import android.widget.EditText;
87 import android.widget.FrameLayout;
88 import android.widget.ImageView;
89 import android.widget.LinearLayout;
90 import android.widget.ListView;
91 import android.widget.ProgressBar;
92 import android.widget.RadioButton;
93 import android.widget.RelativeLayout;
94 import android.widget.TextView;
96 import androidx.annotation.NonNull;
97 import androidx.appcompat.app.ActionBar;
98 import androidx.appcompat.app.ActionBarDrawerToggle;
99 import androidx.appcompat.app.AppCompatActivity;
100 import androidx.appcompat.widget.Toolbar;
101 import androidx.coordinatorlayout.widget.CoordinatorLayout;
102 import androidx.core.app.ActivityCompat;
103 import androidx.core.content.ContextCompat;
104 import androidx.core.view.GravityCompat;
105 import androidx.drawerlayout.widget.DrawerLayout;
106 import androidx.fragment.app.DialogFragment;
107 import androidx.fragment.app.FragmentManager;
108 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
109 import androidx.viewpager.widget.ViewPager;
111 import com.google.android.material.appbar.AppBarLayout;
112 import com.google.android.material.floatingactionbutton.FloatingActionButton;
113 import com.google.android.material.navigation.NavigationView;
114 import com.google.android.material.snackbar.Snackbar;
115 import com.google.android.material.tabs.TabLayout;
117 import com.stoutner.privacybrowser.BuildConfig;
118 import com.stoutner.privacybrowser.R;
119 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
120 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
121 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
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.DownloadFileDialog;
128 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
129 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
130 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
131 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
132 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
133 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
134 import com.stoutner.privacybrowser.dialogs.SaveWebpageImageDialog;
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.fragments.WebViewTabFragment;
140 import com.stoutner.privacybrowser.helpers.AdHelper;
141 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
142 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
143 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
144 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
145 import com.stoutner.privacybrowser.helpers.FileNameHelper;
146 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
147 import com.stoutner.privacybrowser.views.NestedScrollWebView;
149 import java.io.ByteArrayInputStream;
150 import java.io.ByteArrayOutputStream;
152 import java.io.IOException;
153 import java.io.UnsupportedEncodingException;
154 import java.net.MalformedURLException;
156 import java.net.URLDecoder;
157 import java.net.URLEncoder;
158 import java.util.ArrayList;
159 import java.util.Date;
160 import java.util.HashMap;
161 import java.util.HashSet;
162 import java.util.List;
163 import java.util.Map;
164 import java.util.Set;
166 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
167 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
168 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
169 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageImageDialog.SaveWebpageImageListener,
170 StoragePermissionDialog.StoragePermissionDialogListener, UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
172 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
173 public static String orbotStatus;
175 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
176 public static WebViewPagerAdapter webViewPagerAdapter;
178 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
179 public static boolean loadUrlOnRestart;
180 public static String urlToLoadOnRestart;
182 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
183 public static boolean restartFromBookmarksActivity;
185 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
186 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
187 public static String currentBookmarksFolder;
189 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
190 public final static int UNRECOGNIZED_USER_AGENT = -1;
191 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
192 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
193 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
194 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
195 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
197 // Start activity for result request codes.
198 private final int FILE_UPLOAD_REQUEST_CODE = 0;
199 public final static int BROWSE_SAVE_WEBPAGE_IMAGE_REQUEST_CODE = 1;
202 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
203 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
204 private NestedScrollWebView currentWebView;
206 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
207 private final Map<String, String> customHeaders = new HashMap<>();
209 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
210 private String searchURL;
212 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
213 private Menu optionsMenu;
215 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
216 private ArrayList<List<String[]>> easyList;
217 private ArrayList<List<String[]>> easyPrivacy;
218 private ArrayList<List<String[]>> fanboysAnnoyanceList;
219 private ArrayList<List<String[]>> fanboysSocialList;
220 private ArrayList<List<String[]>> ultraList;
221 private ArrayList<List<String[]>> ultraPrivacy;
223 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
224 private String webViewDefaultUserAgent;
226 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
227 private boolean proxyThroughOrbot;
229 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
230 private boolean incognitoModeEnabled;
232 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
233 private boolean fullScreenBrowsingModeEnabled;
235 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
236 private boolean inFullScreenBrowsingMode;
238 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
239 private boolean hideAppBar;
240 private boolean scrollAppBar;
242 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
243 private boolean loadingNewIntent;
245 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
246 private boolean reapplyDomainSettingsOnRestart;
248 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
249 private boolean reapplyAppSettingsOnRestart;
251 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
252 private boolean displayingFullScreenVideo;
254 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
255 private BroadcastReceiver orbotStatusBroadcastReceiver;
257 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
258 private boolean waitingForOrbot;
260 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
261 private ActionBarDrawerToggle actionBarDrawerToggle;
263 // The color spans are used in `onCreate()` and `highlightUrlText()`.
264 private ForegroundColorSpan redColorSpan;
265 private ForegroundColorSpan initialGrayColorSpan;
266 private ForegroundColorSpan finalGrayColorSpan;
268 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
269 private int drawerHeaderPaddingLeftAndRight;
270 private int drawerHeaderPaddingTop;
271 private int drawerHeaderPaddingBottom;
273 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
274 // and `loadBookmarksFolder()`.
275 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
277 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
278 private Cursor bookmarksCursor;
280 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
281 private CursorAdapter bookmarksCursorAdapter;
283 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
284 private String oldFolderNameString;
286 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
287 private ValueCallback<Uri[]> fileChooserCallback;
289 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
290 private int defaultProgressViewStartOffset;
291 private int defaultProgressViewEndOffset;
293 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
294 private int swipeRefreshLayoutPaddingTop;
296 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
297 private boolean sanitizeGoogleAnalytics;
298 private boolean sanitizeFacebookClickIds;
299 private boolean sanitizeTwitterAmpRedirects;
301 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
302 private String downloadUrl;
303 private String downloadContentDisposition;
304 private long downloadContentLength;
306 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
307 private String downloadImageUrl;
309 // The save website image file path string is used in `onSaveWebpageImage()` and `onRequestPermissionResult()`
310 private String saveWebsiteImageFilePath;
312 // The permission result request codes are used in `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, `onSaveWebpageImage()`,
313 // `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
314 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
315 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
316 private final int SAVE_WEBPAGE_IMAGE_REQUEST_CODE = 3;
319 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
320 @SuppressLint("ClickableViewAccessibility")
321 protected void onCreate(Bundle savedInstanceState) {
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.
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 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
469 if (proxyThroughOrbot) {
470 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
471 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
473 // Send the intent to the Orbot package.
474 orbotIntent.setPackage("org.torproject.android");
477 sendBroadcast(orbotIntent);
480 // Apply the app settings if returning from the Settings activity.
481 if (reapplyAppSettingsOnRestart) {
482 // Reset the reapply app settings on restart tracker.
483 reapplyAppSettingsOnRestart = false;
485 // Apply the app settings.
489 // Apply the domain settings if returning from the settings or domains activity.
490 if (reapplyDomainSettingsOnRestart) {
491 // Reset the reapply domain settings on restart tracker.
492 reapplyDomainSettingsOnRestart = false;
494 // Reapply the domain settings for each tab.
495 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
496 // Get the WebView tab fragment.
497 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
499 // Get the fragment view.
500 View fragmentView = webViewTabFragment.getView();
502 // Only reload the WebViews if they exist.
503 if (fragmentView != null) {
504 // Get the nested scroll WebView from the tab fragment.
505 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
507 // Reset the current domain name so the domain settings will be reapplied.
508 nestedScrollWebView.resetCurrentDomainName();
510 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
511 if (nestedScrollWebView.getUrl() != null) {
512 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
518 // Load the URL on restart (used when loading a bookmark).
519 if (loadUrlOnRestart) {
520 // Load the specified URL.
521 loadUrl(urlToLoadOnRestart);
523 // Reset the load on restart tracker.
524 loadUrlOnRestart = false;
527 // Update the bookmarks drawer if returning from the Bookmarks activity.
528 if (restartFromBookmarksActivity) {
529 // Get a handle for the drawer layout.
530 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
532 // Close the bookmarks drawer.
533 drawerLayout.closeDrawer(GravityCompat.END);
535 // Reload the bookmarks drawer.
536 loadBookmarksFolder();
538 // Reset `restartFromBookmarksActivity`.
539 restartFromBookmarksActivity = false;
542 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
543 updatePrivacyIcons(true);
546 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
548 public void onResume() {
549 // Run the default commands.
552 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
553 // Get the WebView tab fragment.
554 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
556 // Get the fragment view.
557 View fragmentView = webViewTabFragment.getView();
559 // Only resume the WebViews if they exist (they won't when the app is first created).
560 if (fragmentView != null) {
561 // Get the nested scroll WebView from the tab fragment.
562 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
564 // Resume the nested scroll WebView JavaScript timers.
565 nestedScrollWebView.resumeTimers();
567 // Resume the nested scroll WebView.
568 nestedScrollWebView.onResume();
572 // Display a message to the user if waiting for Orbot.
573 if (waitingForOrbot && !orbotStatus.equals("ON")) {
574 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
575 currentWebView.getSettings().setUseWideViewPort(false);
577 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
578 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
581 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
582 // Get a handle for the root frame layouts.
583 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
585 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
586 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
588 /* Hide the system bars.
589 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
590 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
591 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
592 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
594 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
595 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
596 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
598 AdHelper.resumeAd(findViewById(R.id.adview));
603 public void onPause() {
604 // Run the default commands.
607 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
608 // Get the WebView tab fragment.
609 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
611 // Get the fragment view.
612 View fragmentView = webViewTabFragment.getView();
614 // Only pause the WebViews if they exist (they won't when the app is first created).
615 if (fragmentView != null) {
616 // Get the nested scroll WebView from the tab fragment.
617 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
619 // Pause the nested scroll WebView.
620 nestedScrollWebView.onPause();
622 // Pause the nested scroll WebView JavaScript timers.
623 nestedScrollWebView.pauseTimers();
627 // Pause the ad or it will continue to consume resources in the background on the free flavor.
628 if (BuildConfig.FLAVOR.contentEquals("free")) {
630 AdHelper.pauseAd(findViewById(R.id.adview));
635 public void onDestroy() {
636 // Unregister the Orbot status broadcast receiver.
637 this.unregisterReceiver(orbotStatusBroadcastReceiver);
639 // Close the bookmarks cursor and database.
640 bookmarksCursor.close();
641 bookmarksDatabaseHelper.close();
643 // Run the default commands.
648 public boolean onCreateOptionsMenu(Menu menu) {
649 // Inflate the menu. This adds items to the action bar if it is present.
650 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
652 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
655 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
656 updatePrivacyIcons(false);
658 // Get handles for the menu items.
659 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
660 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
661 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
662 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
663 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
664 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
665 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
667 // Only display third-party cookies if API >= 21
668 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
670 // Only display the form data menu items if the API < 26.
671 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
672 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
674 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
675 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
677 // Only show Ad Consent if this is the free flavor.
678 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
680 // Get the shared preferences.
681 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
683 // Get the dark theme and app bar preferences..
684 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
685 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
687 // 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.
688 if (displayAdditionalAppBarIcons) {
689 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
690 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
691 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
692 } else { //Do not display the additional icons.
693 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
694 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
695 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
698 // Replace Refresh with Stop if a URL is already loading.
699 if (currentWebView != null && currentWebView.getProgress() != 100) {
701 refreshMenuItem.setTitle(R.string.stop);
703 // If the icon is displayed in the AppBar, set it according to the theme.
704 if (displayAdditionalAppBarIcons) {
706 refreshMenuItem.setIcon(R.drawable.close_dark);
708 refreshMenuItem.setIcon(R.drawable.close_light);
718 public boolean onPrepareOptionsMenu(Menu menu) {
719 // Get handles for the menu items.
720 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
721 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
722 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
723 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
724 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
725 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
726 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
727 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
728 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
729 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
730 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
731 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
732 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
733 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
734 MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
735 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
736 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
737 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
738 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
739 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
740 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
741 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
742 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
744 // Get a handle for the cookie manager.
745 CookieManager cookieManager = CookieManager.getInstance();
747 // Initialize the current user agent string and the font size.
748 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
751 // 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.
752 if (currentWebView != null) {
753 // Set the add or edit domain text.
754 if (currentWebView.getDomainSettingsApplied()) {
755 addOrEditDomain.setTitle(R.string.edit_domain_settings);
757 addOrEditDomain.setTitle(R.string.add_domain_settings);
760 // Get the current user agent from the WebView.
761 currentUserAgent = currentWebView.getSettings().getUserAgentString();
763 // Get the current font size from the
764 fontSize = currentWebView.getSettings().getTextZoom();
766 // Set the status of the menu item checkboxes.
767 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
768 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
769 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
770 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
771 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
772 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
773 ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
774 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
775 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
776 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
777 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
778 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
779 nightModeMenuItem.setChecked(currentWebView.getNightMode());
781 // Initialize the display names for the blocklists with the number of blocked requests.
782 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
783 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
784 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
785 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
786 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
787 ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
788 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
789 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
791 // Only modify third-party cookies if the API >= 21.
792 if (Build.VERSION.SDK_INT >= 21) {
793 // Set the status of the third-party cookies checkbox.
794 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
796 // Enable third-party cookies if first-party cookies are enabled.
797 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
800 // Enable DOM Storage if JavaScript is enabled.
801 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
804 // Set the status of the menu item checkboxes.
805 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
806 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
808 // Enable Clear Cookies if there are any.
809 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
811 // 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`.
812 String privateDataDirectoryString = getApplicationInfo().dataDir;
814 // Get a count of the number of files in the Local Storage directory.
815 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
816 int localStorageDirectoryNumberOfFiles = 0;
817 if (localStorageDirectory.exists()) {
818 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
821 // Get a count of the number of files in the IndexedDB directory.
822 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
823 int indexedDBDirectoryNumberOfFiles = 0;
824 if (indexedDBDirectory.exists()) {
825 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
828 // Enable Clear DOM Storage if there is any.
829 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
831 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
832 if (Build.VERSION.SDK_INT < 26) {
833 // Get the WebView database.
834 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
836 // Enable the clear form data menu item if there is anything to clear.
837 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
840 // Enable Clear Data if any of the submenu items are enabled.
841 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
843 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
844 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
846 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
847 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
848 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
849 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
850 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
851 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
852 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
853 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
854 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
855 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
856 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
857 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
858 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
859 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
860 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
861 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
862 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
863 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
864 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
865 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
866 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
867 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
868 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
869 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
870 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
871 } else { // Custom user agent.
872 menu.findItem(R.id.user_agent_custom).setChecked(true);
875 // Instantiate the font size title and the selected font size menu item.
876 String fontSizeTitle;
877 MenuItem selectedFontSizeMenuItem;
879 // Prepare the font size title and current size menu item.
880 //noinspection DuplicateBranchesInSwitch
883 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
884 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
888 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
889 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
893 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
894 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
898 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
899 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
903 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
904 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
908 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
909 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
913 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
914 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
918 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
919 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
923 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
924 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
928 // Set the font size title and select the current size menu item.
929 fontSizeMenuItem.setTitle(fontSizeTitle);
930 selectedFontSizeMenuItem.setChecked(true);
932 // Run all the other default commands.
933 super.onPrepareOptionsMenu(menu);
940 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
941 @SuppressLint("SetJavaScriptEnabled")
942 public boolean onOptionsItemSelected(MenuItem menuItem) {
943 // Get the selected menu item ID.
944 int menuItemId = menuItem.getItemId();
946 // Get a handle for the shared preferences.
947 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
949 // Get a handle for the cookie manager.
950 CookieManager cookieManager = CookieManager.getInstance();
952 // Run the commands that correlate to the selected menu item.
953 switch (menuItemId) {
954 case R.id.toggle_javascript:
955 // Toggle the JavaScript status.
956 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
958 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
959 updatePrivacyIcons(true);
961 // Display a `Snackbar`.
962 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
963 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
964 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
965 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
966 } else { // Privacy mode.
967 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
970 // Reload the current WebView.
971 currentWebView.reload();
973 // Consume the event.
976 case R.id.add_or_edit_domain:
977 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
978 // Reapply the domain settings on returning to `MainWebViewActivity`.
979 reapplyDomainSettingsOnRestart = true;
981 // Create an intent to launch the domains activity.
982 Intent domainsIntent = new Intent(this, DomainsActivity.class);
984 // Add the extra information to the intent.
985 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
986 domainsIntent.putExtra("close_on_back", true);
987 domainsIntent.putExtra("current_url", currentWebView.getUrl());
989 // Get the current certificate.
990 SslCertificate sslCertificate = currentWebView.getCertificate();
992 // Check to see if the SSL certificate is populated.
993 if (sslCertificate != null) {
994 // Extract the certificate to strings.
995 String issuedToCName = sslCertificate.getIssuedTo().getCName();
996 String issuedToOName = sslCertificate.getIssuedTo().getOName();
997 String issuedToUName = sslCertificate.getIssuedTo().getUName();
998 String issuedByCName = sslCertificate.getIssuedBy().getCName();
999 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1000 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1001 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1002 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1004 // Add the certificate to the intent.
1005 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1006 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1007 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1008 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1009 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1010 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1011 domainsIntent.putExtra("ssl_start_date", startDateLong);
1012 domainsIntent.putExtra("ssl_end_date", endDateLong);
1015 // Check to see if the current IP addresses have been received.
1016 if (currentWebView.hasCurrentIpAddresses()) {
1017 // Add the current IP addresses to the intent.
1018 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1022 startActivity(domainsIntent);
1023 } else { // Add a new domain.
1024 // Apply the new domain settings on returning to `MainWebViewActivity`.
1025 reapplyDomainSettingsOnRestart = true;
1027 // Get the current domain
1028 Uri currentUri = Uri.parse(currentWebView.getUrl());
1029 String currentDomain = currentUri.getHost();
1031 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1032 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1034 // Create the domain and store the database ID.
1035 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1037 // Create an intent to launch the domains activity.
1038 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1040 // Add the extra information to the intent.
1041 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1042 domainsIntent.putExtra("close_on_back", true);
1043 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1045 // Get the current certificate.
1046 SslCertificate sslCertificate = currentWebView.getCertificate();
1048 // Check to see if the SSL certificate is populated.
1049 if (sslCertificate != null) {
1050 // Extract the certificate to strings.
1051 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1052 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1053 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1054 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1055 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1056 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1057 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1058 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1060 // Add the certificate to the intent.
1061 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1062 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1063 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1064 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1065 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1066 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1067 domainsIntent.putExtra("ssl_start_date", startDateLong);
1068 domainsIntent.putExtra("ssl_end_date", endDateLong);
1071 // Check to see if the current IP addresses have been received.
1072 if (currentWebView.hasCurrentIpAddresses()) {
1073 // Add the current IP addresses to the intent.
1074 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1078 startActivity(domainsIntent);
1081 // Consume the event.
1084 case R.id.toggle_first_party_cookies:
1085 // Switch the first-party cookie status.
1086 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1088 // Store the first-party cookie status.
1089 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1091 // Update the menu checkbox.
1092 menuItem.setChecked(cookieManager.acceptCookie());
1094 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1095 updatePrivacyIcons(true);
1097 // Display a snackbar.
1098 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1099 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1100 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1101 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1102 } else { // Privacy mode.
1103 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1106 // Reload the current WebView.
1107 currentWebView.reload();
1109 // Consume the event.
1112 case R.id.toggle_third_party_cookies:
1113 if (Build.VERSION.SDK_INT >= 21) {
1114 // Switch the status of thirdPartyCookiesEnabled.
1115 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1117 // Update the menu checkbox.
1118 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1120 // Display a snackbar.
1121 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1122 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1124 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1127 // Reload the current WebView.
1128 currentWebView.reload();
1129 } // Else do nothing because SDK < 21.
1131 // Consume the event.
1134 case R.id.toggle_dom_storage:
1135 // Toggle the status of domStorageEnabled.
1136 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1138 // Update the menu checkbox.
1139 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1141 // Update the privacy icon. `true` refreshes the app bar icons.
1142 updatePrivacyIcons(true);
1144 // Display a snackbar.
1145 if (currentWebView.getSettings().getDomStorageEnabled()) {
1146 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1148 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1151 // Reload the current WebView.
1152 currentWebView.reload();
1154 // Consume the event.
1157 // Form data can be removed once the minimum API >= 26.
1158 case R.id.toggle_save_form_data:
1159 // Switch the status of saveFormDataEnabled.
1160 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1162 // Update the menu checkbox.
1163 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1165 // Display a snackbar.
1166 if (currentWebView.getSettings().getSaveFormData()) {
1167 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1169 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1172 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1173 updatePrivacyIcons(true);
1175 // Reload the current WebView.
1176 currentWebView.reload();
1178 // Consume the event.
1181 case R.id.clear_cookies:
1182 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1183 .setAction(R.string.undo, v -> {
1184 // Do nothing because everything will be handled by `onDismissed()` below.
1186 .addCallback(new Snackbar.Callback() {
1187 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1189 public void onDismissed(Snackbar snackbar, int event) {
1190 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1191 // Delete the cookies, which command varies by SDK.
1192 if (Build.VERSION.SDK_INT < 21) {
1193 cookieManager.removeAllCookie();
1195 cookieManager.removeAllCookies(null);
1202 // Consume the event.
1205 case R.id.clear_dom_storage:
1206 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1207 .setAction(R.string.undo, v -> {
1208 // Do nothing because everything will be handled by `onDismissed()` below.
1210 .addCallback(new Snackbar.Callback() {
1211 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1213 public void onDismissed(Snackbar snackbar, int event) {
1214 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1215 // Delete the DOM Storage.
1216 WebStorage webStorage = WebStorage.getInstance();
1217 webStorage.deleteAllData();
1219 // Initialize a handler to manually delete the DOM storage files and directories.
1220 Handler deleteDomStorageHandler = new Handler();
1222 // Setup a runnable to manually delete the DOM storage files and directories.
1223 Runnable deleteDomStorageRunnable = () -> {
1225 // Get a handle for the runtime.
1226 Runtime runtime = Runtime.getRuntime();
1228 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1229 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1230 String privateDataDirectoryString = getApplicationInfo().dataDir;
1232 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1233 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1235 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1236 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1237 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1238 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1239 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1241 // Wait for the processes to finish.
1242 deleteLocalStorageProcess.waitFor();
1243 deleteIndexProcess.waitFor();
1244 deleteQuotaManagerProcess.waitFor();
1245 deleteQuotaManagerJournalProcess.waitFor();
1246 deleteDatabasesProcess.waitFor();
1247 } catch (Exception exception) {
1248 // Do nothing if an error is thrown.
1252 // Manually delete the DOM storage files after 200 milliseconds.
1253 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1259 // Consume the event.
1262 // Form data can be remove once the minimum API >= 26.
1263 case R.id.clear_form_data:
1264 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1265 .setAction(R.string.undo, v -> {
1266 // Do nothing because everything will be handled by `onDismissed()` below.
1268 .addCallback(new Snackbar.Callback() {
1269 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1271 public void onDismissed(Snackbar snackbar, int event) {
1272 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1273 // Delete the form data.
1274 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1275 mainWebViewDatabase.clearFormData();
1281 // Consume the event.
1285 // Toggle the EasyList status.
1286 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1288 // Update the menu checkbox.
1289 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1291 // Reload the current WebView.
1292 currentWebView.reload();
1294 // Consume the event.
1297 case R.id.easyprivacy:
1298 // Toggle the EasyPrivacy status.
1299 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1301 // Update the menu checkbox.
1302 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1304 // Reload the current WebView.
1305 currentWebView.reload();
1307 // Consume the event.
1310 case R.id.fanboys_annoyance_list:
1311 // Toggle Fanboy's Annoyance List status.
1312 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1314 // Update the menu checkbox.
1315 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1317 // Update the staus of Fanboy's Social Blocking List.
1318 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1319 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1321 // Reload the current WebView.
1322 currentWebView.reload();
1324 // Consume the event.
1327 case R.id.fanboys_social_blocking_list:
1328 // Toggle Fanboy's Social Blocking List status.
1329 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1331 // Update the menu checkbox.
1332 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1334 // Reload the current WebView.
1335 currentWebView.reload();
1337 // Consume the event.
1340 case R.id.ultralist:
1341 // Toggle the UltraList status.
1342 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1344 // Update the menu checkbox.
1345 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1347 // Reload the current WebView.
1348 currentWebView.reload();
1350 // Consume the event.
1353 case R.id.ultraprivacy:
1354 // Toggle the UltraPrivacy status.
1355 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1357 // Update the menu checkbox.
1358 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1360 // Reload the current WebView.
1361 currentWebView.reload();
1363 // Consume the event.
1366 case R.id.block_all_third_party_requests:
1367 //Toggle the third-party requests blocker status.
1368 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1370 // Update the menu checkbox.
1371 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1373 // Reload the current WebView.
1374 currentWebView.reload();
1376 // Consume the event.
1379 case R.id.user_agent_privacy_browser:
1380 // Update the user agent.
1381 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1383 // Reload the current WebView.
1384 currentWebView.reload();
1386 // Consume the event.
1389 case R.id.user_agent_webview_default:
1390 // Update the user agent.
1391 currentWebView.getSettings().setUserAgentString("");
1393 // Reload the current WebView.
1394 currentWebView.reload();
1396 // Consume the event.
1399 case R.id.user_agent_firefox_on_android:
1400 // Update the user agent.
1401 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1403 // Reload the current WebView.
1404 currentWebView.reload();
1406 // Consume the event.
1409 case R.id.user_agent_chrome_on_android:
1410 // Update the user agent.
1411 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1413 // Reload the current WebView.
1414 currentWebView.reload();
1416 // Consume the event.
1419 case R.id.user_agent_safari_on_ios:
1420 // Update the user agent.
1421 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1423 // Reload the current WebView.
1424 currentWebView.reload();
1426 // Consume the event.
1429 case R.id.user_agent_firefox_on_linux:
1430 // Update the user agent.
1431 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1433 // Reload the current WebView.
1434 currentWebView.reload();
1436 // Consume the event.
1439 case R.id.user_agent_chromium_on_linux:
1440 // Update the user agent.
1441 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1443 // Reload the current WebView.
1444 currentWebView.reload();
1446 // Consume the event.
1449 case R.id.user_agent_firefox_on_windows:
1450 // Update the user agent.
1451 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1453 // Reload the current WebView.
1454 currentWebView.reload();
1456 // Consume the event.
1459 case R.id.user_agent_chrome_on_windows:
1460 // Update the user agent.
1461 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1463 // Reload the current WebView.
1464 currentWebView.reload();
1466 // Consume the event.
1469 case R.id.user_agent_edge_on_windows:
1470 // Update the user agent.
1471 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1473 // Reload the current WebView.
1474 currentWebView.reload();
1476 // Consume the event.
1479 case R.id.user_agent_internet_explorer_on_windows:
1480 // Update the user agent.
1481 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1483 // Reload the current WebView.
1484 currentWebView.reload();
1486 // Consume the event.
1489 case R.id.user_agent_safari_on_macos:
1490 // Update the user agent.
1491 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1493 // Reload the current WebView.
1494 currentWebView.reload();
1496 // Consume the event.
1499 case R.id.user_agent_custom:
1500 // Update the user agent.
1501 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1503 // Reload the current WebView.
1504 currentWebView.reload();
1506 // Consume the event.
1509 case R.id.font_size_twenty_five_percent:
1510 // Set the font size.
1511 currentWebView.getSettings().setTextZoom(25);
1513 // Consume the event.
1516 case R.id.font_size_fifty_percent:
1517 // Set the font size.
1518 currentWebView.getSettings().setTextZoom(50);
1520 // Consume the event.
1523 case R.id.font_size_seventy_five_percent:
1524 // Set the font size.
1525 currentWebView.getSettings().setTextZoom(75);
1527 // Consume the event.
1530 case R.id.font_size_one_hundred_percent:
1531 // Set the font size.
1532 currentWebView.getSettings().setTextZoom(100);
1534 // Consume the event.
1537 case R.id.font_size_one_hundred_twenty_five_percent:
1538 // Set the font size.
1539 currentWebView.getSettings().setTextZoom(125);
1541 // Consume the event.
1544 case R.id.font_size_one_hundred_fifty_percent:
1545 // Set the font size.
1546 currentWebView.getSettings().setTextZoom(150);
1548 // Consume the event.
1551 case R.id.font_size_one_hundred_seventy_five_percent:
1552 // Set the font size.
1553 currentWebView.getSettings().setTextZoom(175);
1555 // Consume the event.
1558 case R.id.font_size_two_hundred_percent:
1559 // Set the font size.
1560 currentWebView.getSettings().setTextZoom(200);
1562 // Consume the event.
1565 case R.id.swipe_to_refresh:
1566 // Toggle the stored status of swipe to refresh.
1567 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1569 // Get a handle for the swipe refresh layout.
1570 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1572 // Update the swipe refresh layout.
1573 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1574 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1575 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1576 } else { // Swipe to refresh is disabled.
1577 // Disable the swipe refresh layout.
1578 swipeRefreshLayout.setEnabled(false);
1581 // Consume the event.
1584 case R.id.wide_viewport:
1585 // Toggle the viewport.
1586 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1588 // Consume the event.
1591 case R.id.display_images:
1592 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1593 // Disable loading of images.
1594 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1596 // Reload the website to remove existing images.
1597 currentWebView.reload();
1598 } else { // Images are not currently loaded automatically.
1599 // Enable loading of images. Missing images will be loaded without the need for a reload.
1600 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1603 // Consume the event.
1606 case R.id.night_mode:
1607 // Toggle night mode.
1608 currentWebView.setNightMode(!currentWebView.getNightMode());
1610 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1611 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1612 // Enable JavaScript.
1613 currentWebView.getSettings().setJavaScriptEnabled(true);
1614 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1615 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1616 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1617 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1618 // Apply the JavaScript preference.
1619 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1622 // Update the privacy icons.
1623 updatePrivacyIcons(false);
1625 // Reload the website.
1626 currentWebView.reload();
1628 // Consume the event.
1631 case R.id.find_on_page:
1632 // Get a handle for the views.
1633 Toolbar toolbar = findViewById(R.id.toolbar);
1634 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1635 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1637 // Set the minimum height of the find on page linear layout to match the toolbar.
1638 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1640 // Hide the toolbar.
1641 toolbar.setVisibility(View.GONE);
1643 // Show the find on page linear layout.
1644 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1646 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1647 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1648 findOnPageEditText.postDelayed(() -> {
1649 // Set the focus on `findOnPageEditText`.
1650 findOnPageEditText.requestFocus();
1652 // Get a handle for the input method manager.
1653 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1655 // Remove the lint warning below that the input method manager might be null.
1656 assert inputMethodManager != null;
1658 // Display the keyboard. `0` sets no input flags.
1659 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1662 // Consume the event.
1666 // Get a print manager instance.
1667 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1669 // Remove the lint error below that print manager might be null.
1670 assert printManager != null;
1672 // Create a print document adapter from the current WebView.
1673 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1675 // Print the document.
1676 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1678 // Consume the event.
1681 case R.id.save_as_image:
1682 // Instantiate the save webpage image dialog.
1683 DialogFragment saveWebpageImageDialogFragment = new SaveWebpageImageDialog();
1685 // Show the save webpage image dialog.
1686 saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_as_image));
1688 // Consume the event.
1691 case R.id.add_to_homescreen:
1692 // Instantiate the create home screen shortcut dialog.
1693 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1694 currentWebView.getFavoriteOrDefaultIcon());
1696 // Show the create home screen shortcut dialog.
1697 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1699 // Consume the event.
1702 case R.id.view_source:
1703 // Create an intent to launch the view source activity.
1704 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1706 // Add the variables to the intent.
1707 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1708 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1711 startActivity(viewSourceIntent);
1713 // Consume the event.
1716 case R.id.share_url:
1717 // Setup the share string.
1718 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1720 // Create the share intent.
1721 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1722 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1723 shareIntent.setType("text/plain");
1726 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1728 // Consume the event.
1731 case R.id.open_with_app:
1732 // Open the URL with an outside app.
1733 openWithApp(currentWebView.getUrl());
1735 // Consume the event.
1738 case R.id.open_with_browser:
1739 // Open the URL with an outside browser.
1740 openWithBrowser(currentWebView.getUrl());
1742 // Consume the event.
1745 case R.id.proxy_through_orbot:
1746 // Toggle the proxy through Orbot variable.
1747 proxyThroughOrbot = !proxyThroughOrbot;
1749 // Apply the proxy through Orbot settings.
1750 applyProxyThroughOrbot(true);
1752 // Consume the event.
1756 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1757 // Reload the current WebView.
1758 currentWebView.reload();
1759 } else { // The stop button was pushed.
1760 // Stop the loading of the WebView.
1761 currentWebView.stopLoading();
1764 // Consume the event.
1767 case R.id.ad_consent:
1768 // Instantiate the ad consent dialog.
1769 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1771 // Display the ad consent dialog.
1772 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1774 // Consume the event.
1778 // Don't consume the event.
1779 return super.onOptionsItemSelected(menuItem);
1783 // removeAllCookies is deprecated, but it is required for API < 21.
1785 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1786 // Get the menu item ID.
1787 int menuItemId = menuItem.getItemId();
1789 // Get a handle for the shared preferences.
1790 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1792 // Run the commands that correspond to the selected menu item.
1793 switch (menuItemId) {
1794 case R.id.clear_and_exit:
1795 // Clear and exit Privacy Browser.
1800 // Select the homepage based on the proxy through Orbot status.
1801 if (proxyThroughOrbot) {
1802 // Load the Tor homepage.
1803 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
1805 // Load the normal homepage.
1806 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1811 if (currentWebView.canGoBack()) {
1812 // Get the current web back forward list.
1813 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1815 // Get the previous entry URL.
1816 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1818 // Apply the domain settings.
1819 applyDomainSettings(currentWebView, previousUrl, false, false);
1821 // Load the previous website in the history.
1822 currentWebView.goBack();
1827 if (currentWebView.canGoForward()) {
1828 // Get the current web back forward list.
1829 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1831 // Get the next entry URL.
1832 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1834 // Apply the domain settings.
1835 applyDomainSettings(currentWebView, nextUrl, false, false);
1837 // Load the next website in the history.
1838 currentWebView.goForward();
1843 // Instantiate the URL history dialog.
1844 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1846 // Show the URL history dialog.
1847 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1851 // Populate the resource requests.
1852 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1854 // Create an intent to launch the Requests activity.
1855 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1857 // Add the block third-party requests status to the intent.
1858 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1861 startActivity(requestsIntent);
1864 case R.id.downloads:
1865 // Launch the system Download Manager.
1866 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1868 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1869 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1871 startActivity(downloadManagerIntent);
1875 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1876 reapplyDomainSettingsOnRestart = true;
1878 // Launch the domains activity.
1879 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1881 // Add the extra information to the intent.
1882 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1884 // Get the current certificate.
1885 SslCertificate sslCertificate = currentWebView.getCertificate();
1887 // Check to see if the SSL certificate is populated.
1888 if (sslCertificate != null) {
1889 // Extract the certificate to strings.
1890 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1891 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1892 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1893 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1894 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1895 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1896 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1897 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1899 // Add the certificate to the intent.
1900 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1901 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1902 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1903 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1904 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1905 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1906 domainsIntent.putExtra("ssl_start_date", startDateLong);
1907 domainsIntent.putExtra("ssl_end_date", endDateLong);
1910 // Check to see if the current IP addresses have been received.
1911 if (currentWebView.hasCurrentIpAddresses()) {
1912 // Add the current IP addresses to the intent.
1913 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1917 startActivity(domainsIntent);
1921 // Set the flag to reapply app settings on restart when returning from Settings.
1922 reapplyAppSettingsOnRestart = true;
1924 // Set the flag to reapply the domain settings on restart when returning from Settings.
1925 reapplyDomainSettingsOnRestart = true;
1927 // Launch the settings activity.
1928 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1929 startActivity(settingsIntent);
1932 case R.id.import_export:
1933 // Launch the import/export activity.
1934 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1935 startActivity(importExportIntent);
1939 // Launch the logcat activity.
1940 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1941 startActivity(logcatIntent);
1945 // Launch `GuideActivity`.
1946 Intent guideIntent = new Intent(this, GuideActivity.class);
1947 startActivity(guideIntent);
1951 // Create an intent to launch the about activity.
1952 Intent aboutIntent = new Intent(this, AboutActivity.class);
1954 // Create a string array for the blocklist versions.
1955 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],
1956 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
1958 // Add the blocklist versions to the intent.
1959 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
1962 startActivity(aboutIntent);
1966 // Get a handle for the drawer layout.
1967 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1969 // Close the navigation drawer.
1970 drawerLayout.closeDrawer(GravityCompat.START);
1975 public void onPostCreate(Bundle savedInstanceState) {
1976 // Run the default commands.
1977 super.onPostCreate(savedInstanceState);
1979 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
1980 actionBarDrawerToggle.syncState();
1984 public void onConfigurationChanged(@NonNull Configuration newConfig) {
1985 // Run the default commands.
1986 super.onConfigurationChanged(newConfig);
1988 // Get the status bar pixel size.
1989 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
1990 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
1992 // Get the resource density.
1993 float screenDensity = getResources().getDisplayMetrics().density;
1995 // Recalculate the drawer header padding.
1996 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
1997 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
1998 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2000 // Reload the ad for the free flavor if not in full screen mode.
2001 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2002 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2003 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2006 // `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:
2007 // https://code.google.com/p/android/issues/detail?id=20493#c8
2008 // ActivityCompat.invalidateOptionsMenu(this);
2012 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2013 // Store the hit test result.
2014 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2016 // Define the URL strings.
2017 final String imageUrl;
2018 final String linkUrl;
2020 // Get handles for the system managers.
2021 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2022 FragmentManager fragmentManager = getSupportFragmentManager();
2023 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2025 // Remove the lint errors below that the clipboard manager might be null.
2026 assert clipboardManager != null;
2028 // Process the link according to the type.
2029 switch (hitTestResult.getType()) {
2030 // `SRC_ANCHOR_TYPE` is a link.
2031 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2032 // Get the target URL.
2033 linkUrl = hitTestResult.getExtra();
2035 // Set the target URL as the title of the `ContextMenu`.
2036 menu.setHeaderTitle(linkUrl);
2038 // Add an Open in New Tab entry.
2039 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2040 // Load the link URL in a new tab and move to it.
2041 addNewTab(linkUrl, true);
2043 // Consume the event.
2047 // Add an Open in Background entry.
2048 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2049 // Load the link URL in a new tab but do not move to it.
2050 addNewTab(linkUrl, false);
2052 // Consume the event.
2056 // Add an Open with App entry.
2057 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2058 openWithApp(linkUrl);
2060 // Consume the event.
2064 // Add an Open with Browser entry.
2065 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2066 openWithBrowser(linkUrl);
2068 // Consume the event.
2072 // Add a Copy URL entry.
2073 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2074 // Save the link URL in a `ClipData`.
2075 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2077 // Set the `ClipData` as the clipboard's primary clip.
2078 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2080 // Consume the event.
2084 // Add a Download URL entry.
2085 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2086 // Check if the download should be processed by an external app.
2087 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2088 openUrlWithExternalApp(linkUrl);
2089 } else { // Download with Android's download manager.
2090 // Check to see if the storage permission has already been granted.
2091 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2092 // Store the variables for future use by `onRequestPermissionsResult()`.
2093 downloadUrl = linkUrl;
2094 downloadContentDisposition = "none";
2095 downloadContentLength = -1;
2097 // Show a dialog if the user has previously denied the permission.
2098 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2099 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2100 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2102 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2103 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2104 } else { // Show the permission request directly.
2105 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2106 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2108 } else { // The storage permission has already been granted.
2109 // Get a handle for the download file alert dialog.
2110 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2112 // Show the download file alert dialog.
2113 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2117 // Consume the event.
2121 // Add a Cancel entry, which by default closes the context menu.
2122 menu.add(R.string.cancel);
2125 case WebView.HitTestResult.EMAIL_TYPE:
2126 // Get the target URL.
2127 linkUrl = hitTestResult.getExtra();
2129 // Set the target URL as the title of the `ContextMenu`.
2130 menu.setHeaderTitle(linkUrl);
2132 // Add a Write Email entry.
2133 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2134 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2135 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2137 // Parse the url and set it as the data for the `Intent`.
2138 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2140 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2141 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2144 startActivity(emailIntent);
2146 // Consume the event.
2150 // Add a Copy Email Address entry.
2151 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2152 // Save the email address in a `ClipData`.
2153 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2155 // Set the `ClipData` as the clipboard's primary clip.
2156 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2158 // Consume the event.
2162 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2163 menu.add(R.string.cancel);
2166 // `IMAGE_TYPE` is an image.
2167 case WebView.HitTestResult.IMAGE_TYPE:
2168 // Get the image URL.
2169 imageUrl = hitTestResult.getExtra();
2171 // Set the image URL as the title of the context menu.
2172 menu.setHeaderTitle(imageUrl);
2174 // Add an Open in New Tab entry.
2175 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2176 // Load the image in a new tab.
2177 addNewTab(imageUrl, true);
2179 // Consume the event.
2183 // Add a View Image entry.
2184 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2185 // Load the image in the current tab.
2188 // Consume the event.
2192 // Add a Download Image entry.
2193 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2194 // Check if the download should be processed by an external app.
2195 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2196 openUrlWithExternalApp(imageUrl);
2197 } else { // Download with Android's download manager.
2198 // Check to see if the storage permission has already been granted.
2199 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2200 // Store the image URL for use by `onRequestPermissionResult()`.
2201 downloadImageUrl = imageUrl;
2203 // Show a dialog if the user has previously denied the permission.
2204 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2205 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2206 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2208 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2209 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2210 } else { // Show the permission request directly.
2211 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2212 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2214 } else { // The storage permission has already been granted.
2215 // Get a handle for the download image alert dialog.
2216 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2218 // Show the download image alert dialog.
2219 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2223 // Consume the event.
2227 // Add a Copy URL entry.
2228 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2229 // Save the image URL in a clip data.
2230 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2232 // Set the clip data as the clipboard's primary clip.
2233 clipboardManager.setPrimaryClip(imageTypeClipData);
2235 // Consume the event.
2239 // Add an Open with App entry.
2240 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2241 // Open the image URL with an external app.
2242 openWithApp(imageUrl);
2244 // Consume the event.
2248 // Add an Open with Browser entry.
2249 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2250 // Open the image URL with an external browser.
2251 openWithBrowser(imageUrl);
2253 // Consume the event.
2257 // Add a Cancel entry, which by default closes the context menu.
2258 menu.add(R.string.cancel);
2261 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2262 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2263 // Get the image URL.
2264 imageUrl = hitTestResult.getExtra();
2266 // Instantiate a handler.
2267 Handler handler = new Handler();
2269 // Get a message from the handler.
2270 Message message = handler.obtainMessage();
2272 // Request the image details from the last touched node be returned in the message.
2273 currentWebView.requestFocusNodeHref(message);
2275 // Get the link URL from the message data.
2276 linkUrl = message.getData().getString("url");
2278 // Set the link URL as the title of the context menu.
2279 menu.setHeaderTitle(linkUrl);
2281 // Add an Open in New Tab entry.
2282 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2283 // Load the link URL in a new tab and move to it.
2284 addNewTab(linkUrl, true);
2286 // Consume the event.
2290 // Add an Open in Background entry.
2291 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2292 // Lod the link URL in a new tab but do not move to it.
2293 addNewTab(linkUrl, false);
2295 // Consume the event.
2299 // Add an Open Image in New Tab entry.
2300 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2301 // Load the image in a new tab and move to it.
2302 addNewTab(imageUrl, true);
2304 // Consume the event.
2308 // Add a View Image entry.
2309 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2310 // View the image in the current tab.
2313 // Consume the event.
2317 // Add a Download Image entry.
2318 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2319 // Check if the download should be processed by an external app.
2320 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2321 openUrlWithExternalApp(imageUrl);
2322 } else { // Download with Android's download manager.
2323 // Check to see if the storage permission has already been granted.
2324 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2325 // Store the image URL for use by `onRequestPermissionResult()`.
2326 downloadImageUrl = imageUrl;
2328 // Show a dialog if the user has previously denied the permission.
2329 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2330 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2331 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2333 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2334 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2335 } else { // Show the permission request directly.
2336 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2337 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2339 } else { // The storage permission has already been granted.
2340 // Get a handle for the download image alert dialog.
2341 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2343 // Show the download image alert dialog.
2344 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2348 // Consume the event.
2352 // Add a Copy URL entry.
2353 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2354 // Save the link URL in a clip data.
2355 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2357 // Set the clip data as the clipboard's primary clip.
2358 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2360 // Consume the event.
2364 // Add an Open with App entry.
2365 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2366 // Open the link URL with an external app.
2367 openWithApp(linkUrl);
2369 // Consume the event.
2373 // Add an Open with Browser entry.
2374 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2375 // Open the link URL with an external browser.
2376 openWithBrowser(linkUrl);
2378 // Consume the event.
2382 // Add a cancel entry, which by default closes the context menu.
2383 menu.add(R.string.cancel);
2389 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2390 // Get a handle for the bookmarks list view.
2391 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2394 Dialog dialog = dialogFragment.getDialog();
2396 // Remove the incorrect lint warning below that the dialog might be null.
2397 assert dialog != null;
2399 // Get the views from the dialog fragment.
2400 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2401 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2403 // Extract the strings from the edit texts.
2404 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2405 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2407 // Create a favorite icon byte array output stream.
2408 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2410 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2411 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2413 // Convert the favorite icon byte array stream to a byte array.
2414 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2416 // Display the new bookmark below the current items in the (0 indexed) list.
2417 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2419 // Create the bookmark.
2420 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2422 // Update the bookmarks cursor with the current contents of this folder.
2423 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2425 // Update the list view.
2426 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2428 // Scroll to the new bookmark.
2429 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2433 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2434 // Get a handle for the bookmarks list view.
2435 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2438 Dialog dialog = dialogFragment.getDialog();
2440 // Remove the incorrect lint warning below that the dialog might be null.
2441 assert dialog != null;
2443 // Get handles for the views in the dialog fragment.
2444 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2445 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2446 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2448 // Get new folder name string.
2449 String folderNameString = createFolderNameEditText.getText().toString();
2451 // Create a folder icon bitmap.
2452 Bitmap folderIconBitmap;
2454 // Set the folder icon bitmap according to the dialog.
2455 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2456 // Get the default folder icon drawable.
2457 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2459 // Convert the folder icon drawable to a bitmap drawable.
2460 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2462 // Convert the folder icon bitmap drawable to a bitmap.
2463 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2464 } else { // Use the WebView favorite icon.
2465 // Copy the favorite icon bitmap to the folder icon bitmap.
2466 folderIconBitmap = favoriteIconBitmap;
2469 // Create a folder icon byte array output stream.
2470 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2472 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2473 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2475 // Convert the folder icon byte array stream to a byte array.
2476 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2478 // Move all the bookmarks down one in the display order.
2479 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2480 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2481 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2484 // Create the folder, which will be placed at the top of the `ListView`.
2485 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2487 // Update the bookmarks cursor with the current contents of this folder.
2488 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2490 // Update the `ListView`.
2491 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2493 // Scroll to the new folder.
2494 bookmarksListView.setSelection(0);
2498 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2500 Dialog dialog = dialogFragment.getDialog();
2502 // Remove the incorrect lint warning below that the dialog might be null.
2503 assert dialog != null;
2505 // Get handles for the views from the dialog.
2506 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
2507 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
2508 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2510 // Store the bookmark strings.
2511 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2512 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2514 // Update the bookmark.
2515 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2516 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2517 } else { // Update the bookmark using the `WebView` favorite icon.
2518 // Create a favorite icon byte array output stream.
2519 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2521 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2522 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2524 // Convert the favorite icon byte array stream to a byte array.
2525 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2527 // Update the bookmark and the favorite icon.
2528 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2531 // Update the bookmarks cursor with the current contents of this folder.
2532 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2534 // Update the list view.
2535 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2539 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2541 Dialog dialog = dialogFragment.getDialog();
2543 // Remove the incorrect lint warning below that the dialog might be null.
2544 assert dialog != null;
2546 // Get handles for the views from `dialogFragment`.
2547 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2548 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2549 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2550 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2552 // Get the new folder name.
2553 String newFolderNameString = editFolderNameEditText.getText().toString();
2555 // Check if the favorite icon has changed.
2556 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2557 // Update the name in the database.
2558 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2559 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2560 // Create the new folder icon Bitmap.
2561 Bitmap folderIconBitmap;
2563 // Populate the new folder icon bitmap.
2564 if (defaultFolderIconRadioButton.isChecked()) {
2565 // Get the default folder icon drawable.
2566 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2568 // Convert the folder icon drawable to a bitmap drawable.
2569 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2571 // Convert the folder icon bitmap drawable to a bitmap.
2572 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2573 } else { // Use the `WebView` favorite icon.
2574 // Copy the favorite icon bitmap to the folder icon bitmap.
2575 folderIconBitmap = favoriteIconBitmap;
2578 // Create a folder icon byte array output stream.
2579 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2581 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2582 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2584 // Convert the folder icon byte array stream to a byte array.
2585 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2587 // Update the folder icon in the database.
2588 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2589 } else { // The folder icon and the name have changed.
2590 // Get the new folder icon `Bitmap`.
2591 Bitmap folderIconBitmap;
2592 if (defaultFolderIconRadioButton.isChecked()) {
2593 // Get the default folder icon drawable.
2594 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2596 // Convert the folder icon drawable to a bitmap drawable.
2597 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2599 // Convert the folder icon bitmap drawable to a bitmap.
2600 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2601 } else { // Use the `WebView` favorite icon.
2602 // Copy the favorite icon bitmap to the folder icon bitmap.
2603 folderIconBitmap = favoriteIconBitmap;
2606 // Create a folder icon byte array output stream.
2607 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2609 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2610 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2612 // Convert the folder icon byte array stream to a byte array.
2613 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2615 // Update the folder name and icon in the database.
2616 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2619 // Update the bookmarks cursor with the current contents of this folder.
2620 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2622 // Update the `ListView`.
2623 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2627 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2628 switch (downloadType) {
2629 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2630 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2631 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2634 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2635 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2636 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2642 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
2643 // Get a handle for the fragment manager.