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.coordinatorlayout.widget.CoordinatorLayout;
99 import androidx.core.app.ActivityCompat;
100 import androidx.core.content.ContextCompat;
101 import androidx.core.view.GravityCompat;
102 import androidx.drawerlayout.widget.DrawerLayout;
103 import androidx.fragment.app.DialogFragment;
104 import androidx.fragment.app.FragmentManager;
105 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
106 import androidx.viewpager.widget.ViewPager;
108 import com.google.android.material.appbar.AppBarLayout;
109 import com.google.android.material.floatingactionbutton.FloatingActionButton;
110 import com.google.android.material.navigation.NavigationView;
111 import com.google.android.material.snackbar.Snackbar;
112 import com.google.android.material.tabs.TabLayout;
114 import com.stoutner.privacybrowser.BuildConfig;
115 import com.stoutner.privacybrowser.R;
116 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
117 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
118 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
124 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
125 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
126 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
127 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
128 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
129 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
130 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
131 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
132 import com.stoutner.privacybrowser.helpers.AdHelper;
133 import com.stoutner.privacybrowser.helpers.BlockListHelper;
134 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
135 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
136 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
137 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
138 import com.stoutner.privacybrowser.views.NestedScrollWebView;
140 import java.io.ByteArrayInputStream;
141 import java.io.ByteArrayOutputStream;
143 import java.io.IOException;
144 import java.io.UnsupportedEncodingException;
145 import java.net.MalformedURLException;
147 import java.net.URLDecoder;
148 import java.net.URLEncoder;
149 import java.util.ArrayList;
150 import java.util.Date;
151 import java.util.HashMap;
152 import java.util.HashSet;
153 import java.util.List;
154 import java.util.Map;
155 import java.util.Set;
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 app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
225 private boolean hideAppBar;
226 private boolean scrollAppBar;
228 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
229 private boolean reapplyDomainSettingsOnRestart;
231 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
232 private boolean reapplyAppSettingsOnRestart;
234 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
235 private boolean displayingFullScreenVideo;
237 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
238 private BroadcastReceiver orbotStatusBroadcastReceiver;
240 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
241 private boolean waitingForOrbot;
243 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
244 private ActionBarDrawerToggle actionBarDrawerToggle;
246 // The color spans are used in `onCreate()` and `highlightUrlText()`.
247 private ForegroundColorSpan redColorSpan;
248 private ForegroundColorSpan initialGrayColorSpan;
249 private ForegroundColorSpan finalGrayColorSpan;
251 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
252 private int drawerHeaderPaddingLeftAndRight;
253 private int drawerHeaderPaddingTop;
254 private int drawerHeaderPaddingBottom;
256 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
257 // and `loadBookmarksFolder()`.
258 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
260 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
261 private Cursor bookmarksCursor;
263 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
264 private CursorAdapter bookmarksCursorAdapter;
266 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
267 private String oldFolderNameString;
269 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
270 private ValueCallback<Uri[]> fileChooserCallback;
272 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
273 private int defaultProgressViewStartOffset;
274 private int defaultProgressViewEndOffset;
276 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
277 private int swipeRefreshLayoutPaddingTop;
279 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
280 private String downloadUrl;
281 private String downloadContentDisposition;
282 private long downloadContentLength;
284 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
285 private String downloadImageUrl;
287 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
288 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
289 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
292 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
293 @SuppressLint("ClickableViewAccessibility")
294 protected void onCreate(Bundle savedInstanceState) {
295 // Get a handle for the shared preferences.
296 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
298 // Get the theme and screenshot preferences.
299 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
300 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
302 // Disable screenshots if not allowed.
303 if (!allowScreenshots) {
304 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
307 // Set the activity theme.
309 setTheme(R.style.PrivacyBrowserDark);
311 setTheme(R.style.PrivacyBrowserLight);
314 // Run the default commands.
315 super.onCreate(savedInstanceState);
317 // Set the content view.
318 setContentView(R.layout.main_framelayout);
320 // Get a handle for the input method.
321 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
323 // Remove the lint warning below that the input method manager might be null.
324 assert inputMethodManager != null;
326 // Get a handle for the toolbar.
327 Toolbar toolbar = findViewById(R.id.toolbar);
329 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
330 setSupportActionBar(toolbar);
332 // Get a handle for the action bar.
333 ActionBar actionBar = getSupportActionBar();
335 // This is needed to get rid of the Android Studio warning that the action bar might be null.
336 assert actionBar != null;
338 // Add the custom layout, which shows the URL text bar.
339 actionBar.setCustomView(R.layout.url_app_bar);
340 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
342 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
343 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
344 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
345 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
347 // Get handles for the URL views.
348 EditText urlEditText = findViewById(R.id.url_edittext);
350 // Remove the formatting from `urlTextBar` when the user is editing the text.
351 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
352 if (hasFocus) { // The user is editing the URL text box.
353 // Remove the highlighting.
354 urlEditText.getText().removeSpan(redColorSpan);
355 urlEditText.getText().removeSpan(initialGrayColorSpan);
356 urlEditText.getText().removeSpan(finalGrayColorSpan);
357 } else { // The user has stopped editing the URL text box.
358 // Move to the beginning of the string.
359 urlEditText.setSelection(0);
361 // Reapply the highlighting.
366 // Set the go button on the keyboard to load the URL in `urlTextBox`.
367 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
368 // If the event is a key-down event on the `enter` button, load the URL.
369 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
370 // Load the URL into the mainWebView and consume the event.
371 loadUrlFromTextBox();
373 // If the enter key was pressed, consume the event.
376 // If any other key was pressed, do not consume the event.
381 // Initialize the Orbot status and the waiting for Orbot trackers.
382 orbotStatus = "unknown";
383 waitingForOrbot = false;
385 // Create an Orbot status `BroadcastReceiver`.
386 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
388 public void onReceive(Context context, Intent intent) {
389 // Store the content of the status message in `orbotStatus`.
390 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
392 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
393 if (orbotStatus.equals("ON") && waitingForOrbot) {
394 // Reset the waiting for Orbot status.
395 waitingForOrbot = false;
397 // Get the intent that started the app.
398 Intent launchingIntent = getIntent();
400 // Get the information from the intent.
401 String launchingIntentAction = launchingIntent.getAction();
402 Uri launchingIntentUriData = launchingIntent.getData();
404 // If the intent action is a web search, perform the search.
405 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
406 // Create an encoded URL string.
407 String encodedUrlString;
409 // Sanitize the search input and convert it to a search.
411 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
412 } catch (UnsupportedEncodingException exception) {
413 encodedUrlString = "";
416 // Load the completed search URL.
417 loadUrl(searchURL + encodedUrlString);
418 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
419 // Load the URL from the intent.
420 loadUrl(launchingIntentUriData.toString());
421 } else { // The is no URL in the intent.
422 // Select the homepage based on the proxy through Orbot status.
423 if (proxyThroughOrbot) {
424 // Load the Tor homepage.
425 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
427 // Load the normal homepage.
428 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
435 // Register `orbotStatusBroadcastReceiver` on `this` context.
436 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
438 // Instantiate the blocklist helper.
439 BlockListHelper blockListHelper = new BlockListHelper();
441 // Parse the block lists.
442 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
443 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
444 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
445 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
446 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
448 // Get handles for views that need to be modified.
449 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
450 NavigationView navigationView = findViewById(R.id.navigationview);
451 TabLayout tabLayout = findViewById(R.id.tablayout);
452 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
453 ViewPager webViewPager = findViewById(R.id.webviewpager);
454 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
455 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
456 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
457 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
458 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
460 // Listen for touches on the navigation menu.
461 navigationView.setNavigationItemSelectedListener(this);
463 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
464 Menu navigationMenu = navigationView.getMenu();
465 MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
466 MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
467 MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
468 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
469 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
471 // Initialize the web view pager adapter.
472 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
474 // Set the pager adapter on the web view pager.
475 webViewPager.setAdapter(webViewPagerAdapter);
477 // Store up to 100 tabs in memory.
478 webViewPager.setOffscreenPageLimit(100);
480 // Update the web view pager every time a tab is modified.
481 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
483 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
488 public void onPageSelected(int position) {
489 // Close the find on page bar if it is open.
490 closeFindOnPage(null);
492 // Set the current WebView.
493 setCurrentWebView(position);
495 // 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.
496 if (tabLayout.getSelectedTabPosition() != position) {
497 // Create a handler to select the tab.
498 Handler selectTabHandler = new Handler();
500 // Create a runnable select the new tab.
501 Runnable selectTabRunnable = () -> {
502 // Get a handle for the tab.
503 TabLayout.Tab tab = tabLayout.getTabAt(position);
505 // Assert that the tab is not null.
512 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
513 selectTabHandler.postDelayed(selectTabRunnable, 100);
518 public void onPageScrollStateChanged(int state) {
523 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
524 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
526 public void onTabSelected(TabLayout.Tab tab) {
527 // Select the same page in the view pager.
528 webViewPager.setCurrentItem(tab.getPosition());
532 public void onTabUnselected(TabLayout.Tab tab) {
537 public void onTabReselected(TabLayout.Tab tab) {
538 // Instantiate the View SSL Certificate dialog.
539 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
541 // Display the View SSL Certificate dialog.
542 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
546 // Add the first tab.
549 // 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.
550 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
552 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
553 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
554 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
555 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
557 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
558 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
559 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
560 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
563 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
564 launchBookmarksActivityFab.setOnClickListener(v -> {
565 // Get a copy of the favorite icon bitmap.
566 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
568 // Create a favorite icon byte array output stream.
569 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
571 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
572 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
574 // Convert the favorite icon byte array stream to a byte array.
575 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
577 // Create an intent to launch the bookmarks activity.
578 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
580 // Add the extra information to the intent.
581 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
582 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
583 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
584 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
587 startActivity(bookmarksIntent);
590 // Set the create new bookmark folder FAB to display an alert dialog.
591 createBookmarkFolderFab.setOnClickListener(v -> {
592 // Create a create bookmark folder dialog.
593 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
595 // Show the create bookmark folder dialog.
596 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
599 // Set the create new bookmark FAB to display an alert dialog.
600 createBookmarkFab.setOnClickListener(view -> {
601 // Instantiate the create bookmark dialog.
602 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
604 // Display the create bookmark dialog.
605 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
608 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
609 findOnPageEditText.addTextChangedListener(new TextWatcher() {
611 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
616 public void onTextChanged(CharSequence s, int start, int before, int count) {
621 public void afterTextChanged(Editable s) {
622 // Search for the text in the WebView if it is not null. Sometimes on resume after a period of non-use the WebView will be null.
623 if (currentWebView != null) {
624 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
629 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
630 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
631 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
632 // Hide the soft keyboard.
633 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
635 // Consume the event.
637 } else { // A different key was pressed.
638 // Do not consume the event.
643 // Implement swipe to refresh.
644 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
646 // Store the default progress view offsets for use later in `initializeWebView()`.
647 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
648 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
650 // Set the swipe to refresh color according to the theme.
652 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
653 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
655 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
658 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
659 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
660 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
662 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
663 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
665 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
666 currentBookmarksFolder = "";
668 // Load the home folder, which is `""` in the database.
669 loadBookmarksFolder();
671 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
672 // Convert the id from long to int to match the format of the bookmarks database.
673 int databaseID = (int) id;
675 // Get the bookmark cursor for this ID and move it to the first row.
676 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
677 bookmarkCursor.moveToFirst();
679 // Act upon the bookmark according to the type.
680 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
681 // Store the new folder name in `currentBookmarksFolder`.
682 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
684 // Load the new folder.
685 loadBookmarksFolder();
686 } else { // The selected bookmark is not a folder.
687 // Load the bookmark URL.
688 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
690 // Close the bookmarks drawer.
691 drawerLayout.closeDrawer(GravityCompat.END);
694 // Close the `Cursor`.
695 bookmarkCursor.close();
698 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
699 // Convert the database ID from `long` to `int`.
700 int databaseId = (int) id;
702 // Find out if the selected bookmark is a folder.
703 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
706 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
707 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
709 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
710 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
711 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
713 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
714 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
715 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
718 // Consume the event.
722 // Get the status bar pixel size.
723 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
724 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
726 // Get the resource density.
727 float screenDensity = getResources().getDisplayMetrics().density;
729 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
730 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
731 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
732 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
734 // The drawer listener is used to update the navigation menu.`
735 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
737 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
741 public void onDrawerOpened(@NonNull View drawerView) {
745 public void onDrawerClosed(@NonNull View drawerView) {
749 public void onDrawerStateChanged(int newState) {
750 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
751 // Get handles for the drawer headers.
752 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
753 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
755 // 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.
756 if (navigationHeaderTextView != null) {
757 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
760 // 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.
761 if (bookmarksHeaderTextView != null) {
762 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
765 // Update the navigation menu items.
766 navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
767 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
768 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
769 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
770 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
772 // Hide the keyboard (if displayed).
773 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
775 // 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.
776 urlEditText.clearFocus();
777 currentWebView.clearFocus();
782 // Create the hamburger icon at the start of the AppBar.
783 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
785 // 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).
786 customHeaders.put("X-Requested-With", "");
788 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
789 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
791 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
792 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
794 // Get a handle for the WebView.
795 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
797 // Store the default user agent.
798 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
800 // Destroy the bare WebView.
801 bareWebView.destroy();
805 protected void onNewIntent(Intent intent) {
806 // Get the information from the intent.
807 String intentAction = intent.getAction();
808 Uri intentUriData = intent.getData();
810 // 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.
811 if (intentUriData != null) {
812 // Sets the new intent as the activity intent, which replaces the one that originally started the app.
818 // Create a URL string.
821 // If the intent action is a web search, perform the search.
822 if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
823 // Create an encoded URL string.
824 String encodedUrlString;
826 // Sanitize the search input and convert it to a search.
828 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
829 } catch (UnsupportedEncodingException exception) {
830 encodedUrlString = "";
833 // Add the base search URL.
834 url = searchURL + encodedUrlString;
835 } else { // The intent should contain a URL.
836 // Set the intent data as the URL.
837 url = intentUriData.toString();
843 // Get a handle for the drawer layout.
844 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
846 // Close the navigation drawer if it is open.
847 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
848 drawerLayout.closeDrawer(GravityCompat.START);
851 // Close the bookmarks drawer if it is open.
852 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
853 drawerLayout.closeDrawer(GravityCompat.END);
856 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
857 currentWebView.requestFocus();
862 public void onRestart() {
863 // Run the default commands.
866 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
867 if (proxyThroughOrbot) {
868 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
869 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
871 // Send the intent to the Orbot package.
872 orbotIntent.setPackage("org.torproject.android");
875 sendBroadcast(orbotIntent);
878 // Apply the app settings if returning from the Settings activity.
879 if (reapplyAppSettingsOnRestart) {
880 // Reset the reapply app settings on restart tracker.
881 reapplyAppSettingsOnRestart = false;
883 // Apply the app settings.
887 // Apply the domain settings if returning from the settings or domains activity.
888 if (reapplyDomainSettingsOnRestart) {
889 // Reset the reapply domain settings on restart tracker.
890 reapplyDomainSettingsOnRestart = false;
892 // Reapply the domain settings for each tab.
893 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
894 // Get the WebView tab fragment.
895 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
897 // Get the fragment view.
898 View fragmentView = webViewTabFragment.getView();
900 // Only reload the WebViews if they exist.
901 if (fragmentView != null) {
902 // Get the nested scroll WebView from the tab fragment.
903 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
905 // Reset the current domain name so the domain settings will be reapplied.
906 nestedScrollWebView.resetCurrentDomainName();
908 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
909 if (nestedScrollWebView.getUrl() != null) {
910 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
916 // Load the URL on restart (used when loading a bookmark).
917 if (loadUrlOnRestart) {
918 // Load the specified URL.
919 loadUrl(urlToLoadOnRestart);
921 // Reset the load on restart tracker.
922 loadUrlOnRestart = false;
925 // Update the bookmarks drawer if returning from the Bookmarks activity.
926 if (restartFromBookmarksActivity) {
927 // Get a handle for the drawer layout.
928 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
930 // Close the bookmarks drawer.
931 drawerLayout.closeDrawer(GravityCompat.END);
933 // Reload the bookmarks drawer.
934 loadBookmarksFolder();
936 // Reset `restartFromBookmarksActivity`.
937 restartFromBookmarksActivity = false;
940 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
941 updatePrivacyIcons(true);
944 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
946 public void onResume() {
947 // Run the default commands.
950 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
951 // Get the WebView tab fragment.
952 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
954 // Get the fragment view.
955 View fragmentView = webViewTabFragment.getView();
957 // Only resume the WebViews if they exist (they won't when the app is first created).
958 if (fragmentView != null) {
959 // Get the nested scroll WebView from the tab fragment.
960 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
962 // Resume the nested scroll WebView JavaScript timers.
963 nestedScrollWebView.resumeTimers();
965 // Resume the nested scroll WebView.
966 nestedScrollWebView.onResume();
970 // Display a message to the user if waiting for Orbot.
971 if (waitingForOrbot && !orbotStatus.equals("ON")) {
972 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
973 currentWebView.getSettings().setUseWideViewPort(false);
975 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
976 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
979 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
980 // Get a handle for the root frame layouts.
981 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
983 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
984 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
986 /* Hide the system bars.
987 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
988 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
989 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
990 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
992 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
993 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
994 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
996 AdHelper.resumeAd(findViewById(R.id.adview));
1001 public void onPause() {
1002 // Run the default commands.
1005 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1006 // Get the WebView tab fragment.
1007 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1009 // Get the fragment view.
1010 View fragmentView = webViewTabFragment.getView();
1012 // Only pause the WebViews if they exist (they won't when the app is first created).
1013 if (fragmentView != null) {
1014 // Get the nested scroll WebView from the tab fragment.
1015 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1017 // Pause the nested scroll WebView.
1018 nestedScrollWebView.onPause();
1020 // Pause the nested scroll WebView JavaScript timers.
1021 nestedScrollWebView.pauseTimers();
1025 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1026 if (BuildConfig.FLAVOR.contentEquals("free")) {
1028 AdHelper.pauseAd(findViewById(R.id.adview));
1033 public void onDestroy() {
1034 // Unregister the Orbot status broadcast receiver.
1035 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1037 // Close the bookmarks cursor and database.
1038 bookmarksCursor.close();
1039 bookmarksDatabaseHelper.close();
1041 // Run the default commands.
1046 public boolean onCreateOptionsMenu(Menu menu) {
1047 // Inflate the menu. This adds items to the action bar if it is present.
1048 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1050 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1053 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1054 updatePrivacyIcons(false);
1056 // Get handles for the menu items.
1057 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1058 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1059 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1060 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1061 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1062 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1063 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1065 // Only display third-party cookies if API >= 21
1066 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1068 // Only display the form data menu items if the API < 26.
1069 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1070 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1072 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1073 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1075 // Only show Ad Consent if this is the free flavor.
1076 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1078 // Get the shared preference values.
1079 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1081 // Get the dark theme and app bar preferences..
1082 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1083 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1085 // 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.
1086 if (displayAdditionalAppBarIcons) {
1087 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1088 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1089 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1090 } else { //Do not display the additional icons.
1091 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1092 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1093 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1096 // Replace Refresh with Stop if a URL is already loading.
1097 if (currentWebView != null && currentWebView.getProgress() != 100) {
1099 refreshMenuItem.setTitle(R.string.stop);
1101 // If the icon is displayed in the AppBar, set it according to the theme.
1102 if (displayAdditionalAppBarIcons) {
1104 refreshMenuItem.setIcon(R.drawable.close_dark);
1106 refreshMenuItem.setIcon(R.drawable.close_light);
1115 public boolean onPrepareOptionsMenu(Menu menu) {
1116 // Get handles for the menu items.
1117 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1118 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1119 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1120 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1121 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1122 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1123 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1124 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1125 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1126 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1127 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1128 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1129 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1130 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1131 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1132 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1133 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1134 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1135 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1136 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1137 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1139 // Get a handle for the cookie manager.
1140 CookieManager cookieManager = CookieManager.getInstance();
1142 // Initialize the current user agent string and the font size.
1143 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1146 // 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.
1147 if (currentWebView != null) {
1148 // Set the add or edit domain text.
1149 if (currentWebView.getDomainSettingsApplied()) {
1150 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1152 addOrEditDomain.setTitle(R.string.add_domain_settings);
1155 // Get the current user agent from the WebView.
1156 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1158 // Get the current font size from the
1159 fontSize = currentWebView.getSettings().getTextZoom();
1161 // Set the status of the menu item checkboxes.
1162 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1163 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1164 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1165 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1166 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1167 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1168 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1169 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1170 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1171 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1172 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1174 // Initialize the display names for the blocklists with the number of blocked requests.
1175 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1176 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1177 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1178 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1179 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1180 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1181 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1183 // Only modify third-party cookies if the API >= 21.
1184 if (Build.VERSION.SDK_INT >= 21) {
1185 // Set the status of the third-party cookies checkbox.
1186 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1188 // Enable third-party cookies if first-party cookies are enabled.
1189 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1192 // Enable DOM Storage if JavaScript is enabled.
1193 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1196 // Set the status of the menu item checkboxes.
1197 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1198 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1200 // Enable Clear Cookies if there are any.
1201 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1203 // 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`.
1204 String privateDataDirectoryString = getApplicationInfo().dataDir;
1206 // Get a count of the number of files in the Local Storage directory.
1207 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1208 int localStorageDirectoryNumberOfFiles = 0;
1209 if (localStorageDirectory.exists()) {
1210 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1213 // Get a count of the number of files in the IndexedDB directory.
1214 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1215 int indexedDBDirectoryNumberOfFiles = 0;
1216 if (indexedDBDirectory.exists()) {
1217 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1220 // Enable Clear DOM Storage if there is any.
1221 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1223 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1224 if (Build.VERSION.SDK_INT < 26) {
1225 // Get the WebView database.
1226 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1228 // Enable the clear form data menu item if there is anything to clear.
1229 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1232 // Enable Clear Data if any of the submenu items are enabled.
1233 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1235 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1236 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1238 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1239 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1240 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1241 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1242 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1243 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1244 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1245 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1246 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1247 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1248 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1249 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1250 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1251 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1252 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1253 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1254 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1255 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1256 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1257 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1258 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1259 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1260 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1261 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1262 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1263 } else { // Custom user agent.
1264 menu.findItem(R.id.user_agent_custom).setChecked(true);
1267 // Instantiate the font size title and the selected font size menu item.
1268 String fontSizeTitle;
1269 MenuItem selectedFontSizeMenuItem;
1271 // Prepare the font size title and current size menu item.
1274 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1275 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1279 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1280 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1284 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1285 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1289 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1290 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1294 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1295 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1299 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1300 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1304 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1305 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1309 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1310 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1314 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1315 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1319 // Set the font size title and select the current size menu item.
1320 fontSizeMenuItem.setTitle(fontSizeTitle);
1321 selectedFontSizeMenuItem.setChecked(true);
1323 // Run all the other default commands.
1324 super.onPrepareOptionsMenu(menu);
1326 // Display the menu.
1331 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1332 @SuppressLint("SetJavaScriptEnabled")
1333 public boolean onOptionsItemSelected(MenuItem menuItem) {
1334 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1335 if (inFullScreenBrowsingMode) {
1336 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1337 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1339 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1341 /* Hide the system bars.
1342 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1343 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1344 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1345 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1347 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1348 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1351 // Get the selected menu item ID.
1352 int menuItemId = menuItem.getItemId();
1354 // Get a handle for the shared preferences.
1355 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1357 // Get a handle for the cookie manager.
1358 CookieManager cookieManager = CookieManager.getInstance();
1360 // Run the commands that correlate to the selected menu item.
1361 switch (menuItemId) {
1362 case R.id.toggle_javascript:
1363 // Toggle the JavaScript status.
1364 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1366 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1367 updatePrivacyIcons(true);
1369 // Display a `Snackbar`.
1370 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1371 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1372 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1373 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1374 } else { // Privacy mode.
1375 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1378 // Reload the current WebView.
1379 currentWebView.reload();
1382 case R.id.add_or_edit_domain:
1383 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1384 // Reapply the domain settings on returning to `MainWebViewActivity`.
1385 reapplyDomainSettingsOnRestart = true;
1387 // Create an intent to launch the domains activity.
1388 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1390 // Add the extra information to the intent.
1391 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1392 domainsIntent.putExtra("close_on_back", true);
1393 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1395 // Get the current certificate.
1396 SslCertificate sslCertificate = currentWebView.getCertificate();
1398 // Check to see if the SSL certificate is populated.
1399 if (sslCertificate != null) {
1400 // Extract the certificate to strings.
1401 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1402 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1403 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1404 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1405 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1406 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1407 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1408 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1410 // Add the certificate to the intent.
1411 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1412 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1413 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1414 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1415 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1416 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1417 domainsIntent.putExtra("ssl_start_date", startDateLong);
1418 domainsIntent.putExtra("ssl_end_date", endDateLong);
1421 // Check to see if the current IP addresses have been received.
1422 if (currentWebView.hasCurrentIpAddresses()) {
1423 // Add the current IP addresses to the intent.
1424 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1428 startActivity(domainsIntent);
1429 } else { // Add a new domain.
1430 // Apply the new domain settings on returning to `MainWebViewActivity`.
1431 reapplyDomainSettingsOnRestart = true;
1433 // Get the current domain
1434 Uri currentUri = Uri.parse(currentWebView.getUrl());
1435 String currentDomain = currentUri.getHost();
1437 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1438 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1440 // Create the domain and store the database ID.
1441 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1443 // Create an intent to launch the domains activity.
1444 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1446 // Add the extra information to the intent.
1447 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1448 domainsIntent.putExtra("close_on_back", true);
1449 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1451 // Get the current certificate.
1452 SslCertificate sslCertificate = currentWebView.getCertificate();
1454 // Check to see if the SSL certificate is populated.
1455 if (sslCertificate != null) {
1456 // Extract the certificate to strings.
1457 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1458 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1459 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1460 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1461 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1462 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1463 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1464 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1466 // Add the certificate to the intent.
1467 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1468 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1469 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1470 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1471 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1472 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1473 domainsIntent.putExtra("ssl_start_date", startDateLong);
1474 domainsIntent.putExtra("ssl_end_date", endDateLong);
1477 // Check to see if the current IP addresses have been received.
1478 if (currentWebView.hasCurrentIpAddresses()) {
1479 // Add the current IP addresses to the intent.
1480 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1484 startActivity(domainsIntent);
1488 case R.id.toggle_first_party_cookies:
1489 // Switch the first-party cookie status.
1490 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1492 // Store the first-party cookie status.
1493 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1495 // Update the menu checkbox.
1496 menuItem.setChecked(cookieManager.acceptCookie());
1498 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1499 updatePrivacyIcons(true);
1501 // Display a snackbar.
1502 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1503 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1504 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1505 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1506 } else { // Privacy mode.
1507 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1510 // Reload the current WebView.
1511 currentWebView.reload();
1514 case R.id.toggle_third_party_cookies:
1515 if (Build.VERSION.SDK_INT >= 21) {
1516 // Switch the status of thirdPartyCookiesEnabled.
1517 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1519 // Update the menu checkbox.
1520 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1522 // Display a snackbar.
1523 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1524 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1526 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1529 // Reload the current WebView.
1530 currentWebView.reload();
1531 } // Else do nothing because SDK < 21.
1534 case R.id.toggle_dom_storage:
1535 // Toggle the status of domStorageEnabled.
1536 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1538 // Update the menu checkbox.
1539 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1541 // Update the privacy icon. `true` refreshes the app bar icons.
1542 updatePrivacyIcons(true);
1544 // Display a snackbar.
1545 if (currentWebView.getSettings().getDomStorageEnabled()) {
1546 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1548 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1551 // Reload the current WebView.
1552 currentWebView.reload();
1555 // Form data can be removed once the minimum API >= 26.
1556 case R.id.toggle_save_form_data:
1557 // Switch the status of saveFormDataEnabled.
1558 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1560 // Update the menu checkbox.
1561 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1563 // Display a snackbar.
1564 if (currentWebView.getSettings().getSaveFormData()) {
1565 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1567 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1570 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1571 updatePrivacyIcons(true);
1573 // Reload the current WebView.
1574 currentWebView.reload();
1577 case R.id.clear_cookies:
1578 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1579 .setAction(R.string.undo, v -> {
1580 // Do nothing because everything will be handled by `onDismissed()` below.
1582 .addCallback(new Snackbar.Callback() {
1583 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1585 public void onDismissed(Snackbar snackbar, int event) {
1586 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1587 // Delete the cookies, which command varies by SDK.
1588 if (Build.VERSION.SDK_INT < 21) {
1589 cookieManager.removeAllCookie();
1591 cookieManager.removeAllCookies(null);
1599 case R.id.clear_dom_storage:
1600 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1601 .setAction(R.string.undo, v -> {
1602 // Do nothing because everything will be handled by `onDismissed()` below.
1604 .addCallback(new Snackbar.Callback() {
1605 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1607 public void onDismissed(Snackbar snackbar, int event) {
1608 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1609 // Delete the DOM Storage.
1610 WebStorage webStorage = WebStorage.getInstance();
1611 webStorage.deleteAllData();
1613 // Initialize a handler to manually delete the DOM storage files and directories.
1614 Handler deleteDomStorageHandler = new Handler();
1616 // Setup a runnable to manually delete the DOM storage files and directories.
1617 Runnable deleteDomStorageRunnable = () -> {
1619 // Get a handle for the runtime.
1620 Runtime runtime = Runtime.getRuntime();
1622 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1623 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1624 String privateDataDirectoryString = getApplicationInfo().dataDir;
1626 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1627 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1629 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1630 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1631 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1632 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1633 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1635 // Wait for the processes to finish.
1636 deleteLocalStorageProcess.waitFor();
1637 deleteIndexProcess.waitFor();
1638 deleteQuotaManagerProcess.waitFor();
1639 deleteQuotaManagerJournalProcess.waitFor();
1640 deleteDatabasesProcess.waitFor();
1641 } catch (Exception exception) {
1642 // Do nothing if an error is thrown.
1646 // Manually delete the DOM storage files after 200 milliseconds.
1647 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1654 // Form data can be remove once the minimum API >= 26.
1655 case R.id.clear_form_data:
1656 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1657 .setAction(R.string.undo, v -> {
1658 // Do nothing because everything will be handled by `onDismissed()` below.
1660 .addCallback(new Snackbar.Callback() {
1661 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1663 public void onDismissed(Snackbar snackbar, int event) {
1664 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1665 // Delete the form data.
1666 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1667 mainWebViewDatabase.clearFormData();
1675 // Toggle the EasyList status.
1676 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1678 // Update the menu checkbox.
1679 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1681 // Reload the current WebView.
1682 currentWebView.reload();
1685 case R.id.easyprivacy:
1686 // Toggle the EasyPrivacy status.
1687 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1689 // Update the menu checkbox.
1690 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1692 // Reload the current WebView.
1693 currentWebView.reload();
1696 case R.id.fanboys_annoyance_list:
1697 // Toggle Fanboy's Annoyance List status.
1698 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1700 // Update the menu checkbox.
1701 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1703 // Update the staus of Fanboy's Social Blocking List.
1704 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1705 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1707 // Reload the current WebView.
1708 currentWebView.reload();
1711 case R.id.fanboys_social_blocking_list:
1712 // Toggle Fanboy's Social Blocking List status.
1713 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1715 // Update the menu checkbox.
1716 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1718 // Reload the current WebView.
1719 currentWebView.reload();
1722 case R.id.ultraprivacy:
1723 // Toggle the UltraPrivacy status.
1724 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1726 // Update the menu checkbox.
1727 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1729 // Reload the current WebView.
1730 currentWebView.reload();
1733 case R.id.block_all_third_party_requests:
1734 //Toggle the third-party requests blocker status.
1735 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1737 // Update the menu checkbox.
1738 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1740 // Reload the current WebView.
1741 currentWebView.reload();
1744 case R.id.user_agent_privacy_browser:
1745 // Update the user agent.
1746 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1748 // Reload the current WebView.
1749 currentWebView.reload();
1752 case R.id.user_agent_webview_default:
1753 // Update the user agent.
1754 currentWebView.getSettings().setUserAgentString("");
1756 // Reload the current WebView.
1757 currentWebView.reload();
1760 case R.id.user_agent_firefox_on_android:
1761 // Update the user agent.
1762 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1764 // Reload the current WebView.
1765 currentWebView.reload();
1768 case R.id.user_agent_chrome_on_android:
1769 // Update the user agent.
1770 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1772 // Reload the current WebView.
1773 currentWebView.reload();
1776 case R.id.user_agent_safari_on_ios:
1777 // Update the user agent.
1778 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1780 // Reload the current WebView.
1781 currentWebView.reload();
1784 case R.id.user_agent_firefox_on_linux:
1785 // Update the user agent.
1786 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1788 // Reload the current WebView.
1789 currentWebView.reload();
1792 case R.id.user_agent_chromium_on_linux:
1793 // Update the user agent.
1794 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1796 // Reload the current WebView.
1797 currentWebView.reload();
1800 case R.id.user_agent_firefox_on_windows:
1801 // Update the user agent.
1802 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1804 // Reload the current WebView.
1805 currentWebView.reload();
1808 case R.id.user_agent_chrome_on_windows:
1809 // Update the user agent.
1810 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1812 // Reload the current WebView.
1813 currentWebView.reload();
1816 case R.id.user_agent_edge_on_windows:
1817 // Update the user agent.
1818 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1820 // Reload the current WebView.
1821 currentWebView.reload();
1824 case R.id.user_agent_internet_explorer_on_windows:
1825 // Update the user agent.
1826 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1828 // Reload the current WebView.
1829 currentWebView.reload();
1832 case R.id.user_agent_safari_on_macos:
1833 // Update the user agent.
1834 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1836 // Reload the current WebView.
1837 currentWebView.reload();
1840 case R.id.user_agent_custom:
1841 // Update the user agent.
1842 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1844 // Reload the current WebView.
1845 currentWebView.reload();
1848 case R.id.font_size_twenty_five_percent:
1849 currentWebView.getSettings().setTextZoom(25);
1852 case R.id.font_size_fifty_percent:
1853 currentWebView.getSettings().setTextZoom(50);
1856 case R.id.font_size_seventy_five_percent:
1857 currentWebView.getSettings().setTextZoom(75);
1860 case R.id.font_size_one_hundred_percent:
1861 currentWebView.getSettings().setTextZoom(100);
1864 case R.id.font_size_one_hundred_twenty_five_percent:
1865 currentWebView.getSettings().setTextZoom(125);
1868 case R.id.font_size_one_hundred_fifty_percent:
1869 currentWebView.getSettings().setTextZoom(150);
1872 case R.id.font_size_one_hundred_seventy_five_percent:
1873 currentWebView.getSettings().setTextZoom(175);
1876 case R.id.font_size_two_hundred_percent:
1877 currentWebView.getSettings().setTextZoom(200);
1880 case R.id.swipe_to_refresh:
1881 // Toggle the stored status of swipe to refresh.
1882 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1884 // Get a handle for the swipe refresh layout.
1885 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1887 // Update the swipe refresh layout.
1888 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1889 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.
1890 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1891 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1892 } else { // For API < 23, the swipe refresh layout is always enabled.
1893 // Enable the swipe refresh layout.
1894 swipeRefreshLayout.setEnabled(true);
1896 } else { // Swipe to refresh is disabled.
1897 // Disable the swipe refresh layout.
1898 swipeRefreshLayout.setEnabled(false);
1902 case R.id.display_images:
1903 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1904 // Disable loading of images.
1905 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1907 // Reload the website to remove existing images.
1908 currentWebView.reload();
1909 } else { // Images are not currently loaded automatically.
1910 // Enable loading of images. Missing images will be loaded without the need for a reload.
1911 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1915 case R.id.night_mode:
1916 // Toggle night mode.
1917 currentWebView.setNightMode(!currentWebView.getNightMode());
1919 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1920 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1921 // Enable JavaScript.
1922 currentWebView.getSettings().setJavaScriptEnabled(true);
1923 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1924 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1925 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1926 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1927 // Apply the JavaScript preference.
1928 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1931 // Update the privacy icons.
1932 updatePrivacyIcons(false);
1934 // Reload the website.
1935 currentWebView.reload();
1938 case R.id.find_on_page:
1939 // Get a handle for the views.
1940 Toolbar toolbar = findViewById(R.id.toolbar);
1941 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1942 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1944 // Set the minimum height of the find on page linear layout to match the toolbar.
1945 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1947 // Hide the toolbar.
1948 toolbar.setVisibility(View.GONE);
1950 // Show the find on page linear layout.
1951 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1953 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1954 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1955 findOnPageEditText.postDelayed(() -> {
1956 // Set the focus on `findOnPageEditText`.
1957 findOnPageEditText.requestFocus();
1959 // Get a handle for the input method manager.
1960 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1962 // Remove the lint warning below that the input method manager might be null.
1963 assert inputMethodManager != null;
1965 // Display the keyboard. `0` sets no input flags.
1966 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1970 case R.id.view_source:
1971 // Create an intent to launch the view source activity.
1972 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1974 // Add the variables to the intent.
1975 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1976 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1979 startActivity(viewSourceIntent);
1982 case R.id.share_url:
1983 // Setup the share string.
1984 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1986 // Create the share intent.
1987 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1988 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1989 shareIntent.setType("text/plain");
1992 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1996 // Get a print manager instance.
1997 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1999 // Remove the lint error below that print manager might be null.
2000 assert printManager != null;
2002 // Create a print document adapter from the current WebView.
2003 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2005 // Print the document.
2006 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2009 case R.id.open_with_app:
2010 openWithApp(currentWebView.getUrl());
2013 case R.id.open_with_browser:
2014 openWithBrowser(currentWebView.getUrl());
2017 case R.id.add_to_homescreen:
2018 // Instantiate the create home screen shortcut dialog.
2019 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2020 currentWebView.getFavoriteOrDefaultIcon());
2022 // Show the create home screen shortcut dialog.
2023 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2026 case R.id.proxy_through_orbot:
2027 // Toggle the proxy through Orbot variable.
2028 proxyThroughOrbot = !proxyThroughOrbot;
2030 // Apply the proxy through Orbot settings.
2031 applyProxyThroughOrbot(true);
2035 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2036 // Reload the current WebView.
2037 currentWebView.reload();
2038 } else { // The stop button was pushed.
2039 // Stop the loading of the WebView.
2040 currentWebView.stopLoading();
2044 case R.id.ad_consent:
2045 // Display the ad consent dialog.
2046 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2047 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2051 // Don't consume the event.
2052 return super.onOptionsItemSelected(menuItem);
2056 // removeAllCookies is deprecated, but it is required for API < 21.
2058 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2059 // Get the menu item ID.
2060 int menuItemId = menuItem.getItemId();
2062 // Get a handle for the shared preferences.
2063 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2065 // Run the commands that correspond to the selected menu item.
2066 switch (menuItemId) {
2067 case R.id.close_tab:
2068 // Get a handle for the tab layout and the view pager.
2069 TabLayout tabLayout = findViewById(R.id.tablayout);
2070 ViewPager webViewPager = findViewById(R.id.webviewpager);
2072 // Get the current tab number.
2073 int currentTabNumber = tabLayout.getSelectedTabPosition();
2075 // Delete the current tab.
2076 tabLayout.removeTabAt(currentTabNumber);
2078 // 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.
2079 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2080 setCurrentWebView(currentTabNumber);
2084 case R.id.clear_and_exit:
2085 // Close the bookmarks cursor and database.
2086 bookmarksCursor.close();
2087 bookmarksDatabaseHelper.close();
2089 // Get the status of the clear everything preference.
2090 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2092 // Get a handle for the runtime.
2093 Runtime runtime = Runtime.getRuntime();
2095 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
2096 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
2097 String privateDataDirectoryString = getApplicationInfo().dataDir;
2100 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2101 // The command to remove cookies changed slightly in API 21.
2102 if (Build.VERSION.SDK_INT >= 21) {
2103 CookieManager.getInstance().removeAllCookies(null);
2105 CookieManager.getInstance().removeAllCookie();
2108 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2110 // Two commands must be used because `Runtime.exec()` does not like `*`.
2111 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2112 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2114 // Wait until the processes have finished.
2115 deleteCookiesProcess.waitFor();
2116 deleteCookiesJournalProcess.waitFor();
2117 } catch (Exception exception) {
2118 // Do nothing if an error is thrown.
2122 // Clear DOM storage.
2123 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2124 // Ask `WebStorage` to clear the DOM storage.
2125 WebStorage webStorage = WebStorage.getInstance();
2126 webStorage.deleteAllData();
2128 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2130 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2131 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2133 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2134 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2135 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2136 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2137 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2139 // Wait until the processes have finished.
2140 deleteLocalStorageProcess.waitFor();
2141 deleteIndexProcess.waitFor();
2142 deleteQuotaManagerProcess.waitFor();
2143 deleteQuotaManagerJournalProcess.waitFor();
2144 deleteDatabaseProcess.waitFor();
2145 } catch (Exception exception) {
2146 // Do nothing if an error is thrown.
2150 // Clear form data if the API < 26.
2151 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2152 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2153 webViewDatabase.clearFormData();
2155 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2157 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2158 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2159 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2161 // Wait until the processes have finished.
2162 deleteWebDataProcess.waitFor();
2163 deleteWebDataJournalProcess.waitFor();
2164 } catch (Exception exception) {
2165 // Do nothing if an error is thrown.
2170 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2171 // Clear the cache from each WebView.
2172 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2173 // Get the WebView tab fragment.
2174 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2176 // Get the fragment view.
2177 View fragmentView = webViewTabFragment.getView();
2179 // Only clear the cache if the WebView exists.
2180 if (fragmentView != null) {
2181 // Get the nested scroll WebView from the tab fragment.
2182 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2184 // Clear the cache for this WebView.
2185 nestedScrollWebView.clearCache(true);
2189 // Manually delete the cache directories.
2191 // Delete the main cache directory.
2192 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2194 // Delete the secondary `Service Worker` cache directory.
2195 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2196 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2198 // Wait until the processes have finished.
2199 deleteCacheProcess.waitFor();
2200 deleteServiceWorkerProcess.waitFor();
2201 } catch (Exception exception) {
2202 // Do nothing if an error is thrown.
2206 // Wipe out each WebView.
2207 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2208 // Get the WebView tab fragment.
2209 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2211 // Get the fragment view.
2212 View fragmentView = webViewTabFragment.getView();
2214 // Only wipe out the WebView if it exists.
2215 if (fragmentView != null) {
2216 // Get the nested scroll WebView from the tab fragment.
2217 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2219 // Clear SSL certificate preferences for this WebView.
2220 nestedScrollWebView.clearSslPreferences();
2222 // Clear the back/forward history for this WebView.
2223 nestedScrollWebView.clearHistory();
2225 // Destroy the internal state of `mainWebView`.
2226 nestedScrollWebView.destroy();
2230 // Clear the custom headers.
2231 customHeaders.clear();
2233 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2234 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2235 if (clearEverything) {
2237 // Delete the folder.
2238 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2240 // Wait until the process has finished.
2241 deleteAppWebviewProcess.waitFor();
2242 } catch (Exception exception) {
2243 // Do nothing if an error is thrown.
2247 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2248 if (Build.VERSION.SDK_INT >= 21) {
2249 finishAndRemoveTask();
2254 // Remove the terminated program from RAM. The status code is `0`.
2259 // Select the homepage based on the proxy through Orbot status.
2260 if (proxyThroughOrbot) {
2261 // Load the Tor homepage.
2262 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2264 // Load the normal homepage.
2265 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2270 if (currentWebView.canGoBack()) {
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 previous website in the history.
2278 currentWebView.goBack();
2283 if (currentWebView.canGoForward()) {
2284 // Reset the current domain name so that navigation works if third-party requests are blocked.
2285 currentWebView.resetCurrentDomainName();
2287 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2288 currentWebView.setNavigatingHistory(true);
2290 // Load the next website in the history.
2291 currentWebView.goForward();
2296 // Instantiate the URL history dialog.
2297 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2299 // Show the URL history dialog.
2300 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2304 // Populate the resource requests.
2305 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2307 // Create an intent to launch the Requests activity.
2308 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2310 // Add the block third-party requests status to the intent.
2311 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2314 startActivity(requestsIntent);
2317 case R.id.downloads:
2318 // Launch the system Download Manager.
2319 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2321 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2322 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2324 startActivity(downloadManagerIntent);
2328 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2329 reapplyDomainSettingsOnRestart = true;
2331 // Launch the domains activity.
2332 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2334 // Add the extra information to the intent.
2335 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2337 // Get the current certificate.
2338 SslCertificate sslCertificate = currentWebView.getCertificate();
2340 // Check to see if the SSL certificate is populated.
2341 if (sslCertificate != null) {
2342 // Extract the certificate to strings.
2343 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2344 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2345 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2346 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2347 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2348 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2349 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2350 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2352 // Add the certificate to the intent.
2353 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2354 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2355 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2356 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2357 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2358 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2359 domainsIntent.putExtra("ssl_start_date", startDateLong);
2360 domainsIntent.putExtra("ssl_end_date", endDateLong);
2363 // Check to see if the current IP addresses have been received.
2364 if (currentWebView.hasCurrentIpAddresses()) {
2365 // Add the current IP addresses to the intent.
2366 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2370 startActivity(domainsIntent);
2374 // Set the flag to reapply app settings on restart when returning from Settings.
2375 reapplyAppSettingsOnRestart = true;
2377 // Set the flag to reapply the domain settings on restart when returning from Settings.
2378 reapplyDomainSettingsOnRestart = true;
2380 // Launch the settings activity.
2381 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2382 startActivity(settingsIntent);
2385 case R.id.import_export:
2386 // Launch the import/export activity.
2387 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2388 startActivity(importExportIntent);
2392 // Launch the logcat activity.
2393 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2394 startActivity(logcatIntent);
2398 // Launch `GuideActivity`.
2399 Intent guideIntent = new Intent(this, GuideActivity.class);
2400 startActivity(guideIntent);
2404 // Create an intent to launch the about activity.
2405 Intent aboutIntent = new Intent(this, AboutActivity.class);
2407 // Create a string array for the blocklist versions.
2408 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],
2409 ultraPrivacy.get(0).get(0)[0]};
2411 // Add the blocklist versions to the intent.
2412 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2415 startActivity(aboutIntent);
2419 // Get a handle for the drawer layout.
2420 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2422 // Close the navigation drawer.
2423 drawerLayout.closeDrawer(GravityCompat.START);
2428 public void onPostCreate(Bundle savedInstanceState) {
2429 // Run the default commands.
2430 super.onPostCreate(savedInstanceState);
2432 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2433 actionBarDrawerToggle.syncState();
2437 public void onConfigurationChanged(Configuration newConfig) {
2438 // Run the default commands.
2439 super.onConfigurationChanged(newConfig);
2441 // Get the status bar pixel size.
2442 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2443 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2445 // Get the resource density.
2446 float screenDensity = getResources().getDisplayMetrics().density;
2448 // Recalculate the drawer header padding.
2449 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2450 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2451 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2453 // Reload the ad for the free flavor if not in full screen mode.
2454 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2455 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2456 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2459 // `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:
2460 // https://code.google.com/p/android/issues/detail?id=20493#c8
2461 // ActivityCompat.invalidateOptionsMenu(this);
2465 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2466 // Store the hit test result.
2467 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2469 // Create the URL strings.
2470 final String imageUrl;
2471 final String linkUrl;
2473 // Get handles for the system managers.
2474 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2475 FragmentManager fragmentManager = getSupportFragmentManager();
2476 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2478 // Remove the lint errors below that the clipboard manager might be null.
2479 assert clipboardManager != null;
2481 // Process the link according to the type.
2482 switch (hitTestResult.getType()) {
2483 // `SRC_ANCHOR_TYPE` is a link.
2484 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2485 // Get the target URL.
2486 linkUrl = hitTestResult.getExtra();
2488 // Set the target URL as the title of the `ContextMenu`.
2489 menu.setHeaderTitle(linkUrl);
2491 // Add a Load URL entry.
2492 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2501 // Add an Open with App entry.
2502 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2503 openWithApp(linkUrl);
2507 // Add an Open with Browser entry.
2508 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2509 openWithBrowser(linkUrl);
2513 // Add a Copy URL entry.
2514 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2515 // Save the link URL in a `ClipData`.
2516 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2518 // Set the `ClipData` as the clipboard's primary clip.
2519 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2523 // Add a Download URL entry.
2524 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2525 // Check if the download should be processed by an external app.
2526 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2527 openUrlWithExternalApp(linkUrl);
2528 } else { // Download with Android's download manager.
2529 // Check to see if the storage permission has already been granted.
2530 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2531 // Store the variables for future use by `onRequestPermissionsResult()`.
2532 downloadUrl = linkUrl;
2533 downloadContentDisposition = "none";
2534 downloadContentLength = -1;
2536 // Show a dialog if the user has previously denied the permission.
2537 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2538 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2539 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2541 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2542 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2543 } else { // Show the permission request directly.
2544 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2545 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2547 } else { // The storage permission has already been granted.
2548 // Get a handle for the download file alert dialog.
2549 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2551 // Show the download file alert dialog.
2552 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2558 // Add a Cancel entry, which by default closes the context menu.
2559 menu.add(R.string.cancel);
2562 case WebView.HitTestResult.EMAIL_TYPE:
2563 // Get the target URL.
2564 linkUrl = hitTestResult.getExtra();
2566 // Set the target URL as the title of the `ContextMenu`.
2567 menu.setHeaderTitle(linkUrl);
2569 // Add a Write Email entry.
2570 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2571 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2572 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2574 // Parse the url and set it as the data for the `Intent`.
2575 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2577 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2578 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2581 startActivity(emailIntent);
2585 // Add a Copy Email Address entry.
2586 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2587 // Save the email address in a `ClipData`.
2588 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2590 // Set the `ClipData` as the clipboard's primary clip.
2591 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2595 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2596 menu.add(R.string.cancel);
2599 // `IMAGE_TYPE` is an image.
2600 case WebView.HitTestResult.IMAGE_TYPE:
2601 // Get the image URL.
2602 imageUrl = hitTestResult.getExtra();
2604 // Set the image URL as the title of the `ContextMenu`.
2605 menu.setHeaderTitle(imageUrl);
2607 // Add a View Image entry.
2608 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2613 // Add a Download Image entry.
2614 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2615 // Check if the download should be processed by an external app.
2616 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2617 openUrlWithExternalApp(imageUrl);
2618 } else { // Download with Android's download manager.
2619 // Check to see if the storage permission has already been granted.
2620 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2621 // Store the image URL for use by `onRequestPermissionResult()`.
2622 downloadImageUrl = imageUrl;
2624 // Show a dialog if the user has previously denied the permission.
2625 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2626 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2627 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2629 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2630 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2631 } else { // Show the permission request directly.
2632 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2633 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2635 } else { // The storage permission has already been granted.
2636 // Get a handle for the download image alert dialog.
2637 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2639 // Show the download image alert dialog.
2640 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2646 // Add a Copy URL entry.
2647 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2648 // Save the image URL in a `ClipData`.
2649 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2651 // Set the `ClipData` as the clipboard's primary clip.
2652 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2656 // Add an Open with App entry.
2657 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2658 openWithApp(imageUrl);
2662 // Add an Open with Browser entry.
2663 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2664 openWithBrowser(imageUrl);
2668 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2669 menu.add(R.string.cancel);
2673 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2674 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2675 // Get the image URL.
2676 imageUrl = hitTestResult.getExtra();
2678 // Set the image URL as the title of the `ContextMenu`.
2679 menu.setHeaderTitle(imageUrl);
2681 // Add a `View Image` entry.
2682 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2687 // Add a `Download Image` entry.
2688 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2689 // Check if the download should be processed by an external app.
2690 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2691 openUrlWithExternalApp(imageUrl);
2692 } else { // Download with Android's download manager.
2693 // Check to see if the storage permission has already been granted.
2694 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2695 // Store the image URL for use by `onRequestPermissionResult()`.
2696 downloadImageUrl = imageUrl;
2698 // Show a dialog if the user has previously denied the permission.
2699 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2700 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2701 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2703 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2704 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2705 } else { // Show the permission request directly.
2706 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2707 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2709 } else { // The storage permission has already been granted.
2710 // Get a handle for the download image alert dialog.
2711 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2713 // Show the download image alert dialog.
2714 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2720 // Add a `Copy URL` entry.
2721 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2722 // Save the image URL in a `ClipData`.
2723 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2725 // Set the `ClipData` as the clipboard's primary clip.
2726 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2730 // Add an Open with App entry.
2731 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2732 openWithApp(imageUrl);
2736 // Add an Open with Browser entry.
2737 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2738 openWithBrowser(imageUrl);
2742 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2743 menu.add(R.string.cancel);
2749 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2750 // Get a handle for the bookmarks list view.
2751 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2753 // Get the views from the dialog fragment.
2754 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2755 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2757 // Extract the strings from the edit texts.
2758 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2759 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2761 // Create a favorite icon byte array output stream.
2762 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2764 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2765 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2767 // Convert the favorite icon byte array stream to a byte array.
2768 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2770 // Display the new bookmark below the current items in the (0 indexed) list.
2771 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2773 // Create the bookmark.
2774 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2776 // Update the bookmarks cursor with the current contents of this folder.
2777 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2779 // Update the list view.
2780 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2782 // Scroll to the new bookmark.
2783 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2787 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2788 // Get a handle for the bookmarks list view.
2789 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2791 // Get handles for the views in the dialog fragment.
2792 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2793 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2794 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2796 // Get new folder name string.
2797 String folderNameString = createFolderNameEditText.getText().toString();
2799 // Create a folder icon bitmap.
2800 Bitmap folderIconBitmap;
2802 // Set the folder icon bitmap according to the dialog.
2803 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2804 // Get the default folder icon drawable.
2805 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2807 // Convert the folder icon drawable to a bitmap drawable.
2808 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2810 // Convert the folder icon bitmap drawable to a bitmap.
2811 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2812 } else { // Use the WebView favorite icon.
2813 // Copy the favorite icon bitmap to the folder icon bitmap.
2814 folderIconBitmap = favoriteIconBitmap;
2817 // Create a folder icon byte array output stream.
2818 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2820 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2821 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2823 // Convert the folder icon byte array stream to a byte array.
2824 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2826 // Move all the bookmarks down one in the display order.
2827 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2828 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2829 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2832 // Create the folder, which will be placed at the top of the `ListView`.
2833 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2835 // Update the bookmarks cursor with the current contents of this folder.
2836 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2838 // Update the `ListView`.
2839 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2841 // Scroll to the new folder.
2842 bookmarksListView.setSelection(0);
2846 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2847 // Get handles for the views from `dialogFragment`.
2848 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2849 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2850 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2852 // Store the bookmark strings.
2853 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2854 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2856 // Update the bookmark.
2857 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2858 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2859 } else { // Update the bookmark using the `WebView` favorite icon.
2860 // Create a favorite icon byte array output stream.
2861 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2863 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2864 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2866 // Convert the favorite icon byte array stream to a byte array.
2867 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2869 // Update the bookmark and the favorite icon.
2870 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2873 // Update the bookmarks cursor with the current contents of this folder.
2874 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2876 // Update the list view.
2877 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2881 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2882 // Get handles for the views from `dialogFragment`.
2883 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2884 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2885 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2886 ImageView defaultFolderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2888 // Get the new folder name.
2889 String newFolderNameString = editFolderNameEditText.getText().toString();
2891 // Check if the favorite icon has changed.
2892 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2893 // Update the name in the database.
2894 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2895 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2896 // Create the new folder icon Bitmap.
2897 Bitmap folderIconBitmap;
2899 // Populate the new folder icon bitmap.
2900 if (defaultFolderIconRadioButton.isChecked()) {
2901 // Get the default folder icon drawable.
2902 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2904 // Convert the folder icon drawable to a bitmap drawable.
2905 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2907 // Convert the folder icon bitmap drawable to a bitmap.
2908 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2909 } else { // Use the `WebView` favorite icon.
2910 // Copy the favorite icon bitmap to the folder icon bitmap.
2911 folderIconBitmap = favoriteIconBitmap;