2 * Copyright © 2015-2020 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.database.Cursor;
41 import android.graphics.Bitmap;
42 import android.graphics.BitmapFactory;
43 import android.graphics.Typeface;
44 import android.graphics.drawable.BitmapDrawable;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.net.http.SslCertificate;
48 import android.net.http.SslError;
49 import android.os.Build;
50 import android.os.Bundle;
51 import android.os.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.SaveUrl;
123 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
124 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
125 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
126 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
127 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
128 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
129 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
130 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
131 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
132 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
133 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
134 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
135 import com.stoutner.privacybrowser.dialogs.OpenDialog;
136 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
137 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
138 import com.stoutner.privacybrowser.dialogs.SaveWebpageDialog;
139 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
140 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
141 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
142 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
143 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
144 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
145 import com.stoutner.privacybrowser.helpers.AdHelper;
146 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
147 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
148 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
149 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
150 import com.stoutner.privacybrowser.helpers.FileNameHelper;
151 import com.stoutner.privacybrowser.helpers.ProxyHelper;
152 import com.stoutner.privacybrowser.views.NestedScrollWebView;
154 import java.io.ByteArrayInputStream;
155 import java.io.ByteArrayOutputStream;
157 import java.io.IOException;
158 import java.io.UnsupportedEncodingException;
159 import java.net.MalformedURLException;
161 import java.net.URLDecoder;
162 import java.net.URLEncoder;
163 import java.util.ArrayList;
164 import java.util.Date;
165 import java.util.HashMap;
166 import java.util.HashSet;
167 import java.util.List;
168 import java.util.Map;
169 import java.util.Objects;
170 import java.util.Set;
172 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
173 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
174 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
175 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
176 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageDialog.SaveWebpageListener, StoragePermissionDialog.StoragePermissionDialogListener,
177 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
179 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
180 public static String orbotStatus = "unknown";
182 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
183 public static WebViewPagerAdapter webViewPagerAdapter;
185 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
186 public static boolean loadUrlOnRestart;
187 public static String urlToLoadOnRestart;
189 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
190 public static boolean restartFromBookmarksActivity;
192 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
193 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
194 public static String currentBookmarksFolder;
196 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
197 public final static int UNRECOGNIZED_USER_AGENT = -1;
198 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
199 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
200 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
201 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
202 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
204 // Start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
205 public final static int BROWSE_OPEN_REQUEST_CODE = 0;
206 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 1;
207 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 2;
209 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
210 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
211 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
212 public static String proxyMode = ProxyHelper.NONE;
215 // The permission result request codes are used in `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, `onSaveWebpage()`,
216 // `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
217 private final int PERMISSION_DOWNLOAD_FILE_REQUEST_CODE = 0;
218 private final int PERMISSION_DOWNLOAD_IMAGE_REQUEST_CODE = 1;
219 private final int PERMISSION_OPEN_REQUEST_CODE = 2;
220 private final int PERMISSION_SAVE_WEBPAGE_ARCHIVE_REQUEST_CODE = 3;
221 private final int PERMISSION_SAVE_WEBPAGE_IMAGE_REQUEST_CODE = 4;
222 private final int PERMISSION_SAVE_WEBPAGE_RAW_REQUEST_CODE = 5;
224 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
225 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
226 private NestedScrollWebView currentWebView;
228 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
229 private final Map<String, String> customHeaders = new HashMap<>();
231 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
232 private String searchURL;
234 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
235 private Menu optionsMenu;
237 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
238 private ArrayList<List<String[]>> easyList;
239 private ArrayList<List<String[]>> easyPrivacy;
240 private ArrayList<List<String[]>> fanboysAnnoyanceList;
241 private ArrayList<List<String[]>> fanboysSocialList;
242 private ArrayList<List<String[]>> ultraList;
243 private ArrayList<List<String[]>> ultraPrivacy;
245 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
246 private String webViewDefaultUserAgent;
248 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
249 private boolean incognitoModeEnabled;
251 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
252 private boolean fullScreenBrowsingModeEnabled;
254 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
255 private boolean inFullScreenBrowsingMode;
257 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
258 private boolean hideAppBar;
259 private boolean scrollAppBar;
261 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
262 private boolean loadingNewIntent;
264 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
265 private boolean reapplyDomainSettingsOnRestart;
267 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
268 private boolean reapplyAppSettingsOnRestart;
270 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
271 private boolean displayingFullScreenVideo;
273 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
274 private BroadcastReceiver orbotStatusBroadcastReceiver;
276 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
277 private boolean waitingForProxy = false;
279 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
280 private ActionBarDrawerToggle actionBarDrawerToggle;
282 // The color spans are used in `onCreate()` and `highlightUrlText()`.
283 private ForegroundColorSpan redColorSpan;
284 private ForegroundColorSpan initialGrayColorSpan;
285 private ForegroundColorSpan finalGrayColorSpan;
287 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
288 private int drawerHeaderPaddingLeftAndRight;
289 private int drawerHeaderPaddingTop;
290 private int drawerHeaderPaddingBottom;
292 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
293 // and `loadBookmarksFolder()`.
294 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
296 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
297 private Cursor bookmarksCursor;
299 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
300 private CursorAdapter bookmarksCursorAdapter;
302 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
303 private String oldFolderNameString;
305 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
306 private ValueCallback<Uri[]> fileChooserCallback;
308 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
309 private int defaultProgressViewStartOffset;
310 private int defaultProgressViewEndOffset;
312 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
313 private int swipeRefreshLayoutPaddingTop;
315 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
316 private boolean sanitizeGoogleAnalytics;
317 private boolean sanitizeFacebookClickIds;
318 private boolean sanitizeTwitterAmpRedirects;
320 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
321 private String downloadUrl;
322 private String downloadContentDisposition;
323 private long downloadContentLength;
325 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
326 private String downloadImageUrl;
328 // The file path strings are used in `onSaveWebpageImage()` and `onRequestPermissionResult()`
329 private String openFilePath;
330 private String saveWebpageUrl;
331 private String saveWebpageFilePath;
334 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
335 @SuppressLint("ClickableViewAccessibility")
336 protected void onCreate(Bundle savedInstanceState) {
337 if (Build.VERSION.SDK_INT >= 21) {
338 WebView.enableSlowWholeDocumentDraw();
341 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
342 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
344 // Get a handle for the shared preferences.
345 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
347 // Get the theme and screenshot preferences.
348 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
349 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
351 // Disable screenshots if not allowed.
352 if (!allowScreenshots) {
353 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
356 // Set the activity theme.
358 setTheme(R.style.PrivacyBrowserDark);
360 setTheme(R.style.PrivacyBrowserLight);
363 // Run the default commands.
364 super.onCreate(savedInstanceState);
366 // Set the content view.
367 setContentView(R.layout.main_framelayout);
369 // Get handles for the views that need to be modified.
370 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
371 Toolbar toolbar = findViewById(R.id.toolbar);
372 ViewPager webViewPager = findViewById(R.id.webviewpager);
374 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
375 setSupportActionBar(toolbar);
377 // Get a handle for the action bar.
378 ActionBar actionBar = getSupportActionBar();
380 // This is needed to get rid of the Android Studio warning that the action bar might be null.
381 assert actionBar != null;
383 // Add the custom layout, which shows the URL text bar.
384 actionBar.setCustomView(R.layout.url_app_bar);
385 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
387 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
388 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
390 // Create the hamburger icon at the start of the AppBar.
391 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
393 // Initialize the web view pager adapter.
394 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
396 // Set the pager adapter on the web view pager.
397 webViewPager.setAdapter(webViewPagerAdapter);
399 // Store up to 100 tabs in memory.
400 webViewPager.setOffscreenPageLimit(100);
402 // Populate the blocklists.
403 new PopulateBlocklists(this, this).execute();
407 protected void onNewIntent(Intent intent) {
408 // Run the default commands.
409 super.onNewIntent(intent);
411 // Replace the intent that started the app with this one.
414 // 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()`.
415 if (ultraPrivacy != null) {
416 // Get the information from the intent.
417 String intentAction = intent.getAction();
418 Uri intentUriData = intent.getData();
420 // Determine if this is a web search.
421 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
423 // 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.
424 if (intentUriData != null || isWebSearch) {
425 // Get the shared preferences.
426 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
428 // Create a URL string.
431 // If the intent action is a web search, perform the search.
433 // Create an encoded URL string.
434 String encodedUrlString;
436 // Sanitize the search input and convert it to a search.
438 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
439 } catch (UnsupportedEncodingException exception) {
440 encodedUrlString = "";
443 // Add the base search URL.
444 url = searchURL + encodedUrlString;
445 } else { // The intent should contain a URL.
446 // Set the intent data as the URL.
447 url = intentUriData.toString();
450 // Add a new tab if specified in the preferences.
451 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
452 // Set the loading new intent flag.
453 loadingNewIntent = true;
456 addNewTab(url, true);
457 } else { // Load the URL in the current tab.
459 loadUrl(currentWebView, url);
462 // Get a handle for the drawer layout.
463 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
465 // Close the navigation drawer if it is open.
466 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
467 drawerLayout.closeDrawer(GravityCompat.START);
470 // Close the bookmarks drawer if it is open.
471 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
472 drawerLayout.closeDrawer(GravityCompat.END);
479 public void onRestart() {
480 // Run the default commands.
483 // Apply the app settings if returning from the Settings activity.
484 if (reapplyAppSettingsOnRestart) {
485 // Reset the reapply app settings on restart tracker.
486 reapplyAppSettingsOnRestart = false;
488 // Apply the app settings.
492 // Apply the domain settings if returning from the settings or domains activity.
493 if (reapplyDomainSettingsOnRestart) {
494 // Reset the reapply domain settings on restart tracker.
495 reapplyDomainSettingsOnRestart = false;
497 // Reapply the domain settings for each tab.
498 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
499 // Get the WebView tab fragment.
500 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
502 // Get the fragment view.
503 View fragmentView = webViewTabFragment.getView();
505 // Only reload the WebViews if they exist.
506 if (fragmentView != null) {
507 // Get the nested scroll WebView from the tab fragment.
508 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
510 // Reset the current domain name so the domain settings will be reapplied.
511 nestedScrollWebView.resetCurrentDomainName();
513 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
514 if (nestedScrollWebView.getUrl() != null) {
515 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
521 // Load the URL on restart (used when loading a bookmark).
522 if (loadUrlOnRestart) {
523 // Load the specified URL.
524 loadUrl(currentWebView, urlToLoadOnRestart);
526 // Reset the load on restart tracker.
527 loadUrlOnRestart = false;
530 // Update the bookmarks drawer if returning from the Bookmarks activity.
531 if (restartFromBookmarksActivity) {
532 // Get a handle for the drawer layout.
533 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
535 // Close the bookmarks drawer.
536 drawerLayout.closeDrawer(GravityCompat.END);
538 // Reload the bookmarks drawer.
539 loadBookmarksFolder();
541 // Reset `restartFromBookmarksActivity`.
542 restartFromBookmarksActivity = false;
545 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
546 updatePrivacyIcons(true);
549 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
551 public void onResume() {
552 // Run the default commands.
555 // Resume any WebViews.
556 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
557 // Get the WebView tab fragment.
558 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
560 // Get the fragment view.
561 View fragmentView = webViewTabFragment.getView();
563 // Only resume the WebViews if they exist (they won't when the app is first created).
564 if (fragmentView != null) {
565 // Get the nested scroll WebView from the tab fragment.
566 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
568 // Resume the nested scroll WebView JavaScript timers.
569 nestedScrollWebView.resumeTimers();
571 // Resume the nested scroll WebView.
572 nestedScrollWebView.onResume();
576 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
577 if (!proxyMode.equals(ProxyHelper.NONE)) {
581 // Reapply any system UI flags and the ad in the free flavor.
582 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
583 // Get a handle for the root frame layouts.
584 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
586 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
587 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
589 /* Hide the system bars.
590 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
591 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
592 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
593 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
595 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
596 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
597 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
599 AdHelper.resumeAd(findViewById(R.id.adview));
604 public void onPause() {
605 // Run the default commands.
608 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
609 // Get the WebView tab fragment.
610 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
612 // Get the fragment view.
613 View fragmentView = webViewTabFragment.getView();
615 // Only pause the WebViews if they exist (they won't when the app is first created).
616 if (fragmentView != null) {
617 // Get the nested scroll WebView from the tab fragment.
618 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
620 // Pause the nested scroll WebView.
621 nestedScrollWebView.onPause();
623 // Pause the nested scroll WebView JavaScript timers.
624 nestedScrollWebView.pauseTimers();
628 // Pause the ad or it will continue to consume resources in the background on the free flavor.
629 if (BuildConfig.FLAVOR.contentEquals("free")) {
631 AdHelper.pauseAd(findViewById(R.id.adview));
636 public void onDestroy() {
637 // Unregister the orbot status broadcast receiver.
638 this.unregisterReceiver(orbotStatusBroadcastReceiver);
640 // Close the bookmarks cursor and database.
641 bookmarksCursor.close();
642 bookmarksDatabaseHelper.close();
644 // Run the default commands.
649 public boolean onCreateOptionsMenu(Menu menu) {
650 // Inflate the menu. This adds items to the action bar if it is present.
651 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
653 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
656 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
657 updatePrivacyIcons(false);
659 // Get handles for the menu items.
660 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
661 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
662 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
663 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
664 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
665 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
666 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
668 // Only display third-party cookies if API >= 21
669 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
671 // Only display the form data menu items if the API < 26.
672 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
673 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
675 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
676 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
678 // Only show Ad Consent if this is the free flavor.
679 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
681 // Get the shared preferences.
682 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
684 // Get the dark theme and app bar preferences..
685 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
686 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
688 // 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.
689 if (displayAdditionalAppBarIcons) {
690 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
691 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
692 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
693 } else { //Do not display the additional icons.
694 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
695 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
696 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
699 // Replace Refresh with Stop if a URL is already loading.
700 if (currentWebView != null && currentWebView.getProgress() != 100) {
702 refreshMenuItem.setTitle(R.string.stop);
704 // If the icon is displayed in the AppBar, set it according to the theme.
705 if (displayAdditionalAppBarIcons) {
707 refreshMenuItem.setIcon(R.drawable.close_dark);
709 refreshMenuItem.setIcon(R.drawable.close_light);
719 public boolean onPrepareOptionsMenu(Menu menu) {
720 // Get handles for the menu items.
721 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
722 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
723 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
724 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
725 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
726 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
727 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
728 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
729 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
730 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
731 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
732 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
733 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
734 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
735 MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
736 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
737 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
738 MenuItem proxyMenuItem = menu.findItem(R.id.proxy);
739 MenuItem userAgentMenuItem = menu.findItem(R.id.user_agent);
740 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
741 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
742 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
743 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
744 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
746 // Get a handle for the cookie manager.
747 CookieManager cookieManager = CookieManager.getInstance();
749 // Initialize the current user agent string and the font size.
750 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
753 // 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.
754 if (currentWebView != null) {
755 // Set the add or edit domain text.
756 if (currentWebView.getDomainSettingsApplied()) {
757 addOrEditDomain.setTitle(R.string.edit_domain_settings);
759 addOrEditDomain.setTitle(R.string.add_domain_settings);
762 // Get the current user agent from the WebView.
763 currentUserAgent = currentWebView.getSettings().getUserAgentString();
765 // Get the current font size from the
766 fontSize = currentWebView.getSettings().getTextZoom();
768 // Set the status of the menu item checkboxes.
769 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
770 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
771 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
772 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
773 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
774 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
775 ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
776 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
777 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
778 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
779 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
780 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
781 nightModeMenuItem.setChecked(currentWebView.getNightMode());
783 // Initialize the display names for the blocklists with the number of blocked requests.
784 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
785 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
786 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
787 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
788 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
789 ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
790 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
791 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
793 // Only modify third-party cookies if the API >= 21.
794 if (Build.VERSION.SDK_INT >= 21) {
795 // Set the status of the third-party cookies checkbox.
796 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
798 // Enable third-party cookies if first-party cookies are enabled.
799 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
802 // Enable DOM Storage if JavaScript is enabled.
803 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
806 // Set the checked status of the first party cookies menu item.
807 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
809 // Enable Clear Cookies if there are any.
810 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
812 // 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`.
813 String privateDataDirectoryString = getApplicationInfo().dataDir;
815 // Get a count of the number of files in the Local Storage directory.
816 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
817 int localStorageDirectoryNumberOfFiles = 0;
818 if (localStorageDirectory.exists()) {
819 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
820 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
823 // Get a count of the number of files in the IndexedDB directory.
824 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
825 int indexedDBDirectoryNumberOfFiles = 0;
826 if (indexedDBDirectory.exists()) {
827 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
828 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
831 // Enable Clear DOM Storage if there is any.
832 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
834 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
835 if (Build.VERSION.SDK_INT < 26) {
836 // Get the WebView database.
837 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
839 // Enable the clear form data menu item if there is anything to clear.
840 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
843 // Enable Clear Data if any of the submenu items are enabled.
844 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
846 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
847 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
849 // Set the proxy title and check the applied proxy.
851 case ProxyHelper.NONE:
852 // Set the proxy title.
853 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
855 // Check the proxy None radio button.
856 menu.findItem(R.id.proxy_none).setChecked(true);
859 case ProxyHelper.TOR:
860 // Set the proxy title.
861 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
863 // Check the proxy Tor radio button.
864 menu.findItem(R.id.proxy_tor).setChecked(true);
867 case ProxyHelper.I2P:
868 // Set the proxy title.
869 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
871 // Check the proxy I2P radio button.
872 menu.findItem(R.id.proxy_i2p).setChecked(true);
875 case ProxyHelper.CUSTOM:
876 // Set the proxy title.
877 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
879 // Check the proxy Custom radio button.
880 menu.findItem(R.id.proxy_custom).setChecked(true);
884 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
885 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
886 // Update the user agent menu item title.
887 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
889 // Select the Privacy Browser radio box.
890 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
891 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
892 // Update the user agent menu item title.
893 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
895 // Select the WebView Default radio box.
896 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
897 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
898 // Update the user agent menu item title.
899 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
901 // Select the Firefox on Android radio box.
902 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
903 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
904 // Update the user agent menu item title.
905 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
907 // Select the Chrome on Android radio box.
908 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
909 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
910 // Update the user agent menu item title.
911 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
913 // Select the Safari on iOS radio box.
914 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
915 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
916 // Update the user agent menu item title.
917 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
919 // Select the Firefox on Linux radio box.
920 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
921 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
922 // Update the user agent menu item title.
923 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
925 // Select the Chromium on Linux radio box.
926 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
927 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
928 // Update the user agent menu item title.
929 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
931 // Select the Firefox on Windows radio box.
932 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
933 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
934 // Update the user agent menu item title.
935 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
937 // Select the Chrome on Windows radio box.
938 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
939 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
940 // Update the user agent menu item title.
941 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
943 // Select the Edge on Windows radio box.
944 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
945 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
946 // Update the user agent menu item title.
947 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
949 // Select the Internet on Windows radio box.
950 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
951 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
952 // Update the user agent menu item title.
953 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
955 // Select the Safari on macOS radio box.
956 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
957 } else { // Custom user agent.
958 // Update the user agent menu item title.
959 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
961 // Select the Custom radio box.
962 menu.findItem(R.id.user_agent_custom).setChecked(true);
965 // Set the font size title.
966 fontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
968 // Run all the other default commands.
969 super.onPrepareOptionsMenu(menu);
976 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
977 @SuppressLint("SetJavaScriptEnabled")
978 public boolean onOptionsItemSelected(MenuItem menuItem) {
979 // Get the selected menu item ID.
980 int menuItemId = menuItem.getItemId();
982 // Get a handle for the shared preferences.
983 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
985 // Get a handle for the cookie manager.
986 CookieManager cookieManager = CookieManager.getInstance();
988 // Run the commands that correlate to the selected menu item.
989 switch (menuItemId) {
990 case R.id.toggle_javascript:
991 // Toggle the JavaScript status.
992 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
994 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
995 updatePrivacyIcons(true);
997 // Display a `Snackbar`.
998 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
999 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1000 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1001 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1002 } else { // Privacy mode.
1003 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1006 // Reload the current WebView.
1007 currentWebView.reload();
1009 // Consume the event.
1012 case R.id.add_or_edit_domain:
1013 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1014 // Reapply the domain settings on returning to `MainWebViewActivity`.
1015 reapplyDomainSettingsOnRestart = true;
1017 // Create an intent to launch the domains activity.
1018 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1020 // Add the extra information to the intent.
1021 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1022 domainsIntent.putExtra("close_on_back", true);
1023 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1025 // Get the current certificate.
1026 SslCertificate sslCertificate = currentWebView.getCertificate();
1028 // Check to see if the SSL certificate is populated.
1029 if (sslCertificate != null) {
1030 // Extract the certificate to strings.
1031 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1032 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1033 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1034 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1035 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1036 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1037 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1038 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1040 // Add the certificate to the intent.
1041 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1042 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1043 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1044 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1045 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1046 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1047 domainsIntent.putExtra("ssl_start_date", startDateLong);
1048 domainsIntent.putExtra("ssl_end_date", endDateLong);
1051 // Check to see if the current IP addresses have been received.
1052 if (currentWebView.hasCurrentIpAddresses()) {
1053 // Add the current IP addresses to the intent.
1054 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1058 startActivity(domainsIntent);
1059 } else { // Add a new domain.
1060 // Apply the new domain settings on returning to `MainWebViewActivity`.
1061 reapplyDomainSettingsOnRestart = true;
1063 // Get the current domain
1064 Uri currentUri = Uri.parse(currentWebView.getUrl());
1065 String currentDomain = currentUri.getHost();
1067 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1068 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1070 // Create the domain and store the database ID.
1071 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1073 // Create an intent to launch the domains activity.
1074 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1076 // Add the extra information to the intent.
1077 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1078 domainsIntent.putExtra("close_on_back", true);
1079 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1081 // Get the current certificate.
1082 SslCertificate sslCertificate = currentWebView.getCertificate();
1084 // Check to see if the SSL certificate is populated.
1085 if (sslCertificate != null) {
1086 // Extract the certificate to strings.
1087 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1088 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1089 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1090 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1091 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1092 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1093 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1094 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1096 // Add the certificate to the intent.
1097 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1098 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1099 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1100 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1101 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1102 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1103 domainsIntent.putExtra("ssl_start_date", startDateLong);
1104 domainsIntent.putExtra("ssl_end_date", endDateLong);
1107 // Check to see if the current IP addresses have been received.
1108 if (currentWebView.hasCurrentIpAddresses()) {
1109 // Add the current IP addresses to the intent.
1110 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1114 startActivity(domainsIntent);
1117 // Consume the event.
1120 case R.id.toggle_first_party_cookies:
1121 // Switch the first-party cookie status.
1122 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1124 // Store the first-party cookie status.
1125 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1127 // Update the menu checkbox.
1128 menuItem.setChecked(cookieManager.acceptCookie());
1130 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1131 updatePrivacyIcons(true);
1133 // Display a snackbar.
1134 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1135 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1136 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1137 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1138 } else { // Privacy mode.
1139 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1142 // Reload the current WebView.
1143 currentWebView.reload();
1145 // Consume the event.
1148 case R.id.toggle_third_party_cookies:
1149 if (Build.VERSION.SDK_INT >= 21) {
1150 // Switch the status of thirdPartyCookiesEnabled.
1151 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1153 // Update the menu checkbox.
1154 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1156 // Display a snackbar.
1157 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1158 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1160 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1163 // Reload the current WebView.
1164 currentWebView.reload();
1165 } // Else do nothing because SDK < 21.
1167 // Consume the event.
1170 case R.id.toggle_dom_storage:
1171 // Toggle the status of domStorageEnabled.
1172 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1174 // Update the menu checkbox.
1175 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1177 // Update the privacy icon. `true` refreshes the app bar icons.
1178 updatePrivacyIcons(true);
1180 // Display a snackbar.
1181 if (currentWebView.getSettings().getDomStorageEnabled()) {
1182 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1184 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1187 // Reload the current WebView.
1188 currentWebView.reload();
1190 // Consume the event.
1193 // Form data can be removed once the minimum API >= 26.
1194 case R.id.toggle_save_form_data:
1195 // Switch the status of saveFormDataEnabled.
1196 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1198 // Update the menu checkbox.
1199 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1201 // Display a snackbar.
1202 if (currentWebView.getSettings().getSaveFormData()) {
1203 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1205 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1208 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1209 updatePrivacyIcons(true);
1211 // Reload the current WebView.
1212 currentWebView.reload();
1214 // Consume the event.
1217 case R.id.clear_cookies:
1218 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1219 .setAction(R.string.undo, v -> {
1220 // Do nothing because everything will be handled by `onDismissed()` below.
1222 .addCallback(new Snackbar.Callback() {
1223 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1225 public void onDismissed(Snackbar snackbar, int event) {
1226 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1227 // Delete the cookies, which command varies by SDK.
1228 if (Build.VERSION.SDK_INT < 21) {
1229 cookieManager.removeAllCookie();
1231 cookieManager.removeAllCookies(null);
1238 // Consume the event.
1241 case R.id.clear_dom_storage:
1242 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1243 .setAction(R.string.undo, v -> {
1244 // Do nothing because everything will be handled by `onDismissed()` below.
1246 .addCallback(new Snackbar.Callback() {
1247 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1249 public void onDismissed(Snackbar snackbar, int event) {
1250 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1251 // Delete the DOM Storage.
1252 WebStorage webStorage = WebStorage.getInstance();
1253 webStorage.deleteAllData();
1255 // Initialize a handler to manually delete the DOM storage files and directories.
1256 Handler deleteDomStorageHandler = new Handler();
1258 // Setup a runnable to manually delete the DOM storage files and directories.
1259 Runnable deleteDomStorageRunnable = () -> {
1261 // Get a handle for the runtime.
1262 Runtime runtime = Runtime.getRuntime();
1264 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1265 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1266 String privateDataDirectoryString = getApplicationInfo().dataDir;
1268 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1269 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1271 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1272 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1273 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1274 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1275 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1277 // Wait for the processes to finish.
1278 deleteLocalStorageProcess.waitFor();
1279 deleteIndexProcess.waitFor();
1280 deleteQuotaManagerProcess.waitFor();
1281 deleteQuotaManagerJournalProcess.waitFor();
1282 deleteDatabasesProcess.waitFor();
1283 } catch (Exception exception) {
1284 // Do nothing if an error is thrown.
1288 // Manually delete the DOM storage files after 200 milliseconds.
1289 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1295 // Consume the event.
1298 // Form data can be remove once the minimum API >= 26.
1299 case R.id.clear_form_data:
1300 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1301 .setAction(R.string.undo, v -> {
1302 // Do nothing because everything will be handled by `onDismissed()` below.
1304 .addCallback(new Snackbar.Callback() {
1305 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1307 public void onDismissed(Snackbar snackbar, int event) {
1308 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1309 // Delete the form data.
1310 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1311 mainWebViewDatabase.clearFormData();
1317 // Consume the event.
1321 // Toggle the EasyList status.
1322 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1324 // Update the menu checkbox.
1325 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1327 // Reload the current WebView.
1328 currentWebView.reload();
1330 // Consume the event.
1333 case R.id.easyprivacy:
1334 // Toggle the EasyPrivacy status.
1335 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1337 // Update the menu checkbox.
1338 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1340 // Reload the current WebView.
1341 currentWebView.reload();
1343 // Consume the event.
1346 case R.id.fanboys_annoyance_list:
1347 // Toggle Fanboy's Annoyance List status.
1348 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1350 // Update the menu checkbox.
1351 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1353 // Update the staus of Fanboy's Social Blocking List.
1354 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1355 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1357 // Reload the current WebView.
1358 currentWebView.reload();
1360 // Consume the event.
1363 case R.id.fanboys_social_blocking_list:
1364 // Toggle Fanboy's Social Blocking List status.
1365 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1367 // Update the menu checkbox.
1368 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1370 // Reload the current WebView.
1371 currentWebView.reload();
1373 // Consume the event.
1376 case R.id.ultralist:
1377 // Toggle the UltraList status.
1378 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1380 // Update the menu checkbox.
1381 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1383 // Reload the current WebView.
1384 currentWebView.reload();
1386 // Consume the event.
1389 case R.id.ultraprivacy:
1390 // Toggle the UltraPrivacy status.
1391 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1393 // Update the menu checkbox.
1394 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1396 // Reload the current WebView.
1397 currentWebView.reload();
1399 // Consume the event.
1402 case R.id.block_all_third_party_requests:
1403 //Toggle the third-party requests blocker status.
1404 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1406 // Update the menu checkbox.
1407 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1409 // Reload the current WebView.
1410 currentWebView.reload();
1412 // Consume the event.
1415 case R.id.proxy_none:
1416 // Update the proxy mode.
1417 proxyMode = ProxyHelper.NONE;
1419 // Apply the proxy mode.
1422 // Consume the event.
1425 case R.id.proxy_tor:
1426 // Update the proxy mode.
1427 proxyMode = ProxyHelper.TOR;
1429 // Apply the proxy mode.
1432 // Consume the event.
1435 case R.id.proxy_i2p:
1436 // Update the proxy mode.
1437 proxyMode = ProxyHelper.I2P;
1439 // Apply the proxy mode.
1442 // Consume the event.
1445 case R.id.proxy_custom:
1446 // Update the proxy mode.
1447 proxyMode = ProxyHelper.CUSTOM;
1449 // Apply the proxy mode.
1452 // Consume the event.
1455 case R.id.user_agent_privacy_browser:
1456 // Update the user agent.
1457 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1459 // Reload the current WebView.
1460 currentWebView.reload();
1462 // Consume the event.
1465 case R.id.user_agent_webview_default:
1466 // Update the user agent.
1467 currentWebView.getSettings().setUserAgentString("");
1469 // Reload the current WebView.
1470 currentWebView.reload();
1472 // Consume the event.
1475 case R.id.user_agent_firefox_on_android:
1476 // Update the user agent.
1477 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1479 // Reload the current WebView.
1480 currentWebView.reload();
1482 // Consume the event.
1485 case R.id.user_agent_chrome_on_android:
1486 // Update the user agent.
1487 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1489 // Reload the current WebView.
1490 currentWebView.reload();
1492 // Consume the event.
1495 case R.id.user_agent_safari_on_ios:
1496 // Update the user agent.
1497 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1499 // Reload the current WebView.
1500 currentWebView.reload();
1502 // Consume the event.
1505 case R.id.user_agent_firefox_on_linux:
1506 // Update the user agent.
1507 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1509 // Reload the current WebView.
1510 currentWebView.reload();
1512 // Consume the event.
1515 case R.id.user_agent_chromium_on_linux:
1516 // Update the user agent.
1517 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1519 // Reload the current WebView.
1520 currentWebView.reload();
1522 // Consume the event.
1525 case R.id.user_agent_firefox_on_windows:
1526 // Update the user agent.
1527 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1529 // Reload the current WebView.
1530 currentWebView.reload();
1532 // Consume the event.
1535 case R.id.user_agent_chrome_on_windows:
1536 // Update the user agent.
1537 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1539 // Reload the current WebView.
1540 currentWebView.reload();
1542 // Consume the event.
1545 case R.id.user_agent_edge_on_windows:
1546 // Update the user agent.
1547 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1549 // Reload the current WebView.
1550 currentWebView.reload();
1552 // Consume the event.
1555 case R.id.user_agent_internet_explorer_on_windows:
1556 // Update the user agent.
1557 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1559 // Reload the current WebView.
1560 currentWebView.reload();
1562 // Consume the event.
1565 case R.id.user_agent_safari_on_macos:
1566 // Update the user agent.
1567 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1569 // Reload the current WebView.
1570 currentWebView.reload();
1572 // Consume the event.
1575 case R.id.user_agent_custom:
1576 // Update the user agent.
1577 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1579 // Reload the current WebView.
1580 currentWebView.reload();
1582 // Consume the event.
1585 case R.id.font_size:
1586 // Instantiate the font size dialog.
1587 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1589 // Show the font size dialog.
1590 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1592 // Consume the event.
1595 case R.id.swipe_to_refresh:
1596 // Toggle the stored status of swipe to refresh.
1597 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1599 // Get a handle for the swipe refresh layout.
1600 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1602 // Update the swipe refresh layout.
1603 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1604 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1605 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1606 } else { // Swipe to refresh is disabled.
1607 // Disable the swipe refresh layout.
1608 swipeRefreshLayout.setEnabled(false);
1611 // Consume the event.
1614 case R.id.wide_viewport:
1615 // Toggle the viewport.
1616 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1618 // Consume the event.
1621 case R.id.display_images:
1622 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1623 // Disable loading of images.
1624 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1626 // Reload the website to remove existing images.
1627 currentWebView.reload();
1628 } else { // Images are not currently loaded automatically.
1629 // Enable loading of images. Missing images will be loaded without the need for a reload.
1630 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1633 // Consume the event.
1636 case R.id.night_mode:
1637 // Toggle night mode.
1638 currentWebView.setNightMode(!currentWebView.getNightMode());
1640 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1641 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1642 // Enable JavaScript.
1643 currentWebView.getSettings().setJavaScriptEnabled(true);
1644 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1645 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1646 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1647 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1648 // Apply the JavaScript preference.
1649 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1652 // Update the privacy icons.
1653 updatePrivacyIcons(false);
1655 // Reload the website.
1656 currentWebView.reload();
1658 // Consume the event.
1661 case R.id.find_on_page:
1662 // Get a handle for the views.
1663 Toolbar toolbar = findViewById(R.id.toolbar);
1664 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1665 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1667 // Set the minimum height of the find on page linear layout to match the toolbar.
1668 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1670 // Hide the toolbar.
1671 toolbar.setVisibility(View.GONE);
1673 // Show the find on page linear layout.
1674 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1676 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1677 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1678 findOnPageEditText.postDelayed(() -> {
1679 // Set the focus on `findOnPageEditText`.
1680 findOnPageEditText.requestFocus();
1682 // Get a handle for the input method manager.
1683 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1685 // Remove the lint warning below that the input method manager might be null.
1686 assert inputMethodManager != null;
1688 // Display the keyboard. `0` sets no input flags.
1689 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1692 // Consume the event.
1696 // Get a print manager instance.
1697 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1699 // Remove the lint error below that print manager might be null.
1700 assert printManager != null;
1702 // Create a print document adapter from the current WebView.
1703 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1705 // Print the document.
1706 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1708 // Consume the event.
1712 // Instantiate the save dialog.
1713 DialogFragment saveDialogFragment = SaveWebpageDialog.saveUrl(StoragePermissionDialog.SAVE, currentWebView.getCurrentUrl());
1715 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
1716 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1718 // Consume the event.
1721 case R.id.save_as_archive:
1722 // Instantiate the save webpage archive dialog.
1723 DialogFragment saveWebpageArchiveDialogFragment = SaveWebpageDialog.saveUrl(StoragePermissionDialog.SAVE_AS_ARCHIVE, currentWebView.getCurrentUrl());
1725 // Show the save webpage archive dialog. It must be named `save_dialog` so that the file picked can update the file name.
1726 saveWebpageArchiveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1728 // Consume the event.
1731 case R.id.save_as_image:
1732 // Instantiate the save webpage image dialog. It must be named `save_webpage` so that the file picked can update the file name.
1733 DialogFragment saveWebpageImageDialogFragment = SaveWebpageDialog.saveUrl(StoragePermissionDialog.SAVE_AS_IMAGE, currentWebView.getCurrentUrl());
1735 // Show the save webpage image dialog. It must be named `save_dialog` so that the file picked can update the file name.
1736 saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1738 // Consume the event.
1741 case R.id.add_to_homescreen:
1742 // Instantiate the create home screen shortcut dialog.
1743 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1744 currentWebView.getFavoriteOrDefaultIcon());
1746 // Show the create home screen shortcut dialog.
1747 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1749 // Consume the event.
1752 case R.id.view_source:
1753 // Create an intent to launch the view source activity.
1754 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1756 // Add the variables to the intent.
1757 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1758 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1761 startActivity(viewSourceIntent);
1763 // Consume the event.
1766 case R.id.share_url:
1767 // Setup the share string.
1768 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1770 // Create the share intent.
1771 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1772 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1773 shareIntent.setType("text/plain");
1776 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1778 // Consume the event.
1781 case R.id.open_with_app:
1782 // Open the URL with an outside app.
1783 openWithApp(currentWebView.getUrl());
1785 // Consume the event.
1788 case R.id.open_with_browser:
1789 // Open the URL with an outside browser.
1790 openWithBrowser(currentWebView.getUrl());
1792 // Consume the event.
1796 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1797 // Reload the current WebView.
1798 currentWebView.reload();
1799 } else { // The stop button was pushed.
1800 // Stop the loading of the WebView.
1801 currentWebView.stopLoading();
1804 // Consume the event.
1807 case R.id.ad_consent:
1808 // Instantiate the ad consent dialog.
1809 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1811 // Display the ad consent dialog.
1812 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1814 // Consume the event.
1818 // Don't consume the event.
1819 return super.onOptionsItemSelected(menuItem);
1823 // removeAllCookies is deprecated, but it is required for API < 21.
1825 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1826 // Get the menu item ID.
1827 int menuItemId = menuItem.getItemId();
1829 // Get a handle for the shared preferences.
1830 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1832 // Run the commands that correspond to the selected menu item.
1833 switch (menuItemId) {
1834 case R.id.clear_and_exit:
1835 // Clear and exit Privacy Browser.
1840 // Load the homepage.
1841 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1845 if (currentWebView.canGoBack()) {
1846 // Get the current web back forward list.
1847 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1849 // Get the previous entry URL.
1850 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1852 // Apply the domain settings.
1853 applyDomainSettings(currentWebView, previousUrl, false, false);
1855 // Load the previous website in the history.
1856 currentWebView.goBack();
1861 if (currentWebView.canGoForward()) {
1862 // Get the current web back forward list.
1863 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1865 // Get the next entry URL.
1866 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1868 // Apply the domain settings.
1869 applyDomainSettings(currentWebView, nextUrl, false, false);
1871 // Load the next website in the history.
1872 currentWebView.goForward();
1877 // Instantiate the URL history dialog.
1878 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1880 // Show the URL history dialog.
1881 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1885 // Instantiate the open file dialog.
1886 DialogFragment openDialogFragment = new OpenDialog();
1888 // Show the open file dialog.
1889 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1893 // Populate the resource requests.
1894 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1896 // Create an intent to launch the Requests activity.
1897 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1899 // Add the block third-party requests status to the intent.
1900 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1903 startActivity(requestsIntent);
1906 case R.id.downloads:
1907 // Launch the system Download Manager.
1908 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1910 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1911 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1913 startActivity(downloadManagerIntent);
1917 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1918 reapplyDomainSettingsOnRestart = true;
1920 // Launch the domains activity.
1921 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1923 // Add the extra information to the intent.
1924 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1926 // Get the current certificate.
1927 SslCertificate sslCertificate = currentWebView.getCertificate();
1929 // Check to see if the SSL certificate is populated.
1930 if (sslCertificate != null) {
1931 // Extract the certificate to strings.
1932 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1933 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1934 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1935 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1936 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1937 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1938 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1939 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1941 // Add the certificate to the intent.
1942 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1943 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1944 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1945 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1946 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1947 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1948 domainsIntent.putExtra("ssl_start_date", startDateLong);
1949 domainsIntent.putExtra("ssl_end_date", endDateLong);
1952 // Check to see if the current IP addresses have been received.
1953 if (currentWebView.hasCurrentIpAddresses()) {
1954 // Add the current IP addresses to the intent.
1955 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1959 startActivity(domainsIntent);
1963 // Set the flag to reapply app settings on restart when returning from Settings.
1964 reapplyAppSettingsOnRestart = true;
1966 // Set the flag to reapply the domain settings on restart when returning from Settings.
1967 reapplyDomainSettingsOnRestart = true;
1969 // Launch the settings activity.
1970 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1971 startActivity(settingsIntent);
1974 case R.id.import_export:
1975 // Launch the import/export activity.
1976 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1977 startActivity(importExportIntent);
1981 // Launch the logcat activity.
1982 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1983 startActivity(logcatIntent);
1987 // Launch `GuideActivity`.
1988 Intent guideIntent = new Intent(this, GuideActivity.class);
1989 startActivity(guideIntent);
1993 // Create an intent to launch the about activity.
1994 Intent aboutIntent = new Intent(this, AboutActivity.class);
1996 // Create a string array for the blocklist versions.
1997 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],
1998 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2000 // Add the blocklist versions to the intent.
2001 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2004 startActivity(aboutIntent);
2008 // Get a handle for the drawer layout.
2009 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2011 // Close the navigation drawer.
2012 drawerLayout.closeDrawer(GravityCompat.START);
2017 public void onPostCreate(Bundle savedInstanceState) {
2018 // Run the default commands.
2019 super.onPostCreate(savedInstanceState);
2021 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2022 actionBarDrawerToggle.syncState();
2026 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2027 // Run the default commands.
2028 super.onConfigurationChanged(newConfig);
2030 // Get the status bar pixel size.
2031 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2032 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2034 // Get the resource density.
2035 float screenDensity = getResources().getDisplayMetrics().density;
2037 // Recalculate the drawer header padding.
2038 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2039 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2040 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2042 // Reload the ad for the free flavor if not in full screen mode.
2043 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2044 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2045 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2048 // `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:
2049 // https://code.google.com/p/android/issues/detail?id=20493#c8
2050 // ActivityCompat.invalidateOptionsMenu(this);
2054 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2055 // Store the hit test result.
2056 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2058 // Define the URL strings.
2059 final String imageUrl;
2060 final String linkUrl;
2062 // Get handles for the system managers.
2063 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2065 // Remove the lint errors below that the clipboard manager might be null.
2066 assert clipboardManager != null;
2068 // Process the link according to the type.
2069 switch (hitTestResult.getType()) {
2070 // `SRC_ANCHOR_TYPE` is a link.
2071 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2072 // Get the target URL.
2073 linkUrl = hitTestResult.getExtra();
2075 // Set the target URL as the title of the `ContextMenu`.
2076 menu.setHeaderTitle(linkUrl);
2078 // Add an Open in New Tab entry.
2079 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2080 // Load the link URL in a new tab and move to it.
2081 addNewTab(linkUrl, true);
2083 // Consume the event.
2087 // Add an Open in Background entry.
2088 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2089 // Load the link URL in a new tab but do not move to it.
2090 addNewTab(linkUrl, false);
2092 // Consume the event.
2096 // Add an Open with App entry.
2097 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2098 openWithApp(linkUrl);
2100 // Consume the event.
2104 // Add an Open with Browser entry.
2105 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2106 openWithBrowser(linkUrl);
2108 // Consume the event.
2112 // Add a Copy URL entry.
2113 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2114 // Save the link URL in a `ClipData`.
2115 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2117 // Set the `ClipData` as the clipboard's primary clip.
2118 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2120 // Consume the event.
2124 // Add a Save URL entry.
2125 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2126 // Instantiate the save dialog.
2127 DialogFragment saveDialogFragment = SaveWebpageDialog.saveUrl(StoragePermissionDialog.SAVE, linkUrl);
2129 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
2130 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2132 // Consume the event.
2136 // Add a Cancel entry, which by default closes the context menu.
2137 menu.add(R.string.cancel);
2140 case WebView.HitTestResult.EMAIL_TYPE:
2141 // Get the target URL.
2142 linkUrl = hitTestResult.getExtra();
2144 // Set the target URL as the title of the `ContextMenu`.
2145 menu.setHeaderTitle(linkUrl);
2147 // Add a Write Email entry.
2148 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2149 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2150 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2152 // Parse the url and set it as the data for the `Intent`.
2153 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2155 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2156 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2159 startActivity(emailIntent);
2161 // Consume the event.
2165 // Add a Copy Email Address entry.
2166 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2167 // Save the email address in a `ClipData`.
2168 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2170 // Set the `ClipData` as the clipboard's primary clip.
2171 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2173 // Consume the event.
2177 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2178 menu.add(R.string.cancel);
2181 // `IMAGE_TYPE` is an image.
2182 case WebView.HitTestResult.IMAGE_TYPE:
2183 // Get the image URL.
2184 imageUrl = hitTestResult.getExtra();
2186 // Set the image URL as the title of the context menu.
2187 menu.setHeaderTitle(imageUrl);
2189 // Add an Open in New Tab entry.
2190 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2191 // Load the image in a new tab.
2192 addNewTab(imageUrl, true);
2194 // Consume the event.
2198 // Add a View Image entry.
2199 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2200 // Load the image in the current tab.
2201 loadUrl(currentWebView, imageUrl);
2203 // Consume the event.
2207 // Add a Save Image entry.
2208 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2209 // Instantiate the save dialog.
2210 DialogFragment saveDialogFragment = SaveWebpageDialog.saveUrl(StoragePermissionDialog.SAVE, imageUrl);
2212 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
2213 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2215 // Consume the event.
2219 // Add a Copy URL entry.
2220 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2221 // Save the image URL in a clip data.
2222 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2224 // Set the clip data as the clipboard's primary clip.
2225 clipboardManager.setPrimaryClip(imageTypeClipData);
2227 // Consume the event.
2231 // Add an Open with App entry.
2232 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2233 // Open the image URL with an external app.
2234 openWithApp(imageUrl);
2236 // Consume the event.
2240 // Add an Open with Browser entry.
2241 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2242 // Open the image URL with an external browser.
2243 openWithBrowser(imageUrl);
2245 // Consume the event.
2249 // Add a Cancel entry, which by default closes the context menu.
2250 menu.add(R.string.cancel);
2253 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2254 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2255 // Get the image URL.
2256 imageUrl = hitTestResult.getExtra();
2258 // Instantiate a handler.
2259 Handler handler = new Handler();
2261 // Get a message from the handler.
2262 Message message = handler.obtainMessage();
2264 // Request the image details from the last touched node be returned in the message.
2265 currentWebView.requestFocusNodeHref(message);
2267 // Get the link URL from the message data.
2268 linkUrl = message.getData().getString("url");
2270 // Set the link URL as the title of the context menu.
2271 menu.setHeaderTitle(linkUrl);
2273 // Add an Open in New Tab entry.
2274 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2275 // Load the link URL in a new tab and move to it.
2276 addNewTab(linkUrl, true);
2278 // Consume the event.
2282 // Add an Open in Background entry.
2283 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2284 // Lod the link URL in a new tab but do not move to it.
2285 addNewTab(linkUrl, false);
2287 // Consume the event.
2291 // Add an Open Image in New Tab entry.
2292 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2293 // Load the image in a new tab and move to it.
2294 addNewTab(imageUrl, true);
2296 // Consume the event.
2300 // Add a View Image entry.
2301 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2302 // View the image in the current tab.
2303 loadUrl(currentWebView, imageUrl);
2305 // Consume the event.
2309 // Add a Copy URL entry.
2310 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2311 // Save the link URL in a clip data.
2312 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2314 // Set the clip data as the clipboard's primary clip.
2315 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2317 // Consume the event.
2321 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2322 // Instantiate the save dialog.
2323 DialogFragment saveDialogFragment = SaveWebpageDialog.saveUrl(StoragePermissionDialog.SAVE, imageUrl);
2325 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2326 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2328 // Consume the event.
2332 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2333 // Instantiate the save dialog.
2334 DialogFragment saveDialogFragment = SaveWebpageDialog.saveUrl(StoragePermissionDialog.SAVE, linkUrl);
2336 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2337 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2339 // Consume the event.
2343 // Add an Open with App entry.
2344 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2345 // Open the link URL with an external app.
2346 openWithApp(linkUrl);
2348 // Consume the event.
2352 // Add an Open with Browser entry.
2353 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2354 // Open the link URL with an external browser.
2355 openWithBrowser(linkUrl);
2357 // Consume the event.
2361 // Add a cancel entry, which by default closes the context menu.
2362 menu.add(R.string.cancel);
2368 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2369 // Get a handle for the bookmarks list view.
2370 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2373 Dialog dialog = dialogFragment.getDialog();
2375 // Remove the incorrect lint warning below that the dialog might be null.
2376 assert dialog != null;
2378 // Get the views from the dialog fragment.
2379 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2380 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2382 // Extract the strings from the edit texts.
2383 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2384 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2386 // Create a favorite icon byte array output stream.
2387 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2389 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2390 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2392 // Convert the favorite icon byte array stream to a byte array.
2393 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2395 // Display the new bookmark below the current items in the (0 indexed) list.
2396 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2398 // Create the bookmark.
2399 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2401 // Update the bookmarks cursor with the current contents of this folder.
2402 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2404 // Update the list view.
2405 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2407 // Scroll to the new bookmark.
2408 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2412 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2413 // Get a handle for the bookmarks list view.
2414 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2417 Dialog dialog = dialogFragment.getDialog();
2419 // Remove the incorrect lint warning below that the dialog might be null.
2420 assert dialog != null;
2422 // Get handles for the views in the dialog fragment.
2423 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2424 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2425 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2427 // Get new folder name string.
2428 String folderNameString = createFolderNameEditText.getText().toString();
2430 // Create a folder icon bitmap.
2431 Bitmap folderIconBitmap;
2433 // Set the folder icon bitmap according to the dialog.
2434 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2435 // Get the default folder icon drawable.
2436 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2438 // Convert the folder icon drawable to a bitmap drawable.
2439 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2441 // Convert the folder icon bitmap drawable to a bitmap.
2442 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2443 } else { // Use the WebView favorite icon.
2444 // Copy the favorite icon bitmap to the folder icon bitmap.
2445 folderIconBitmap = favoriteIconBitmap;
2448 // Create a folder icon byte array output stream.
2449 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2451 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2452 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2454 // Convert the folder icon byte array stream to a byte array.
2455 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2457 // Move all the bookmarks down one in the display order.
2458 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2459 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2460 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2463 // Create the folder, which will be placed at the top of the `ListView`.
2464 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2466 // Update the bookmarks cursor with the current contents of this folder.
2467 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2469 // Update the `ListView`.
2470 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2472 // Scroll to the new folder.
2473 bookmarksListView.setSelection(0);
2477 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2479 Dialog dialog = dialogFragment.getDialog();
2481 // Remove the incorrect lint warning below that the dialog might be null.
2482 assert dialog != null;
2484 // Get handles for the views from the dialog.
2485 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
2486 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
2487 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2489 // Store the bookmark strings.
2490 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2491 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2493 // Update the bookmark.
2494 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2495 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2496 } else { // Update the bookmark using the `WebView` favorite icon.
2497 // Create a favorite icon byte array output stream.
2498 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2500 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2501 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2503 // Convert the favorite icon byte array stream to a byte array.
2504 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2506 // Update the bookmark and the favorite icon.
2507 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2510 // Update the bookmarks cursor with the current contents of this folder.
2511 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2513 // Update the list view.
2514 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2518 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2520 Dialog dialog = dialogFragment.getDialog();
2522 // Remove the incorrect lint warning below that the dialog might be null.
2523 assert dialog != null;
2525 // Get handles for the views from `dialogFragment`.
2526 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2527 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2528 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2529 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2531 // Get the new folder name.
2532 String newFolderNameString = editFolderNameEditText.getText().toString();
2534 // Check if the favorite icon has changed.
2535 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2536 // Update the name in the database.
2537 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2538 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2539 // Create the new folder icon Bitmap.
2540 Bitmap folderIconBitmap;
2542 // Populate the new folder icon bitmap.
2543 if (defaultFolderIconRadioButton.isChecked()) {
2544 // Get the default folder icon drawable.
2545 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2547 // Convert the folder icon drawable to a bitmap drawable.
2548 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2550 // Convert the folder icon bitmap drawable to a bitmap.
2551 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2552 } else { // Use the `WebView` favorite icon.
2553 // Copy the favorite icon bitmap to the folder icon bitmap.
2554 folderIconBitmap = favoriteIconBitmap;
2557 // Create a folder icon byte array output stream.
2558 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2560 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2561 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2563 // Convert the folder icon byte array stream to a byte array.
2564 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2566 // Update the folder icon in the database.
2567 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2568 } else { // The folder icon and the name have changed.
2569 // Get the new folder icon `Bitmap`.
2570 Bitmap folderIconBitmap;
2571 if (defaultFolderIconRadioButton.isChecked()) {
2572 // Get the default folder icon drawable.
2573 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2575 // Convert the folder icon drawable to a bitmap drawable.
2576 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2578 // Convert the folder icon bitmap drawable to a bitmap.
2579 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2580 } else { // Use the `WebView` favorite icon.
2581 // Copy the favorite icon bitmap to the folder icon bitmap.
2582 folderIconBitmap = favoriteIconBitmap;
2585 // Create a folder icon byte array output stream.
2586 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2588 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2589 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2591 // Convert the folder icon byte array stream to a byte array.
2592 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2594 // Update the folder name and icon in the database.
2595 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2598 // Update the bookmarks cursor with the current contents of this folder.
2599 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2601 // Update the `ListView`.
2602 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2606 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2607 switch (downloadType) {
2608 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2609 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2610 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_DOWNLOAD_FILE_REQUEST_CODE);
2613 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2614 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2615 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_DOWNLOAD_IMAGE_REQUEST_CODE);
2621 public void onDownloadImage(DialogFragment dialogFragment, String imageUrl) {
2622 // Download the image if it has an HTTP or HTTPS URI.
2623 if (imageUrl.startsWith("http")) {
2624 // Get a handle for the system `DOWNLOAD_SERVICE`.
2625 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2627 // Parse `imageUrl`.
2628 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2630 // Get a handle for the cookie manager.
2631 CookieManager cookieManager = CookieManager.getInstance();
2633 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2634 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2635 if (cookieManager.acceptCookie()) {
2636 // Get the cookies for `imageUrl`.
2637 String cookies = cookieManager.getCookie(imageUrl);
2639 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2640 downloadRequest.addRequestHeader("Cookie", cookies);
2644 Dialog dialog = dialogFragment.getDialog();
2646 // Remove the incorrect lint warning below that the dialog might be null.
2647 assert dialog != null;
2649 // Get the file name from the dialog fragment.
2650 EditText downloadImageNameEditText = dialog.findViewById(R.id.download_image_name);
2651 String imageName = downloadImageNameEditText.getText().toString();
2653 // Specify the download location.
2654 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2655 // Download to the public download directory.
2656 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2657 } else { // External write permission denied.
2658 // Download to the app's external download directory.
2659 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2662 // Allow `MediaScanner` to index the download if it is a media file.
2663 downloadRequest.allowScanning