2 * Copyright © 2015-2019 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.text.Editable;
56 import android.text.Spanned;
57 import android.text.TextWatcher;
58 import android.text.style.ForegroundColorSpan;
59 import android.util.Patterns;
60 import android.view.ContextMenu;
61 import android.view.GestureDetector;
62 import android.view.KeyEvent;
63 import android.view.Menu;
64 import android.view.MenuItem;
65 import android.view.MotionEvent;
66 import android.view.View;
67 import android.view.ViewGroup;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.HttpAuthHandler;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.ValueCallback;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebSettings;
77 import android.webkit.WebStorage;
78 import android.webkit.WebView;
79 import android.webkit.WebViewClient;
80 import android.webkit.WebViewDatabase;
81 import android.widget.ArrayAdapter;
82 import android.widget.CursorAdapter;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ListView;
88 import android.widget.ProgressBar;
89 import android.widget.RadioButton;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
93 import androidx.annotation.NonNull;
94 import androidx.appcompat.app.ActionBar;
95 import androidx.appcompat.app.ActionBarDrawerToggle;
96 import androidx.appcompat.app.AppCompatActivity;
97 import androidx.appcompat.widget.Toolbar;
98 import androidx.core.app.ActivityCompat;
99 import androidx.core.content.ContextCompat;
100 import androidx.core.view.GravityCompat;
101 import androidx.drawerlayout.widget.DrawerLayout;
102 import androidx.fragment.app.DialogFragment;
103 import androidx.fragment.app.FragmentManager;
104 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
105 import androidx.viewpager.widget.ViewPager;
107 import com.google.android.material.floatingactionbutton.FloatingActionButton;
108 import com.google.android.material.navigation.NavigationView;
109 import com.google.android.material.snackbar.Snackbar;
110 import com.google.android.material.tabs.TabLayout;
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
115 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
116 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
118 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
120 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
121 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
123 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
124 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
125 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
126 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
127 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
128 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
129 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
130 import com.stoutner.privacybrowser.helpers.AdHelper;
131 import com.stoutner.privacybrowser.helpers.BlockListHelper;
132 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
133 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
134 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
135 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
136 import com.stoutner.privacybrowser.views.NestedScrollWebView;
138 import java.io.ByteArrayInputStream;
139 import java.io.ByteArrayOutputStream;
141 import java.io.IOException;
142 import java.io.UnsupportedEncodingException;
143 import java.net.MalformedURLException;
145 import java.net.URLDecoder;
146 import java.net.URLEncoder;
147 import java.util.ArrayList;
148 import java.util.Date;
149 import java.util.HashMap;
150 import java.util.HashSet;
151 import java.util.List;
152 import java.util.Map;
153 import java.util.Set;
155 // TODO. New tabs are white in dark mode.
157 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
158 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
159 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
160 EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener {
162 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
163 public static String orbotStatus;
165 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
166 public static WebViewPagerAdapter webViewPagerAdapter;
168 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
169 public static boolean loadUrlOnRestart;
170 public static String urlToLoadOnRestart;
172 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
173 public static boolean restartFromBookmarksActivity;
175 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
176 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
177 public static String currentBookmarksFolder;
179 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
180 public final static int UNRECOGNIZED_USER_AGENT = -1;
181 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
182 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
183 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
184 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
185 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
189 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
190 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
191 private NestedScrollWebView currentWebView;
193 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
194 private final Map<String, String> customHeaders = new HashMap<>();
196 // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
197 private String searchURL;
199 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
200 private Menu optionsMenu;
202 // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
203 private ArrayList<List<String[]>> easyList;
204 private ArrayList<List<String[]>> easyPrivacy;
205 private ArrayList<List<String[]>> fanboysAnnoyanceList;
206 private ArrayList<List<String[]>> fanboysSocialList;
207 private ArrayList<List<String[]>> ultraPrivacy;
209 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
210 private String webViewDefaultUserAgent;
212 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
213 private boolean proxyThroughOrbot;
215 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
216 private boolean incognitoModeEnabled;
218 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
219 private boolean fullScreenBrowsingModeEnabled;
221 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
222 private boolean inFullScreenBrowsingMode;
224 // The hide app bar tracker is used in `applyAppSettings()` and `initializeWebView()`.
225 private boolean hideAppBar;
227 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
228 private boolean reapplyDomainSettingsOnRestart;
230 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
231 private boolean reapplyAppSettingsOnRestart;
233 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
234 private boolean displayingFullScreenVideo;
236 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
237 private BroadcastReceiver orbotStatusBroadcastReceiver;
239 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
240 private boolean waitingForOrbot;
242 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
243 private ActionBarDrawerToggle actionBarDrawerToggle;
245 // The color spans are used in `onCreate()` and `highlightUrlText()`.
246 private ForegroundColorSpan redColorSpan;
247 private ForegroundColorSpan initialGrayColorSpan;
248 private ForegroundColorSpan finalGrayColorSpan;
250 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
251 private int drawerHeaderPaddingLeftAndRight;
252 private int drawerHeaderPaddingTop;
253 private int drawerHeaderPaddingBottom;
255 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
256 // and `loadBookmarksFolder()`.
257 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
259 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
260 private Cursor bookmarksCursor;
262 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
263 private CursorAdapter bookmarksCursorAdapter;
265 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
266 private String oldFolderNameString;
268 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
269 private ValueCallback<Uri[]> fileChooserCallback;
271 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
272 private String downloadUrl;
273 private String downloadContentDisposition;
274 private long downloadContentLength;
276 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
277 private String downloadImageUrl;
279 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
280 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
281 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
284 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
285 @SuppressLint("ClickableViewAccessibility")
286 protected void onCreate(Bundle savedInstanceState) {
287 // Get a handle for the shared preferences.
288 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
290 // Get the theme and screenshot preferences.
291 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
292 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
294 // Disable screenshots if not allowed.
295 if (!allowScreenshots) {
296 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
299 // Set the activity theme.
301 setTheme(R.style.PrivacyBrowserDark);
303 setTheme(R.style.PrivacyBrowserLight);
306 // Run the default commands.
307 super.onCreate(savedInstanceState);
309 // Set the content view.
310 setContentView(R.layout.main_framelayout);
312 // Get a handle for the input method.
313 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
315 // Remove the lint warning below that the input method manager might be null.
316 assert inputMethodManager != null;
318 // Get a handle for the toolbar.
319 Toolbar toolbar = findViewById(R.id.toolbar);
321 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
322 setSupportActionBar(toolbar);
324 // Get a handle for the action bar.
325 ActionBar actionBar = getSupportActionBar();
327 // This is needed to get rid of the Android Studio warning that the action bar might be null.
328 assert actionBar != null;
330 // Add the custom layout, which shows the URL text bar.
331 actionBar.setCustomView(R.layout.url_app_bar);
332 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
334 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
335 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
336 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
337 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
339 // Get handles for the URL views.
340 EditText urlEditText = findViewById(R.id.url_edittext);
342 // Remove the formatting from `urlTextBar` when the user is editing the text.
343 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
344 if (hasFocus) { // The user is editing the URL text box.
345 // Remove the highlighting.
346 urlEditText.getText().removeSpan(redColorSpan);
347 urlEditText.getText().removeSpan(initialGrayColorSpan);
348 urlEditText.getText().removeSpan(finalGrayColorSpan);
349 } else { // The user has stopped editing the URL text box.
350 // Move to the beginning of the string.
351 urlEditText.setSelection(0);
353 // Reapply the highlighting.
358 // Set the go button on the keyboard to load the URL in `urlTextBox`.
359 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
360 // If the event is a key-down event on the `enter` button, load the URL.
361 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
362 // Load the URL into the mainWebView and consume the event.
363 loadUrlFromTextBox();
365 // If the enter key was pressed, consume the event.
368 // If any other key was pressed, do not consume the event.
373 // Initialize the Orbot status and the waiting for Orbot trackers.
374 orbotStatus = "unknown";
375 waitingForOrbot = false;
377 // Create an Orbot status `BroadcastReceiver`.
378 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
380 public void onReceive(Context context, Intent intent) {
381 // Store the content of the status message in `orbotStatus`.
382 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
384 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
385 if (orbotStatus.equals("ON") && waitingForOrbot) {
386 // Reset the waiting for Orbot status.
387 waitingForOrbot = false;
389 // Get the intent that started the app.
390 Intent launchingIntent = getIntent();
392 // Get the information from the intent.
393 String launchingIntentAction = launchingIntent.getAction();
394 Uri launchingIntentUriData = launchingIntent.getData();
396 // If the intent action is a web search, perform the search.
397 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
398 // Create an encoded URL string.
399 String encodedUrlString;
401 // Sanitize the search input and convert it to a search.
403 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
404 } catch (UnsupportedEncodingException exception) {
405 encodedUrlString = "";
408 // Load the completed search URL.
409 loadUrl(searchURL + encodedUrlString);
410 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
411 // Load the URL from the intent.
412 loadUrl(launchingIntentUriData.toString());
413 } else { // The is no URL in the intent.
414 // Select the homepage based on the proxy through Orbot status.
415 if (proxyThroughOrbot) {
416 // Load the Tor homepage.
417 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
419 // Load the normal homepage.
420 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
427 // Register `orbotStatusBroadcastReceiver` on `this` context.
428 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
430 // Instantiate the blocklist helper.
431 BlockListHelper blockListHelper = new BlockListHelper();
433 // Parse the block lists.
434 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
435 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
436 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
437 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
438 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
440 // Get handles for views that need to be modified.
441 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
442 NavigationView navigationView = findViewById(R.id.navigationview);
443 TabLayout tabLayout = findViewById(R.id.tablayout);
444 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
445 ViewPager webViewPager = findViewById(R.id.webviewpager);
446 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
447 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
448 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
449 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
450 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
452 // Listen for touches on the navigation menu.
453 navigationView.setNavigationItemSelectedListener(this);
455 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
456 Menu navigationMenu = navigationView.getMenu();
457 MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
458 MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
459 MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
460 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
461 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
463 // Initialize the web view pager adapter.
464 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
466 // Set the pager adapter on the web view pager.
467 webViewPager.setAdapter(webViewPagerAdapter);
469 // Store up to 100 tabs in memory.
470 webViewPager.setOffscreenPageLimit(100);
472 // Update the web view pager every time a tab is modified.
473 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
475 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
480 public void onPageSelected(int position) {
481 // Close the find on page bar if it is open.
482 closeFindOnPage(null);
484 // Set the current WebView.
485 setCurrentWebView(position);
487 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled via swiping in the view pager or by creating a new tab.
488 if (tabLayout.getSelectedTabPosition() != position) {
489 // Create a handler to select the tab.
490 Handler selectTabHandler = new Handler();
492 // Create a runnable select the new tab.
493 Runnable selectTabRunnable = () -> {
494 // Get a handle for the tab.
495 TabLayout.Tab tab = tabLayout.getTabAt(position);
497 // Assert that the tab is not null.
504 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
505 selectTabHandler.postDelayed(selectTabRunnable, 100);
510 public void onPageScrollStateChanged(int state) {
515 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
516 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
518 public void onTabSelected(TabLayout.Tab tab) {
519 // Select the same page in the view pager.
520 webViewPager.setCurrentItem(tab.getPosition());
524 public void onTabUnselected(TabLayout.Tab tab) {
529 public void onTabReselected(TabLayout.Tab tab) {
530 // Instantiate the View SSL Certificate dialog.
531 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
533 // Display the View SSL Certificate dialog.
534 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
538 // Add the first tab.
541 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
542 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
544 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
545 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
546 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
547 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
549 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
550 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
551 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
552 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
555 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
556 launchBookmarksActivityFab.setOnClickListener(v -> {
557 // Get a copy of the favorite icon bitmap.
558 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
560 // Create a favorite icon byte array output stream.
561 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
563 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
564 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
566 // Convert the favorite icon byte array stream to a byte array.
567 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
569 // Create an intent to launch the bookmarks activity.
570 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
572 // Add the extra information to the intent.
573 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
574 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
575 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
576 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
579 startActivity(bookmarksIntent);
582 // Set the create new bookmark folder FAB to display an alert dialog.
583 createBookmarkFolderFab.setOnClickListener(v -> {
584 // Create a create bookmark folder dialog.
585 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
587 // Show the create bookmark folder dialog.
588 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
591 // Set the create new bookmark FAB to display an alert dialog.
592 createBookmarkFab.setOnClickListener(view -> {
593 // Instantiate the create bookmark dialog.
594 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
596 // Display the create bookmark dialog.
597 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
600 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
601 findOnPageEditText.addTextChangedListener(new TextWatcher() {
603 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
608 public void onTextChanged(CharSequence s, int start, int before, int count) {
613 public void afterTextChanged(Editable s) {
614 // Search for the text in `mainWebView`.
615 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
619 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
620 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
621 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
622 // Hide the soft keyboard.
623 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
625 // Consume the event.
627 } else { // A different key was pressed.
628 // Do not consume the event.
633 // Implement swipe to refresh.
634 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
636 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
637 swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
639 // Set the swipe to refresh color according to the theme.
641 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
642 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
644 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
647 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
648 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
649 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
651 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
652 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
654 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
655 currentBookmarksFolder = "";
657 // Load the home folder, which is `""` in the database.
658 loadBookmarksFolder();
660 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
661 // Convert the id from long to int to match the format of the bookmarks database.
662 int databaseID = (int) id;
664 // Get the bookmark cursor for this ID and move it to the first row.
665 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
666 bookmarkCursor.moveToFirst();
668 // Act upon the bookmark according to the type.
669 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
670 // Store the new folder name in `currentBookmarksFolder`.
671 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
673 // Load the new folder.
674 loadBookmarksFolder();
675 } else { // The selected bookmark is not a folder.
676 // Load the bookmark URL.
677 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
679 // Close the bookmarks drawer.
680 drawerLayout.closeDrawer(GravityCompat.END);
683 // Close the `Cursor`.
684 bookmarkCursor.close();
687 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
688 // Convert the database ID from `long` to `int`.
689 int databaseId = (int) id;
691 // Find out if the selected bookmark is a folder.
692 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
695 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
696 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
698 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
699 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
700 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
702 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
703 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
704 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
707 // Consume the event.
711 // Get the status bar pixel size.
712 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
713 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
715 // Get the resource density.
716 float screenDensity = getResources().getDisplayMetrics().density;
718 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
719 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
720 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
721 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
723 // The drawer listener is used to update the navigation menu.`
724 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
726 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
730 public void onDrawerOpened(@NonNull View drawerView) {
734 public void onDrawerClosed(@NonNull View drawerView) {
738 public void onDrawerStateChanged(int newState) {
739 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
740 // Get handles for the drawer headers.
741 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
742 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
744 // Apply the navigation header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
745 if (navigationHeaderTextView != null) {
746 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
749 // Apply the bookmarks header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
750 if (bookmarksHeaderTextView != null) {
751 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
754 // Update the navigation menu items.
755 navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
756 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
757 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
758 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
759 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
761 // Hide the keyboard (if displayed).
762 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
764 // Clear the focus from from the URL text box and the WebView. This removes any text selection markers and context menus, which otherwise draw above the open drawers.
765 urlEditText.clearFocus();
766 currentWebView.clearFocus();
771 // Create the hamburger icon at the start of the AppBar.
772 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
774 // Replace the header that `WebView` creates for `X-Requested-With` with a null value. The default value is the application ID (com.stoutner.privacybrowser.standard).
775 customHeaders.put("X-Requested-With", "");
777 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
778 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
780 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
781 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
783 // Get a handle for the WebView.
784 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
786 // Store the default user agent.
787 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
789 // Destroy the bare WebView.
790 bareWebView.destroy();
794 protected void onNewIntent(Intent intent) {
795 // Get the information from the intent.
796 String intentAction = intent.getAction();
797 Uri intentUriData = intent.getData();
799 // Only process the URI if it contains data. If the user pressed the desktop icon after the app was already running the URI will be null.
800 if (intentUriData != null) {
801 // Sets the new intent as the activity intent, which replaces the one that originally started the app.
807 // Create a URL string.
810 // If the intent action is a web search, perform the search.
811 if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
812 // Create an encoded URL string.
813 String encodedUrlString;
815 // Sanitize the search input and convert it to a search.
817 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
818 } catch (UnsupportedEncodingException exception) {
819 encodedUrlString = "";
822 // Add the base search URL.
823 url = searchURL + encodedUrlString;
824 } else { // The intent should contain a URL.
825 // Set the intent data as the URL.
826 url = intentUriData.toString();
832 // Get a handle for the drawer layout.
833 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
835 // Close the navigation drawer if it is open.
836 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
837 drawerLayout.closeDrawer(GravityCompat.START);
840 // Close the bookmarks drawer if it is open.
841 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
842 drawerLayout.closeDrawer(GravityCompat.END);
845 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
846 currentWebView.requestFocus();
851 public void onRestart() {
852 // Run the default commands.
855 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
856 if (proxyThroughOrbot) {
857 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
858 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
860 // Send the intent to the Orbot package.
861 orbotIntent.setPackage("org.torproject.android");
864 sendBroadcast(orbotIntent);
867 // Apply the app settings if returning from the Settings activity.
868 if (reapplyAppSettingsOnRestart) {
869 // Reset the reapply app settings on restart tracker.
870 reapplyAppSettingsOnRestart = false;
872 // Apply the app settings.
876 // Apply the domain settings if returning from the settings or domains activity.
877 if (reapplyDomainSettingsOnRestart) {
878 // Reset the reapply domain settings on restart tracker.
879 reapplyDomainSettingsOnRestart = false;
881 // Reapply the domain settings for each tab.
882 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
883 // Get the WebView tab fragment.
884 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
886 // Get the fragment view.
887 View fragmentView = webViewTabFragment.getView();
889 // Only reload the WebViews if they exist.
890 if (fragmentView != null) {
891 // Get the nested scroll WebView from the tab fragment.
892 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
894 // Reset the current domain name so the domain settings will be reapplied.
895 nestedScrollWebView.resetCurrentDomainName();
897 // Reapply the domain settings.
898 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
903 // Load the URL on restart (used when loading a bookmark).
904 if (loadUrlOnRestart) {
905 // Load the specified URL.
906 loadUrl(urlToLoadOnRestart);
908 // Reset the load on restart tracker.
909 loadUrlOnRestart = false;
912 // Update the bookmarks drawer if returning from the Bookmarks activity.
913 if (restartFromBookmarksActivity) {
914 // Get a handle for the drawer layout.
915 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
917 // Close the bookmarks drawer.
918 drawerLayout.closeDrawer(GravityCompat.END);
920 // Reload the bookmarks drawer.
921 loadBookmarksFolder();
923 // Reset `restartFromBookmarksActivity`.
924 restartFromBookmarksActivity = false;
927 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
928 updatePrivacyIcons(true);
931 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
933 public void onResume() {
934 // Run the default commands.
937 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
938 // Get the WebView tab fragment.
939 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
941 // Get the fragment view.
942 View fragmentView = webViewTabFragment.getView();
944 // Only resume the WebViews if they exist (they won't when the app is first created).
945 if (fragmentView != null) {
946 // Get the nested scroll WebView from the tab fragment.
947 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
949 // Resume the nested scroll WebView JavaScript timers.
950 nestedScrollWebView.resumeTimers();
952 // Resume the nested scroll WebView.
953 nestedScrollWebView.onResume();
957 // Display a message to the user if waiting for Orbot.
958 if (waitingForOrbot && !orbotStatus.equals("ON")) {
959 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
960 currentWebView.getSettings().setUseWideViewPort(false);
962 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
963 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
966 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
967 // Get a handle for the root frame layouts.
968 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
970 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
971 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
973 /* Hide the system bars.
974 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
975 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
976 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
977 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
979 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
980 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
981 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
983 AdHelper.resumeAd(findViewById(R.id.adview));
988 public void onPause() {
989 // Run the default commands.
992 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
993 // Get the WebView tab fragment.
994 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
996 // Get the fragment view.
997 View fragmentView = webViewTabFragment.getView();
999 // Only pause the WebViews if they exist (they won't when the app is first created).
1000 if (fragmentView != null) {
1001 // Get the nested scroll WebView from the tab fragment.
1002 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1004 // Pause the nested scroll WebView.
1005 nestedScrollWebView.onPause();
1007 // Pause the nested scroll WebView JavaScript timers.
1008 nestedScrollWebView.pauseTimers();
1012 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1013 if (BuildConfig.FLAVOR.contentEquals("free")) {
1015 AdHelper.pauseAd(findViewById(R.id.adview));
1020 public void onDestroy() {
1021 // Unregister the Orbot status broadcast receiver.
1022 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1024 // Close the bookmarks cursor and database.
1025 bookmarksCursor.close();
1026 bookmarksDatabaseHelper.close();
1028 // Run the default commands.
1033 public boolean onCreateOptionsMenu(Menu menu) {
1034 // Inflate the menu. This adds items to the action bar if it is present.
1035 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1037 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1040 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1041 updatePrivacyIcons(false);
1043 // Get handles for the menu items.
1044 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1045 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1046 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1047 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1048 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1049 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1050 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1052 // Only display third-party cookies if API >= 21
1053 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1055 // Only display the form data menu items if the API < 26.
1056 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1057 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1059 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1060 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1062 // Only show Ad Consent if this is the free flavor.
1063 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1065 // Get the shared preference values.
1066 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1068 // Get the dark theme and app bar preferences..
1069 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1070 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1072 // 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.
1073 if (displayAdditionalAppBarIcons) {
1074 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1075 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1076 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1077 } else { //Do not display the additional icons.
1078 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1079 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1080 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1083 // Replace Refresh with Stop if a URL is already loading.
1084 if (currentWebView != null && currentWebView.getProgress() != 100) {
1086 refreshMenuItem.setTitle(R.string.stop);
1088 // If the icon is displayed in the AppBar, set it according to the theme.
1089 if (displayAdditionalAppBarIcons) {
1091 refreshMenuItem.setIcon(R.drawable.close_dark);
1093 refreshMenuItem.setIcon(R.drawable.close_light);
1102 public boolean onPrepareOptionsMenu(Menu menu) {
1103 // Get handles for the menu items.
1104 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1105 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1106 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1107 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1108 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1109 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1110 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1111 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1112 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1113 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1114 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1115 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1116 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1117 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1118 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1119 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1120 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1121 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1122 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1123 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1124 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1126 // Get a handle for the cookie manager.
1127 CookieManager cookieManager = CookieManager.getInstance();
1129 // Initialize the current user agent string and the font size.
1130 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1133 // 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.
1134 if (currentWebView != null) {
1135 // Set the add or edit domain text.
1136 if (currentWebView.getDomainSettingsApplied()) {
1137 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1139 addOrEditDomain.setTitle(R.string.add_domain_settings);
1142 // Get the current user agent from the WebView.
1143 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1145 // Get the current font size from the
1146 fontSize = currentWebView.getSettings().getTextZoom();
1148 // Set the status of the menu item checkboxes.
1149 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1150 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1151 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1152 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1153 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1154 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1155 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1156 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1157 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1158 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1159 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1161 // Initialize the display names for the blocklists with the number of blocked requests.
1162 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1163 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1164 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1165 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1166 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1167 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1168 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1170 // Only modify third-party cookies if the API >= 21.
1171 if (Build.VERSION.SDK_INT >= 21) {
1172 // Set the status of the third-party cookies checkbox.
1173 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1175 // Enable third-party cookies if first-party cookies are enabled.
1176 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1179 // Enable DOM Storage if JavaScript is enabled.
1180 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1183 // Set the status of the menu item checkboxes.
1184 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1185 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1187 // Enable Clear Cookies if there are any.
1188 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1190 // 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`.
1191 String privateDataDirectoryString = getApplicationInfo().dataDir;
1193 // Get a count of the number of files in the Local Storage directory.
1194 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1195 int localStorageDirectoryNumberOfFiles = 0;
1196 if (localStorageDirectory.exists()) {
1197 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1200 // Get a count of the number of files in the IndexedDB directory.
1201 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1202 int indexedDBDirectoryNumberOfFiles = 0;
1203 if (indexedDBDirectory.exists()) {
1204 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1207 // Enable Clear DOM Storage if there is any.
1208 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1210 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1211 if (Build.VERSION.SDK_INT < 26) {
1212 // Get the WebView database.
1213 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1215 // Enable the clear form data menu item if there is anything to clear.
1216 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1219 // Enable Clear Data if any of the submenu items are enabled.
1220 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1222 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1223 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1225 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1226 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1227 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1228 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1229 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1230 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1231 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1232 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1233 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1234 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1235 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1236 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1237 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1238 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1239 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1240 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1241 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1242 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1243 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1244 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1245 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1246 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1247 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1248 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1249 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1250 } else { // Custom user agent.
1251 menu.findItem(R.id.user_agent_custom).setChecked(true);
1254 // Instantiate the font size title and the selected font size menu item.
1255 String fontSizeTitle;
1256 MenuItem selectedFontSizeMenuItem;
1258 // Prepare the font size title and current size menu item.
1261 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1262 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1266 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1267 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1271 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1272 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1276 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1277 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1281 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1282 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1286 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1287 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1291 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1292 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1296 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1297 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1301 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1302 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1306 // Set the font size title and select the current size menu item.
1307 fontSizeMenuItem.setTitle(fontSizeTitle);
1308 selectedFontSizeMenuItem.setChecked(true);
1310 // Run all the other default commands.
1311 super.onPrepareOptionsMenu(menu);
1313 // Display the menu.
1318 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1319 @SuppressLint("SetJavaScriptEnabled")
1320 public boolean onOptionsItemSelected(MenuItem menuItem) {
1321 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1322 if (inFullScreenBrowsingMode) {
1323 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1324 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1326 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1328 /* Hide the system bars.
1329 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1330 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1331 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1332 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1334 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1335 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1338 // Get the selected menu item ID.
1339 int menuItemId = menuItem.getItemId();
1341 // Get a handle for the shared preferences.
1342 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1344 // Get a handle for the cookie manager.
1345 CookieManager cookieManager = CookieManager.getInstance();
1347 // Run the commands that correlate to the selected menu item.
1348 switch (menuItemId) {
1349 case R.id.toggle_javascript:
1350 // Toggle the JavaScript status.
1351 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1353 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1354 updatePrivacyIcons(true);
1356 // Display a `Snackbar`.
1357 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1358 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1359 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1360 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1361 } else { // Privacy mode.
1362 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1365 // Reload the current WebView.
1366 currentWebView.reload();
1369 case R.id.add_or_edit_domain:
1370 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1371 // Reapply the domain settings on returning to `MainWebViewActivity`.
1372 reapplyDomainSettingsOnRestart = true;
1374 // Create an intent to launch the domains activity.
1375 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1377 // Add the extra information to the intent.
1378 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1379 domainsIntent.putExtra("close_on_back", true);
1380 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1382 // Get the current certificate.
1383 SslCertificate sslCertificate = currentWebView.getCertificate();
1385 // Check to see if the SSL certificate is populated.
1386 if (sslCertificate != null) {
1387 // Extract the certificate to strings.
1388 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1389 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1390 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1391 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1392 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1393 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1394 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1395 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1397 // Add the certificate to the intent.
1398 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1399 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1400 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1401 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1402 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1403 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1404 domainsIntent.putExtra("ssl_start_date", startDateLong);
1405 domainsIntent.putExtra("ssl_end_date", endDateLong);
1408 // Check to see if the current IP addresses have been received.
1409 if (currentWebView.hasCurrentIpAddresses()) {
1410 // Add the current IP addresses to the intent.
1411 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1415 startActivity(domainsIntent);
1416 } else { // Add a new domain.
1417 // Apply the new domain settings on returning to `MainWebViewActivity`.
1418 reapplyDomainSettingsOnRestart = true;
1420 // Get the current domain
1421 Uri currentUri = Uri.parse(currentWebView.getUrl());
1422 String currentDomain = currentUri.getHost();
1424 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1425 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1427 // Create the domain and store the database ID.
1428 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1430 // Create an intent to launch the domains activity.
1431 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1433 // Add the extra information to the intent.
1434 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1435 domainsIntent.putExtra("close_on_back", true);
1436 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1438 // Get the current certificate.
1439 SslCertificate sslCertificate = currentWebView.getCertificate();
1441 // Check to see if the SSL certificate is populated.
1442 if (sslCertificate != null) {
1443 // Extract the certificate to strings.
1444 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1445 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1446 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1447 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1448 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1449 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1450 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1451 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1453 // Add the certificate to the intent.
1454 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1455 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1456 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1457 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1458 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1459 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1460 domainsIntent.putExtra("ssl_start_date", startDateLong);
1461 domainsIntent.putExtra("ssl_end_date", endDateLong);
1464 // Check to see if the current IP addresses have been received.
1465 if (currentWebView.hasCurrentIpAddresses()) {
1466 // Add the current IP addresses to the intent.
1467 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1471 startActivity(domainsIntent);
1475 case R.id.toggle_first_party_cookies:
1476 // Switch the first-party cookie status.
1477 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1479 // Store the first-party cookie status.
1480 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1482 // Update the menu checkbox.
1483 menuItem.setChecked(cookieManager.acceptCookie());
1485 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1486 updatePrivacyIcons(true);
1488 // Display a snackbar.
1489 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1490 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1491 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1492 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1493 } else { // Privacy mode.
1494 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1497 // Reload the current WebView.
1498 currentWebView.reload();
1501 case R.id.toggle_third_party_cookies:
1502 if (Build.VERSION.SDK_INT >= 21) {
1503 // Switch the status of thirdPartyCookiesEnabled.
1504 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1506 // Update the menu checkbox.
1507 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1509 // Display a snackbar.
1510 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1511 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1513 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1516 // Reload the current WebView.
1517 currentWebView.reload();
1518 } // Else do nothing because SDK < 21.
1521 case R.id.toggle_dom_storage:
1522 // Toggle the status of domStorageEnabled.
1523 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1525 // Update the menu checkbox.
1526 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1528 // Update the privacy icon. `true` refreshes the app bar icons.
1529 updatePrivacyIcons(true);
1531 // Display a snackbar.
1532 if (currentWebView.getSettings().getDomStorageEnabled()) {
1533 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1535 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1538 // Reload the current WebView.
1539 currentWebView.reload();
1542 // Form data can be removed once the minimum API >= 26.
1543 case R.id.toggle_save_form_data:
1544 // Switch the status of saveFormDataEnabled.
1545 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1547 // Update the menu checkbox.
1548 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1550 // Display a snackbar.
1551 if (currentWebView.getSettings().getSaveFormData()) {
1552 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1554 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1557 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1558 updatePrivacyIcons(true);
1560 // Reload the current WebView.
1561 currentWebView.reload();
1564 case R.id.clear_cookies:
1565 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1566 .setAction(R.string.undo, v -> {
1567 // Do nothing because everything will be handled by `onDismissed()` below.
1569 .addCallback(new Snackbar.Callback() {
1570 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1572 public void onDismissed(Snackbar snackbar, int event) {
1573 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1574 // Delete the cookies, which command varies by SDK.
1575 if (Build.VERSION.SDK_INT < 21) {
1576 cookieManager.removeAllCookie();
1578 cookieManager.removeAllCookies(null);
1586 case R.id.clear_dom_storage:
1587 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1588 .setAction(R.string.undo, v -> {
1589 // Do nothing because everything will be handled by `onDismissed()` below.
1591 .addCallback(new Snackbar.Callback() {
1592 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1594 public void onDismissed(Snackbar snackbar, int event) {
1595 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1596 // Delete the DOM Storage.
1597 WebStorage webStorage = WebStorage.getInstance();
1598 webStorage.deleteAllData();
1600 // Initialize a handler to manually delete the DOM storage files and directories.
1601 Handler deleteDomStorageHandler = new Handler();
1603 // Setup a runnable to manually delete the DOM storage files and directories.
1604 Runnable deleteDomStorageRunnable = () -> {
1606 // Get a handle for the runtime.
1607 Runtime runtime = Runtime.getRuntime();
1609 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1610 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1611 String privateDataDirectoryString = getApplicationInfo().dataDir;
1613 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1614 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1616 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1617 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1618 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1619 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1620 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1622 // Wait for the processes to finish.
1623 deleteLocalStorageProcess.waitFor();
1624 deleteIndexProcess.waitFor();
1625 deleteQuotaManagerProcess.waitFor();
1626 deleteQuotaManagerJournalProcess.waitFor();
1627 deleteDatabasesProcess.waitFor();
1628 } catch (Exception exception) {
1629 // Do nothing if an error is thrown.
1633 // Manually delete the DOM storage files after 200 milliseconds.
1634 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1641 // Form data can be remove once the minimum API >= 26.
1642 case R.id.clear_form_data:
1643 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1644 .setAction(R.string.undo, v -> {
1645 // Do nothing because everything will be handled by `onDismissed()` below.
1647 .addCallback(new Snackbar.Callback() {
1648 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1650 public void onDismissed(Snackbar snackbar, int event) {
1651 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1652 // Delete the form data.
1653 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1654 mainWebViewDatabase.clearFormData();
1662 // Toggle the EasyList status.
1663 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1665 // Update the menu checkbox.
1666 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1668 // Reload the current WebView.
1669 currentWebView.reload();
1672 case R.id.easyprivacy:
1673 // Toggle the EasyPrivacy status.
1674 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1676 // Update the menu checkbox.
1677 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1679 // Reload the current WebView.
1680 currentWebView.reload();
1683 case R.id.fanboys_annoyance_list:
1684 // Toggle Fanboy's Annoyance List status.
1685 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1687 // Update the menu checkbox.
1688 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1690 // Update the staus of Fanboy's Social Blocking List.
1691 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1692 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1694 // Reload the current WebView.
1695 currentWebView.reload();
1698 case R.id.fanboys_social_blocking_list:
1699 // Toggle Fanboy's Social Blocking List status.
1700 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1702 // Update the menu checkbox.
1703 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1705 // Reload the current WebView.
1706 currentWebView.reload();
1709 case R.id.ultraprivacy:
1710 // Toggle the UltraPrivacy status.
1711 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1713 // Update the menu checkbox.
1714 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1716 // Reload the current WebView.
1717 currentWebView.reload();
1720 case R.id.block_all_third_party_requests:
1721 //Toggle the third-party requests blocker status.
1722 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1724 // Update the menu checkbox.
1725 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1727 // Reload the current WebView.
1728 currentWebView.reload();
1731 case R.id.user_agent_privacy_browser:
1732 // Update the user agent.
1733 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1735 // Reload the current WebView.
1736 currentWebView.reload();
1739 case R.id.user_agent_webview_default:
1740 // Update the user agent.
1741 currentWebView.getSettings().setUserAgentString("");
1743 // Reload the current WebView.
1744 currentWebView.reload();
1747 case R.id.user_agent_firefox_on_android:
1748 // Update the user agent.
1749 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1751 // Reload the current WebView.
1752 currentWebView.reload();
1755 case R.id.user_agent_chrome_on_android:
1756 // Update the user agent.
1757 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1759 // Reload the current WebView.
1760 currentWebView.reload();
1763 case R.id.user_agent_safari_on_ios:
1764 // Update the user agent.
1765 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1767 // Reload the current WebView.
1768 currentWebView.reload();
1771 case R.id.user_agent_firefox_on_linux:
1772 // Update the user agent.
1773 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1775 // Reload the current WebView.
1776 currentWebView.reload();
1779 case R.id.user_agent_chromium_on_linux:
1780 // Update the user agent.
1781 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1783 // Reload the current WebView.
1784 currentWebView.reload();
1787 case R.id.user_agent_firefox_on_windows:
1788 // Update the user agent.
1789 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1791 // Reload the current WebView.
1792 currentWebView.reload();
1795 case R.id.user_agent_chrome_on_windows:
1796 // Update the user agent.
1797 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1799 // Reload the current WebView.
1800 currentWebView.reload();
1803 case R.id.user_agent_edge_on_windows:
1804 // Update the user agent.
1805 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1807 // Reload the current WebView.
1808 currentWebView.reload();
1811 case R.id.user_agent_internet_explorer_on_windows:
1812 // Update the user agent.
1813 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1815 // Reload the current WebView.
1816 currentWebView.reload();
1819 case R.id.user_agent_safari_on_macos:
1820 // Update the user agent.
1821 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1823 // Reload the current WebView.
1824 currentWebView.reload();
1827 case R.id.user_agent_custom:
1828 // Update the user agent.
1829 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1831 // Reload the current WebView.
1832 currentWebView.reload();
1835 case R.id.font_size_twenty_five_percent:
1836 currentWebView.getSettings().setTextZoom(25);
1839 case R.id.font_size_fifty_percent:
1840 currentWebView.getSettings().setTextZoom(50);
1843 case R.id.font_size_seventy_five_percent:
1844 currentWebView.getSettings().setTextZoom(75);
1847 case R.id.font_size_one_hundred_percent:
1848 currentWebView.getSettings().setTextZoom(100);
1851 case R.id.font_size_one_hundred_twenty_five_percent:
1852 currentWebView.getSettings().setTextZoom(125);
1855 case R.id.font_size_one_hundred_fifty_percent:
1856 currentWebView.getSettings().setTextZoom(150);
1859 case R.id.font_size_one_hundred_seventy_five_percent:
1860 currentWebView.getSettings().setTextZoom(175);
1863 case R.id.font_size_two_hundred_percent:
1864 currentWebView.getSettings().setTextZoom(200);
1867 case R.id.swipe_to_refresh:
1868 // Toggle the stored status of swipe to refresh.
1869 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1871 // Get a handle for the swipe refresh layout.
1872 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1874 // Update the swipe refresh layout.
1875 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1876 if (Build.VERSION.SDK_INT >= 23) { // For API >= 23, the status of the scroll refresh listener is continuously updated by the on scroll change listener.
1877 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1878 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1879 } else { // For API < 23, the swipe refresh layout is always enabled.
1880 // Enable the swipe refresh layout.
1881 swipeRefreshLayout.setEnabled(true);
1883 } else { // Swipe to refresh is disabled.
1884 // Disable the swipe refresh layout.
1885 swipeRefreshLayout.setEnabled(false);
1889 case R.id.display_images:
1890 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1891 // Disable loading of images.
1892 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1894 // Reload the website to remove existing images.
1895 currentWebView.reload();
1896 } else { // Images are not currently loaded automatically.
1897 // Enable loading of images. Missing images will be loaded without the need for a reload.
1898 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1902 case R.id.night_mode:
1903 // Toggle night mode.
1904 currentWebView.setNightMode(!currentWebView.getNightMode());
1906 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1907 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1908 // Enable JavaScript.
1909 currentWebView.getSettings().setJavaScriptEnabled(true);
1910 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1911 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1912 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1913 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1914 // Apply the JavaScript preference.
1915 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1918 // Update the privacy icons.
1919 updatePrivacyIcons(false);
1921 // Reload the website.
1922 currentWebView.reload();
1925 case R.id.find_on_page:
1926 // Get a handle for the views.
1927 Toolbar toolbar = findViewById(R.id.toolbar);
1928 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1929 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1931 // Set the minimum height of the find on page linear layout to match the toolbar.
1932 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1934 // Hide the toolbar.
1935 toolbar.setVisibility(View.GONE);
1937 // Show the find on page linear layout.
1938 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1940 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1941 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1942 findOnPageEditText.postDelayed(() -> {
1943 // Set the focus on `findOnPageEditText`.
1944 findOnPageEditText.requestFocus();
1946 // Get a handle for the input method manager.
1947 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1949 // Remove the lint warning below that the input method manager might be null.
1950 assert inputMethodManager != null;
1952 // Display the keyboard. `0` sets no input flags.
1953 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1957 case R.id.view_source:
1958 // Create an intent to launch the view source activity.
1959 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1961 // Add the variables to the intent.
1962 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1963 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1966 startActivity(viewSourceIntent);
1969 case R.id.share_url:
1970 // Setup the share string.
1971 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1973 // Create the share intent.
1974 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1975 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1976 shareIntent.setType("text/plain");
1979 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1983 // Get a print manager instance.
1984 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1986 // Remove the lint error below that print manager might be null.
1987 assert printManager != null;
1989 // Create a print document adapter from the current WebView.
1990 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1992 // Print the document.
1993 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1996 case R.id.open_with_app:
1997 openWithApp(currentWebView.getUrl());
2000 case R.id.open_with_browser:
2001 openWithBrowser(currentWebView.getUrl());
2004 case R.id.add_to_homescreen:
2005 // Instantiate the create home screen shortcut dialog.
2006 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2007 currentWebView.getFavoriteOrDefaultIcon());
2009 // Show the create home screen shortcut dialog.
2010 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2013 case R.id.proxy_through_orbot:
2014 // Toggle the proxy through Orbot variable.
2015 proxyThroughOrbot = !proxyThroughOrbot;
2017 // Apply the proxy through Orbot settings.
2018 applyProxyThroughOrbot(true);
2022 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2023 // Reload the current WebView.
2024 currentWebView.reload();
2025 } else { // The stop button was pushed.
2026 // Stop the loading of the WebView.
2027 currentWebView.stopLoading();
2031 case R.id.ad_consent:
2032 // Display the ad consent dialog.
2033 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2034 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2038 // Don't consume the event.
2039 return super.onOptionsItemSelected(menuItem);
2043 // removeAllCookies is deprecated, but it is required for API < 21.
2045 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2046 // Get the menu item ID.
2047 int menuItemId = menuItem.getItemId();
2049 // Get a handle for the shared preferences.
2050 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2052 // Run the commands that correspond to the selected menu item.
2053 switch (menuItemId) {
2054 case R.id.close_tab:
2055 // Get a handle for the tab layout and the view pager.
2056 TabLayout tabLayout = findViewById(R.id.tablayout);
2057 ViewPager webViewPager = findViewById(R.id.webviewpager);
2059 // Get the current tab number.
2060 int currentTabNumber = tabLayout.getSelectedTabPosition();
2062 // Delete the current tab.
2063 tabLayout.removeTabAt(currentTabNumber);
2065 // Delete the current page. If the selected page number did not change during the delete, it will return true, meaning that the current WebView must be reset.
2066 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2067 setCurrentWebView(currentTabNumber);
2071 case R.id.clear_and_exit:
2072 // Close the bookmarks cursor and database.
2073 bookmarksCursor.close();
2074 bookmarksDatabaseHelper.close();
2076 // Get the status of the clear everything preference.
2077 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2079 // Get a handle for the runtime.
2080 Runtime runtime = Runtime.getRuntime();
2082 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
2083 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
2084 String privateDataDirectoryString = getApplicationInfo().dataDir;
2087 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2088 // The command to remove cookies changed slightly in API 21.
2089 if (Build.VERSION.SDK_INT >= 21) {
2090 CookieManager.getInstance().removeAllCookies(null);
2092 CookieManager.getInstance().removeAllCookie();
2095 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2097 // Two commands must be used because `Runtime.exec()` does not like `*`.
2098 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2099 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2101 // Wait until the processes have finished.
2102 deleteCookiesProcess.waitFor();
2103 deleteCookiesJournalProcess.waitFor();
2104 } catch (Exception exception) {
2105 // Do nothing if an error is thrown.
2109 // Clear DOM storage.
2110 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2111 // Ask `WebStorage` to clear the DOM storage.
2112 WebStorage webStorage = WebStorage.getInstance();
2113 webStorage.deleteAllData();
2115 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2117 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2118 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2120 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2121 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2122 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2123 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2124 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2126 // Wait until the processes have finished.
2127 deleteLocalStorageProcess.waitFor();
2128 deleteIndexProcess.waitFor();
2129 deleteQuotaManagerProcess.waitFor();
2130 deleteQuotaManagerJournalProcess.waitFor();
2131 deleteDatabaseProcess.waitFor();
2132 } catch (Exception exception) {
2133 // Do nothing if an error is thrown.
2137 // Clear form data if the API < 26.
2138 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2139 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2140 webViewDatabase.clearFormData();
2142 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2144 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2145 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2146 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2148 // Wait until the processes have finished.
2149 deleteWebDataProcess.waitFor();
2150 deleteWebDataJournalProcess.waitFor();
2151 } catch (Exception exception) {
2152 // Do nothing if an error is thrown.
2157 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2158 // Clear the cache from each WebView.
2159 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2160 // Get the WebView tab fragment.
2161 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2163 // Get the fragment view.
2164 View fragmentView = webViewTabFragment.getView();
2166 // Only clear the cache if the WebView exists.
2167 if (fragmentView != null) {
2168 // Get the nested scroll WebView from the tab fragment.
2169 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2171 // Clear the cache for this WebView.
2172 nestedScrollWebView.clearCache(true);
2176 // Manually delete the cache directories.
2178 // Delete the main cache directory.
2179 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2181 // Delete the secondary `Service Worker` cache directory.
2182 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2183 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2185 // Wait until the processes have finished.
2186 deleteCacheProcess.waitFor();
2187 deleteServiceWorkerProcess.waitFor();
2188 } catch (Exception exception) {
2189 // Do nothing if an error is thrown.
2193 // Wipe out each WebView.
2194 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2195 // Get the WebView tab fragment.
2196 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2198 // Get the fragment view.
2199 View fragmentView = webViewTabFragment.getView();
2201 // Only wipe out the WebView if it exists.
2202 if (fragmentView != null) {
2203 // Get the nested scroll WebView from the tab fragment.
2204 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2206 // Clear SSL certificate preferences for this WebView.
2207 nestedScrollWebView.clearSslPreferences();
2209 // Clear the back/forward history for this WebView.
2210 nestedScrollWebView.clearHistory();
2212 // Destroy the internal state of `mainWebView`.
2213 nestedScrollWebView.destroy();
2217 // Clear the custom headers.
2218 customHeaders.clear();
2220 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2221 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2222 if (clearEverything) {
2224 // Delete the folder.
2225 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2227 // Wait until the process has finished.
2228 deleteAppWebviewProcess.waitFor();
2229 } catch (Exception exception) {
2230 // Do nothing if an error is thrown.
2234 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2235 if (Build.VERSION.SDK_INT >= 21) {
2236 finishAndRemoveTask();
2241 // Remove the terminated program from RAM. The status code is `0`.
2246 // Select the homepage based on the proxy through Orbot status.
2247 if (proxyThroughOrbot) {
2248 // Load the Tor homepage.
2249 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2251 // Load the normal homepage.
2252 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2257 if (currentWebView.canGoBack()) {
2258 // Reset the current domain name so that navigation works if third-party requests are blocked.
2259 currentWebView.resetCurrentDomainName();
2261 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2262 currentWebView.setNavigatingHistory(true);
2264 // Load the previous website in the history.
2265 currentWebView.goBack();
2270 if (currentWebView.canGoForward()) {
2271 // Reset the current domain name so that navigation works if third-party requests are blocked.
2272 currentWebView.resetCurrentDomainName();
2274 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2275 currentWebView.setNavigatingHistory(true);
2277 // Load the next website in the history.
2278 currentWebView.goForward();
2283 // Instantiate the URL history dialog.
2284 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2286 // Show the URL history dialog.
2287 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2291 // Populate the resource requests.
2292 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2294 // Create an intent to launch the Requests activity.
2295 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2297 // Add the block third-party requests status to the intent.
2298 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2301 startActivity(requestsIntent);
2304 case R.id.downloads:
2305 // Launch the system Download Manager.
2306 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2308 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2309 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2311 startActivity(downloadManagerIntent);
2315 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2316 reapplyDomainSettingsOnRestart = true;
2318 // Launch the domains activity.
2319 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2321 // Add the extra information to the intent.
2322 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2324 // Get the current certificate.
2325 SslCertificate sslCertificate = currentWebView.getCertificate();
2327 // Check to see if the SSL certificate is populated.
2328 if (sslCertificate != null) {
2329 // Extract the certificate to strings.
2330 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2331 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2332 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2333 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2334 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2335 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2336 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2337 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2339 // Add the certificate to the intent.
2340 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2341 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2342 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2343 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2344 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2345 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2346 domainsIntent.putExtra("ssl_start_date", startDateLong);
2347 domainsIntent.putExtra("ssl_end_date", endDateLong);
2350 // Check to see if the current IP addresses have been received.
2351 if (currentWebView.hasCurrentIpAddresses()) {
2352 // Add the current IP addresses to the intent.
2353 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2357 startActivity(domainsIntent);
2361 // Set the flag to reapply app settings on restart when returning from Settings.
2362 reapplyAppSettingsOnRestart = true;
2364 // Set the flag to reapply the domain settings on restart when returning from Settings.
2365 reapplyDomainSettingsOnRestart = true;
2367 // Launch the settings activity.
2368 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2369 startActivity(settingsIntent);
2372 case R.id.import_export:
2373 // Launch the import/export activity.
2374 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2375 startActivity(importExportIntent);
2379 // Launch the logcat activity.
2380 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2381 startActivity(logcatIntent);
2385 // Launch `GuideActivity`.
2386 Intent guideIntent = new Intent(this, GuideActivity.class);
2387 startActivity(guideIntent);
2391 // Create an intent to launch the about activity.
2392 Intent aboutIntent = new Intent(this, AboutActivity.class);
2394 // Create a string array for the blocklist versions.
2395 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],
2396 ultraPrivacy.get(0).get(0)[0]};
2398 // Add the blocklist versions to the intent.
2399 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2402 startActivity(aboutIntent);
2406 // Get a handle for the drawer layout.
2407 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2409 // Close the navigation drawer.
2410 drawerLayout.closeDrawer(GravityCompat.START);
2415 public void onPostCreate(Bundle savedInstanceState) {
2416 // Run the default commands.
2417 super.onPostCreate(savedInstanceState);
2419 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2420 actionBarDrawerToggle.syncState();
2424 public void onConfigurationChanged(Configuration newConfig) {
2425 // Run the default commands.
2426 super.onConfigurationChanged(newConfig);
2428 // Get the status bar pixel size.
2429 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2430 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2432 // Get the resource density.
2433 float screenDensity = getResources().getDisplayMetrics().density;
2435 // Recalculate the drawer header padding.
2436 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2437 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2438 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2440 // Reload the ad for the free flavor if not in full screen mode.
2441 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2442 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2443 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2446 // `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:
2447 // https://code.google.com/p/android/issues/detail?id=20493#c8
2448 // ActivityCompat.invalidateOptionsMenu(this);
2452 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2453 // Store the hit test result.
2454 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2456 // Create the URL strings.
2457 final String imageUrl;
2458 final String linkUrl;
2460 // Get handles for the system managers.
2461 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2462 FragmentManager fragmentManager = getSupportFragmentManager();
2463 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2465 // Remove the lint errors below that the clipboard manager might be null.
2466 assert clipboardManager != null;
2468 // Process the link according to the type.
2469 switch (hitTestResult.getType()) {
2470 // `SRC_ANCHOR_TYPE` is a link.
2471 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2472 // Get the target URL.
2473 linkUrl = hitTestResult.getExtra();
2475 // Set the target URL as the title of the `ContextMenu`.
2476 menu.setHeaderTitle(linkUrl);
2478 // Add a Load URL entry.
2479 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2488 // Add an Open with App entry.
2489 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2490 openWithApp(linkUrl);
2494 // Add an Open with Browser entry.
2495 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2496 openWithBrowser(linkUrl);
2500 // Add a Copy URL entry.
2501 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2502 // Save the link URL in a `ClipData`.
2503 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2505 // Set the `ClipData` as the clipboard's primary clip.
2506 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2510 // Add a Download URL entry.
2511 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2512 // Check if the download should be processed by an external app.
2513 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2514 openUrlWithExternalApp(linkUrl);
2515 } else { // Download with Android's download manager.
2516 // Check to see if the storage permission has already been granted.
2517 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2518 // Store the variables for future use by `onRequestPermissionsResult()`.
2519 downloadUrl = linkUrl;
2520 downloadContentDisposition = "none";
2521 downloadContentLength = -1;
2523 // Show a dialog if the user has previously denied the permission.
2524 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2525 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2526 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2528 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2529 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2530 } else { // Show the permission request directly.
2531 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2532 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2534 } else { // The storage permission has already been granted.
2535 // Get a handle for the download file alert dialog.
2536 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2538 // Show the download file alert dialog.
2539 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2545 // Add a Cancel entry, which by default closes the context menu.
2546 menu.add(R.string.cancel);
2549 case WebView.HitTestResult.EMAIL_TYPE:
2550 // Get the target URL.
2551 linkUrl = hitTestResult.getExtra();
2553 // Set the target URL as the title of the `ContextMenu`.
2554 menu.setHeaderTitle(linkUrl);
2556 // Add a Write Email entry.
2557 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2558 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2559 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2561 // Parse the url and set it as the data for the `Intent`.
2562 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2564 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2565 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2568 startActivity(emailIntent);
2572 // Add a Copy Email Address entry.
2573 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2574 // Save the email address in a `ClipData`.
2575 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2577 // Set the `ClipData` as the clipboard's primary clip.
2578 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2582 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2583 menu.add(R.string.cancel);
2586 // `IMAGE_TYPE` is an image.
2587 case WebView.HitTestResult.IMAGE_TYPE:
2588 // Get the image URL.
2589 imageUrl = hitTestResult.getExtra();
2591 // Set the image URL as the title of the `ContextMenu`.
2592 menu.setHeaderTitle(imageUrl);
2594 // Add a View Image entry.
2595 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2600 // Add a Download Image entry.
2601 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2602 // Check if the download should be processed by an external app.
2603 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2604 openUrlWithExternalApp(imageUrl);
2605 } else { // Download with Android's download manager.
2606 // Check to see if the storage permission has already been granted.
2607 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2608 // Store the image URL for use by `onRequestPermissionResult()`.
2609 downloadImageUrl = imageUrl;
2611 // Show a dialog if the user has previously denied the permission.
2612 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2613 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2614 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2616 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2617 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2618 } else { // Show the permission request directly.
2619 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2620 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2622 } else { // The storage permission has already been granted.
2623 // Get a handle for the download image alert dialog.
2624 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2626 // Show the download image alert dialog.
2627 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2633 // Add a Copy URL entry.
2634 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2635 // Save the image URL in a `ClipData`.
2636 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2638 // Set the `ClipData` as the clipboard's primary clip.
2639 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2643 // Add an Open with App entry.
2644 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2645 openWithApp(imageUrl);
2649 // Add an Open with Browser entry.
2650 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2651 openWithBrowser(imageUrl);
2655 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2656 menu.add(R.string.cancel);
2660 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2661 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2662 // Get the image URL.
2663 imageUrl = hitTestResult.getExtra();
2665 // Set the image URL as the title of the `ContextMenu`.
2666 menu.setHeaderTitle(imageUrl);
2668 // Add a `View Image` entry.
2669 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2674 // Add a `Download Image` entry.
2675 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2676 // Check if the download should be processed by an external app.
2677 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2678 openUrlWithExternalApp(imageUrl);
2679 } else { // Download with Android's download manager.
2680 // Check to see if the storage permission has already been granted.
2681 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2682 // Store the image URL for use by `onRequestPermissionResult()`.
2683 downloadImageUrl = imageUrl;
2685 // Show a dialog if the user has previously denied the permission.
2686 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2687 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2688 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2690 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2691 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2692 } else { // Show the permission request directly.
2693 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2694 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2696 } else { // The storage permission has already been granted.
2697 // Get a handle for the download image alert dialog.
2698 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2700 // Show the download image alert dialog.
2701 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2707 // Add a `Copy URL` entry.
2708 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2709 // Save the image URL in a `ClipData`.
2710 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2712 // Set the `ClipData` as the clipboard's primary clip.
2713 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2717 // Add an Open with App entry.
2718 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2719 openWithApp(imageUrl);
2723 // Add an Open with Browser entry.
2724 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2725 openWithBrowser(imageUrl);
2729 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2730 menu.add(R.string.cancel);
2736 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2737 // Get a handle for the bookmarks list view.
2738 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2740 // Get the views from the dialog fragment.
2741 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2742 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2744 // Extract the strings from the edit texts.
2745 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2746 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2748 // Create a favorite icon byte array output stream.
2749 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2751 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2752 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2754 // Convert the favorite icon byte array stream to a byte array.
2755 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2757 // Display the new bookmark below the current items in the (0 indexed) list.
2758 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2760 // Create the bookmark.
2761 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2763 // Update the bookmarks cursor with the current contents of this folder.
2764 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2766 // Update the list view.
2767 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2769 // Scroll to the new bookmark.
2770 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2774 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2775 // Get a handle for the bookmarks list view.
2776 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2778 // Get handles for the views in the dialog fragment.
2779 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2780 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2781 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2783 // Get new folder name string.
2784 String folderNameString = createFolderNameEditText.getText().toString();
2786 // Create a folder icon bitmap.
2787 Bitmap folderIconBitmap;
2789 // Set the folder icon bitmap according to the dialog.
2790 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2791 // Get the default folder icon drawable.
2792 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2794 // Convert the folder icon drawable to a bitmap drawable.
2795 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2797 // Convert the folder icon bitmap drawable to a bitmap.
2798 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2799 } else { // Use the WebView favorite icon.
2800 // Copy the favorite icon bitmap to the folder icon bitmap.
2801 folderIconBitmap = favoriteIconBitmap;
2804 // Create a folder icon byte array output stream.
2805 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2807 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2808 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2810 // Convert the folder icon byte array stream to a byte array.
2811 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2813 // Move all the bookmarks down one in the display order.
2814 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2815 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2816 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2819 // Create the folder, which will be placed at the top of the `ListView`.
2820 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2822 // Update the bookmarks cursor with the current contents of this folder.
2823 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2825 // Update the `ListView`.
2826 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2828 // Scroll to the new folder.
2829 bookmarksListView.setSelection(0);
2833 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2834 // Get handles for the views from `dialogFragment`.
2835 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2836 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2837 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2839 // Store the bookmark strings.
2840 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2841 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2843 // Update the bookmark.
2844 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2845 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2846 } else { // Update the bookmark using the `WebView` favorite icon.
2847 // Create a favorite icon byte array output stream.
2848 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2850 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2851 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2853 // Convert the favorite icon byte array stream to a byte array.
2854 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2856 // Update the bookmark and the favorite icon.
2857 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2860 // Update the bookmarks cursor with the current contents of this folder.
2861 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2863 // Update the list view.
2864 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2868 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2869 // Get handles for the views from `dialogFragment`.