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 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
229 private boolean loadingNewIntent;
231 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
232 private boolean reapplyDomainSettingsOnRestart;
234 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
235 private boolean reapplyAppSettingsOnRestart;
237 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
238 private boolean displayingFullScreenVideo;
240 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
241 private BroadcastReceiver orbotStatusBroadcastReceiver;
243 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
244 private boolean waitingForOrbot;
246 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
247 private ActionBarDrawerToggle actionBarDrawerToggle;
249 // The color spans are used in `onCreate()` and `highlightUrlText()`.
250 private ForegroundColorSpan redColorSpan;
251 private ForegroundColorSpan initialGrayColorSpan;
252 private ForegroundColorSpan finalGrayColorSpan;
254 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
255 private int drawerHeaderPaddingLeftAndRight;
256 private int drawerHeaderPaddingTop;
257 private int drawerHeaderPaddingBottom;
259 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
260 // and `loadBookmarksFolder()`.
261 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
263 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
264 private Cursor bookmarksCursor;
266 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
267 private CursorAdapter bookmarksCursorAdapter;
269 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
270 private String oldFolderNameString;
272 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
273 private ValueCallback<Uri[]> fileChooserCallback;
275 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
276 private int defaultProgressViewStartOffset;
277 private int defaultProgressViewEndOffset;
279 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
280 private int swipeRefreshLayoutPaddingTop;
282 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
283 private String downloadUrl;
284 private String downloadContentDisposition;
285 private long downloadContentLength;
287 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
288 private String downloadImageUrl;
290 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
291 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
292 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
295 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
296 @SuppressLint("ClickableViewAccessibility")
297 protected void onCreate(Bundle savedInstanceState) {
298 // Get a handle for the shared preferences.
299 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
301 // Get the theme and screenshot preferences.
302 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
303 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
305 // Disable screenshots if not allowed.
306 if (!allowScreenshots) {
307 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
310 // Set the activity theme.
312 setTheme(R.style.PrivacyBrowserDark);
314 setTheme(R.style.PrivacyBrowserLight);
317 // Run the default commands.
318 super.onCreate(savedInstanceState);
320 // Set the content view.
321 setContentView(R.layout.main_framelayout);
323 // Get a handle for the input method.
324 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
326 // Remove the lint warning below that the input method manager might be null.
327 assert inputMethodManager != null;
329 // Get a handle for the toolbar.
330 Toolbar toolbar = findViewById(R.id.toolbar);
332 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
333 setSupportActionBar(toolbar);
335 // Get a handle for the action bar.
336 ActionBar actionBar = getSupportActionBar();
338 // This is needed to get rid of the Android Studio warning that the action bar might be null.
339 assert actionBar != null;
341 // Add the custom layout, which shows the URL text bar.
342 actionBar.setCustomView(R.layout.url_app_bar);
343 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
345 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
346 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
347 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
348 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
350 // Get handles for the URL views.
351 EditText urlEditText = findViewById(R.id.url_edittext);
353 // Remove the formatting from `urlTextBar` when the user is editing the text.
354 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
355 if (hasFocus) { // The user is editing the URL text box.
356 // Remove the highlighting.
357 urlEditText.getText().removeSpan(redColorSpan);
358 urlEditText.getText().removeSpan(initialGrayColorSpan);
359 urlEditText.getText().removeSpan(finalGrayColorSpan);
360 } else { // The user has stopped editing the URL text box.
361 // Move to the beginning of the string.
362 urlEditText.setSelection(0);
364 // Reapply the highlighting.
369 // Set the go button on the keyboard to load the URL in `urlTextBox`.
370 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
371 // If the event is a key-down event on the `enter` button, load the URL.
372 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
373 // Load the URL into the mainWebView and consume the event.
374 loadUrlFromTextBox();
376 // If the enter key was pressed, consume the event.
379 // If any other key was pressed, do not consume the event.
384 // Initialize the Orbot status and the waiting for Orbot trackers.
385 orbotStatus = "unknown";
386 waitingForOrbot = false;
388 // Create an Orbot status `BroadcastReceiver`.
389 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
391 public void onReceive(Context context, Intent intent) {
392 // Store the content of the status message in `orbotStatus`.
393 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
395 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
396 if (orbotStatus.equals("ON") && waitingForOrbot) {
397 // Reset the waiting for Orbot status.
398 waitingForOrbot = false;
400 // Get the intent that started the app.
401 Intent launchingIntent = getIntent();
403 // Get the information from the intent.
404 String launchingIntentAction = launchingIntent.getAction();
405 Uri launchingIntentUriData = launchingIntent.getData();
407 // If the intent action is a web search, perform the search.
408 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
409 // Create an encoded URL string.
410 String encodedUrlString;
412 // Sanitize the search input and convert it to a search.
414 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
415 } catch (UnsupportedEncodingException exception) {
416 encodedUrlString = "";
419 // Load the completed search URL.
420 loadUrl(searchURL + encodedUrlString);
421 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
422 // Load the URL from the intent.
423 loadUrl(launchingIntentUriData.toString());
424 } else { // The is no URL in the intent.
425 // Select the homepage based on the proxy through Orbot status.
426 if (proxyThroughOrbot) {
427 // Load the Tor homepage.
428 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
430 // Load the normal homepage.
431 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
438 // Register `orbotStatusBroadcastReceiver` on `this` context.
439 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
441 // Instantiate the blocklist helper.
442 BlockListHelper blockListHelper = new BlockListHelper();
444 // Parse the block lists.
445 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
446 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
447 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
448 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
449 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
451 // Get handles for views that need to be modified.
452 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
453 NavigationView navigationView = findViewById(R.id.navigationview);
454 TabLayout tabLayout = findViewById(R.id.tablayout);
455 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
456 ViewPager webViewPager = findViewById(R.id.webviewpager);
457 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
458 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
459 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
460 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
461 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
463 // Listen for touches on the navigation menu.
464 navigationView.setNavigationItemSelectedListener(this);
466 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
467 Menu navigationMenu = navigationView.getMenu();
468 MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
469 MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
470 MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
471 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
472 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
474 // Initialize the web view pager adapter.
475 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
477 // Set the pager adapter on the web view pager.
478 webViewPager.setAdapter(webViewPagerAdapter);
480 // Store up to 100 tabs in memory.
481 webViewPager.setOffscreenPageLimit(100);
483 // Update the web view pager every time a tab is modified.
484 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
486 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
491 public void onPageSelected(int position) {
492 // Close the find on page bar if it is open.
493 closeFindOnPage(null);
495 // Set the current WebView.
496 setCurrentWebView(position);
498 // 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.
499 if (tabLayout.getSelectedTabPosition() != position) {
500 // Create a handler to select the tab.
501 Handler selectTabHandler = new Handler();
503 // Create a runnable select the new tab.
504 Runnable selectTabRunnable = () -> {
505 // Get a handle for the tab.
506 TabLayout.Tab tab = tabLayout.getTabAt(position);
508 // Assert that the tab is not null.
515 // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
516 selectTabHandler.postDelayed(selectTabRunnable, 100);
521 public void onPageScrollStateChanged(int state) {
526 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
527 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
529 public void onTabSelected(TabLayout.Tab tab) {
530 // Select the same page in the view pager.
531 webViewPager.setCurrentItem(tab.getPosition());
535 public void onTabUnselected(TabLayout.Tab tab) {
540 public void onTabReselected(TabLayout.Tab tab) {
541 // Instantiate the View SSL Certificate dialog.
542 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
544 // Display the View SSL Certificate dialog.
545 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
549 // Add the first tab.
552 // 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.
553 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
555 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
556 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
557 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
558 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
560 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
561 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
562 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
563 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
566 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
567 launchBookmarksActivityFab.setOnClickListener(v -> {
568 // Get a copy of the favorite icon bitmap.
569 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
571 // Create a favorite icon byte array output stream.
572 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
574 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
575 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
577 // Convert the favorite icon byte array stream to a byte array.
578 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
580 // Create an intent to launch the bookmarks activity.
581 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
583 // Add the extra information to the intent.
584 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
585 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
586 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
587 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
590 startActivity(bookmarksIntent);
593 // Set the create new bookmark folder FAB to display an alert dialog.
594 createBookmarkFolderFab.setOnClickListener(v -> {
595 // Create a create bookmark folder dialog.
596 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
598 // Show the create bookmark folder dialog.
599 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
602 // Set the create new bookmark FAB to display an alert dialog.
603 createBookmarkFab.setOnClickListener(view -> {
604 // Instantiate the create bookmark dialog.
605 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
607 // Display the create bookmark dialog.
608 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
611 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
612 findOnPageEditText.addTextChangedListener(new TextWatcher() {
614 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
619 public void onTextChanged(CharSequence s, int start, int before, int count) {
624 public void afterTextChanged(Editable s) {
625 // 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.
626 if (currentWebView != null) {
627 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
632 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
633 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
634 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
635 // Hide the soft keyboard.
636 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
638 // Consume the event.
640 } else { // A different key was pressed.
641 // Do not consume the event.
646 // Implement swipe to refresh.
647 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
649 // Store the default progress view offsets for use later in `initializeWebView()`.
650 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
651 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
653 // Set the swipe to refresh color according to the theme.
655 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
656 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
658 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
661 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
662 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
663 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
665 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
666 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
668 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
669 currentBookmarksFolder = "";
671 // Load the home folder, which is `""` in the database.
672 loadBookmarksFolder();
674 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
675 // Convert the id from long to int to match the format of the bookmarks database.
676 int databaseID = (int) id;
678 // Get the bookmark cursor for this ID and move it to the first row.
679 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
680 bookmarkCursor.moveToFirst();
682 // Act upon the bookmark according to the type.
683 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
684 // Store the new folder name in `currentBookmarksFolder`.
685 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
687 // Load the new folder.
688 loadBookmarksFolder();
689 } else { // The selected bookmark is not a folder.
690 // Load the bookmark URL.
691 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
693 // Close the bookmarks drawer.
694 drawerLayout.closeDrawer(GravityCompat.END);
697 // Close the `Cursor`.
698 bookmarkCursor.close();
701 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
702 // Convert the database ID from `long` to `int`.
703 int databaseId = (int) id;
705 // Find out if the selected bookmark is a folder.
706 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
709 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
710 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
712 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
713 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
714 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
716 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
717 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
718 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
721 // Consume the event.
725 // Get the status bar pixel size.
726 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
727 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
729 // Get the resource density.
730 float screenDensity = getResources().getDisplayMetrics().density;
732 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
733 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
734 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
735 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
737 // The drawer listener is used to update the navigation menu.`
738 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
740 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
744 public void onDrawerOpened(@NonNull View drawerView) {
748 public void onDrawerClosed(@NonNull View drawerView) {
752 public void onDrawerStateChanged(int newState) {
753 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
754 // Get handles for the drawer headers.
755 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
756 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
758 // 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.
759 if (navigationHeaderTextView != null) {
760 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
763 // 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.
764 if (bookmarksHeaderTextView != null) {
765 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
768 // Update the navigation menu items.
769 navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
770 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
771 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
772 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
773 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
775 // Hide the keyboard (if displayed).
776 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
778 // 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.
779 urlEditText.clearFocus();
780 currentWebView.clearFocus();
785 // Create the hamburger icon at the start of the AppBar.
786 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
788 // 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).
789 customHeaders.put("X-Requested-With", "");
791 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
792 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
794 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
795 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
797 // Get a handle for the WebView.
798 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
800 // Store the default user agent.
801 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
803 // Destroy the bare WebView.
804 bareWebView.destroy();
808 protected void onNewIntent(Intent intent) {
809 // Get the information from the intent.
810 String intentAction = intent.getAction();
811 Uri intentUriData = intent.getData();
813 // 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.
814 if (intentUriData != null) {
815 // Sets the new intent as the activity intent, which replaces the one that originally started the app.
818 // Get the shared preferences.
819 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
821 // Add a new tab if specified in the preferences.
822 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) {
823 // Set the loading new intent flag.
824 loadingNewIntent = true;
830 // Create a URL string.
833 // If the intent action is a web search, perform the search.
834 if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
835 // Create an encoded URL string.
836 String encodedUrlString;
838 // Sanitize the search input and convert it to a search.
840 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
841 } catch (UnsupportedEncodingException exception) {
842 encodedUrlString = "";
845 // Add the base search URL.
846 url = searchURL + encodedUrlString;
847 } else { // The intent should contain a URL.
848 // Set the intent data as the URL.
849 url = intentUriData.toString();
855 // Get a handle for the drawer layout.
856 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
858 // Close the navigation drawer if it is open.
859 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
860 drawerLayout.closeDrawer(GravityCompat.START);
863 // Close the bookmarks drawer if it is open.
864 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
865 drawerLayout.closeDrawer(GravityCompat.END);
868 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
869 currentWebView.requestFocus();
874 public void onRestart() {
875 // Run the default commands.
878 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
879 if (proxyThroughOrbot) {
880 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
881 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
883 // Send the intent to the Orbot package.
884 orbotIntent.setPackage("org.torproject.android");
887 sendBroadcast(orbotIntent);
890 // Apply the app settings if returning from the Settings activity.
891 if (reapplyAppSettingsOnRestart) {
892 // Reset the reapply app settings on restart tracker.
893 reapplyAppSettingsOnRestart = false;
895 // Apply the app settings.
899 // Apply the domain settings if returning from the settings or domains activity.
900 if (reapplyDomainSettingsOnRestart) {
901 // Reset the reapply domain settings on restart tracker.
902 reapplyDomainSettingsOnRestart = false;
904 // Reapply the domain settings for each tab.
905 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
906 // Get the WebView tab fragment.
907 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
909 // Get the fragment view.
910 View fragmentView = webViewTabFragment.getView();
912 // Only reload the WebViews if they exist.
913 if (fragmentView != null) {
914 // Get the nested scroll WebView from the tab fragment.
915 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
917 // Reset the current domain name so the domain settings will be reapplied.
918 nestedScrollWebView.resetCurrentDomainName();
920 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
921 if (nestedScrollWebView.getUrl() != null) {
922 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
928 // Load the URL on restart (used when loading a bookmark).
929 if (loadUrlOnRestart) {
930 // Load the specified URL.
931 loadUrl(urlToLoadOnRestart);
933 // Reset the load on restart tracker.
934 loadUrlOnRestart = false;
937 // Update the bookmarks drawer if returning from the Bookmarks activity.
938 if (restartFromBookmarksActivity) {
939 // Get a handle for the drawer layout.
940 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
942 // Close the bookmarks drawer.
943 drawerLayout.closeDrawer(GravityCompat.END);
945 // Reload the bookmarks drawer.
946 loadBookmarksFolder();
948 // Reset `restartFromBookmarksActivity`.
949 restartFromBookmarksActivity = false;
952 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
953 updatePrivacyIcons(true);
956 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
958 public void onResume() {
959 // Run the default commands.
962 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
963 // Get the WebView tab fragment.
964 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
966 // Get the fragment view.
967 View fragmentView = webViewTabFragment.getView();
969 // Only resume the WebViews if they exist (they won't when the app is first created).
970 if (fragmentView != null) {
971 // Get the nested scroll WebView from the tab fragment.
972 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
974 // Resume the nested scroll WebView JavaScript timers.
975 nestedScrollWebView.resumeTimers();
977 // Resume the nested scroll WebView.
978 nestedScrollWebView.onResume();
982 // Display a message to the user if waiting for Orbot.
983 if (waitingForOrbot && !orbotStatus.equals("ON")) {
984 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
985 currentWebView.getSettings().setUseWideViewPort(false);
987 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
988 currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
991 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
992 // Get a handle for the root frame layouts.
993 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
995 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
996 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
998 /* Hide the system bars.
999 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1000 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1001 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1002 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1004 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1005 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1006 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
1008 AdHelper.resumeAd(findViewById(R.id.adview));
1013 public void onPause() {
1014 // Run the default commands.
1017 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1018 // Get the WebView tab fragment.
1019 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1021 // Get the fragment view.
1022 View fragmentView = webViewTabFragment.getView();
1024 // Only pause the WebViews if they exist (they won't when the app is first created).
1025 if (fragmentView != null) {
1026 // Get the nested scroll WebView from the tab fragment.
1027 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1029 // Pause the nested scroll WebView.
1030 nestedScrollWebView.onPause();
1032 // Pause the nested scroll WebView JavaScript timers.
1033 nestedScrollWebView.pauseTimers();
1037 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1038 if (BuildConfig.FLAVOR.contentEquals("free")) {
1040 AdHelper.pauseAd(findViewById(R.id.adview));
1045 public void onDestroy() {
1046 // Unregister the Orbot status broadcast receiver.
1047 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1049 // Close the bookmarks cursor and database.
1050 bookmarksCursor.close();
1051 bookmarksDatabaseHelper.close();
1053 // Run the default commands.
1058 public boolean onCreateOptionsMenu(Menu menu) {
1059 // Inflate the menu. This adds items to the action bar if it is present.
1060 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1062 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1065 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1066 updatePrivacyIcons(false);
1068 // Get handles for the menu items.
1069 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1070 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1071 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1072 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1073 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1074 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1075 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1077 // Only display third-party cookies if API >= 21
1078 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1080 // Only display the form data menu items if the API < 26.
1081 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1082 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1084 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1085 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1087 // Only show Ad Consent if this is the free flavor.
1088 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1090 // Get the shared preferences.
1091 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1093 // Get the dark theme and app bar preferences..
1094 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1095 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1097 // 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.
1098 if (displayAdditionalAppBarIcons) {
1099 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1100 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1101 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1102 } else { //Do not display the additional icons.
1103 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1104 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1105 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1108 // Replace Refresh with Stop if a URL is already loading.
1109 if (currentWebView != null && currentWebView.getProgress() != 100) {
1111 refreshMenuItem.setTitle(R.string.stop);
1113 // If the icon is displayed in the AppBar, set it according to the theme.
1114 if (displayAdditionalAppBarIcons) {
1116 refreshMenuItem.setIcon(R.drawable.close_dark);
1118 refreshMenuItem.setIcon(R.drawable.close_light);
1127 public boolean onPrepareOptionsMenu(Menu menu) {
1128 // Get handles for the menu items.
1129 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1130 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1131 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1132 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1133 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1134 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1135 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1136 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1137 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1138 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1139 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1140 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1141 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1142 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1143 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1144 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1145 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1146 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1147 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1148 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1149 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1151 // Get a handle for the cookie manager.
1152 CookieManager cookieManager = CookieManager.getInstance();
1154 // Initialize the current user agent string and the font size.
1155 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1158 // 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.
1159 if (currentWebView != null) {
1160 // Set the add or edit domain text.
1161 if (currentWebView.getDomainSettingsApplied()) {
1162 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1164 addOrEditDomain.setTitle(R.string.add_domain_settings);
1167 // Get the current user agent from the WebView.
1168 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1170 // Get the current font size from the
1171 fontSize = currentWebView.getSettings().getTextZoom();
1173 // Set the status of the menu item checkboxes.
1174 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1175 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1176 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1177 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1178 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1179 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1180 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1181 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1182 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1183 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1184 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1186 // Initialize the display names for the blocklists with the number of blocked requests.
1187 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1188 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1189 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1190 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1191 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1192 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1193 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1195 // Only modify third-party cookies if the API >= 21.
1196 if (Build.VERSION.SDK_INT >= 21) {
1197 // Set the status of the third-party cookies checkbox.
1198 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1200 // Enable third-party cookies if first-party cookies are enabled.
1201 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1204 // Enable DOM Storage if JavaScript is enabled.
1205 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1208 // Set the status of the menu item checkboxes.
1209 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1210 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1212 // Enable Clear Cookies if there are any.
1213 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1215 // 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`.
1216 String privateDataDirectoryString = getApplicationInfo().dataDir;
1218 // Get a count of the number of files in the Local Storage directory.
1219 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1220 int localStorageDirectoryNumberOfFiles = 0;
1221 if (localStorageDirectory.exists()) {
1222 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1225 // Get a count of the number of files in the IndexedDB directory.
1226 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1227 int indexedDBDirectoryNumberOfFiles = 0;
1228 if (indexedDBDirectory.exists()) {
1229 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1232 // Enable Clear DOM Storage if there is any.
1233 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1235 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1236 if (Build.VERSION.SDK_INT < 26) {
1237 // Get the WebView database.
1238 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1240 // Enable the clear form data menu item if there is anything to clear.
1241 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1244 // Enable Clear Data if any of the submenu items are enabled.
1245 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1247 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1248 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1250 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1251 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1252 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1253 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1254 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1255 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1256 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1257 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1258 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1259 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1260 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1261 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1262 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1263 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1264 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1265 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1266 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1267 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1268 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1269 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1270 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1271 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1272 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1273 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1274 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1275 } else { // Custom user agent.
1276 menu.findItem(R.id.user_agent_custom).setChecked(true);
1279 // Instantiate the font size title and the selected font size menu item.
1280 String fontSizeTitle;
1281 MenuItem selectedFontSizeMenuItem;
1283 // Prepare the font size title and current size menu item.
1286 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1287 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1291 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1292 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1296 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1297 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1301 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1302 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1306 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1307 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1311 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1312 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1316 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1317 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1321 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1322 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1326 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1327 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1331 // Set the font size title and select the current size menu item.
1332 fontSizeMenuItem.setTitle(fontSizeTitle);
1333 selectedFontSizeMenuItem.setChecked(true);
1335 // Run all the other default commands.
1336 super.onPrepareOptionsMenu(menu);
1338 // Display the menu.
1343 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1344 @SuppressLint("SetJavaScriptEnabled")
1345 public boolean onOptionsItemSelected(MenuItem menuItem) {
1346 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1347 if (inFullScreenBrowsingMode) {
1348 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1349 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1351 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1353 /* Hide the system bars.
1354 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1355 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1356 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1357 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1359 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1360 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1363 // Get the selected menu item ID.
1364 int menuItemId = menuItem.getItemId();
1366 // Get a handle for the shared preferences.
1367 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1369 // Get a handle for the cookie manager.
1370 CookieManager cookieManager = CookieManager.getInstance();
1372 // Run the commands that correlate to the selected menu item.
1373 switch (menuItemId) {
1374 case R.id.toggle_javascript:
1375 // Toggle the JavaScript status.
1376 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1378 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1379 updatePrivacyIcons(true);
1381 // Display a `Snackbar`.
1382 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1383 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1384 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1385 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1386 } else { // Privacy mode.
1387 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1390 // Reload the current WebView.
1391 currentWebView.reload();
1394 case R.id.add_or_edit_domain:
1395 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1396 // Reapply the domain settings on returning to `MainWebViewActivity`.
1397 reapplyDomainSettingsOnRestart = true;
1399 // Create an intent to launch the domains activity.
1400 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1402 // Add the extra information to the intent.
1403 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1404 domainsIntent.putExtra("close_on_back", true);
1405 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1407 // Get the current certificate.
1408 SslCertificate sslCertificate = currentWebView.getCertificate();
1410 // Check to see if the SSL certificate is populated.
1411 if (sslCertificate != null) {
1412 // Extract the certificate to strings.
1413 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1414 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1415 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1416 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1417 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1418 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1419 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1420 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1422 // Add the certificate to the intent.
1423 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1424 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1425 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1426 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1427 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1428 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1429 domainsIntent.putExtra("ssl_start_date", startDateLong);
1430 domainsIntent.putExtra("ssl_end_date", endDateLong);
1433 // Check to see if the current IP addresses have been received.
1434 if (currentWebView.hasCurrentIpAddresses()) {
1435 // Add the current IP addresses to the intent.
1436 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1440 startActivity(domainsIntent);
1441 } else { // Add a new domain.
1442 // Apply the new domain settings on returning to `MainWebViewActivity`.
1443 reapplyDomainSettingsOnRestart = true;
1445 // Get the current domain
1446 Uri currentUri = Uri.parse(currentWebView.getUrl());
1447 String currentDomain = currentUri.getHost();
1449 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1450 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1452 // Create the domain and store the database ID.
1453 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1455 // Create an intent to launch the domains activity.
1456 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1458 // Add the extra information to the intent.
1459 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1460 domainsIntent.putExtra("close_on_back", true);
1461 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1463 // Get the current certificate.
1464 SslCertificate sslCertificate = currentWebView.getCertificate();
1466 // Check to see if the SSL certificate is populated.
1467 if (sslCertificate != null) {
1468 // Extract the certificate to strings.
1469 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1470 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1471 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1472 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1473 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1474 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1475 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1476 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1478 // Add the certificate to the intent.
1479 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1480 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1481 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1482 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1483 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1484 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1485 domainsIntent.putExtra("ssl_start_date", startDateLong);
1486 domainsIntent.putExtra("ssl_end_date", endDateLong);
1489 // Check to see if the current IP addresses have been received.
1490 if (currentWebView.hasCurrentIpAddresses()) {
1491 // Add the current IP addresses to the intent.
1492 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1496 startActivity(domainsIntent);
1500 case R.id.toggle_first_party_cookies:
1501 // Switch the first-party cookie status.
1502 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1504 // Store the first-party cookie status.
1505 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1507 // Update the menu checkbox.
1508 menuItem.setChecked(cookieManager.acceptCookie());
1510 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1511 updatePrivacyIcons(true);
1513 // Display a snackbar.
1514 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1515 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1516 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1517 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1518 } else { // Privacy mode.
1519 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1522 // Reload the current WebView.
1523 currentWebView.reload();
1526 case R.id.toggle_third_party_cookies:
1527 if (Build.VERSION.SDK_INT >= 21) {
1528 // Switch the status of thirdPartyCookiesEnabled.
1529 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1531 // Update the menu checkbox.
1532 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1534 // Display a snackbar.
1535 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1536 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1538 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1541 // Reload the current WebView.
1542 currentWebView.reload();
1543 } // Else do nothing because SDK < 21.
1546 case R.id.toggle_dom_storage:
1547 // Toggle the status of domStorageEnabled.
1548 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1550 // Update the menu checkbox.
1551 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1553 // Update the privacy icon. `true` refreshes the app bar icons.
1554 updatePrivacyIcons(true);
1556 // Display a snackbar.
1557 if (currentWebView.getSettings().getDomStorageEnabled()) {
1558 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1560 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1563 // Reload the current WebView.
1564 currentWebView.reload();
1567 // Form data can be removed once the minimum API >= 26.
1568 case R.id.toggle_save_form_data:
1569 // Switch the status of saveFormDataEnabled.
1570 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1572 // Update the menu checkbox.
1573 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1575 // Display a snackbar.
1576 if (currentWebView.getSettings().getSaveFormData()) {
1577 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1579 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1582 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1583 updatePrivacyIcons(true);
1585 // Reload the current WebView.
1586 currentWebView.reload();
1589 case R.id.clear_cookies:
1590 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1591 .setAction(R.string.undo, v -> {
1592 // Do nothing because everything will be handled by `onDismissed()` below.
1594 .addCallback(new Snackbar.Callback() {
1595 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1597 public void onDismissed(Snackbar snackbar, int event) {
1598 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1599 // Delete the cookies, which command varies by SDK.
1600 if (Build.VERSION.SDK_INT < 21) {
1601 cookieManager.removeAllCookie();
1603 cookieManager.removeAllCookies(null);
1611 case R.id.clear_dom_storage:
1612 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1613 .setAction(R.string.undo, v -> {
1614 // Do nothing because everything will be handled by `onDismissed()` below.
1616 .addCallback(new Snackbar.Callback() {
1617 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1619 public void onDismissed(Snackbar snackbar, int event) {
1620 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1621 // Delete the DOM Storage.
1622 WebStorage webStorage = WebStorage.getInstance();
1623 webStorage.deleteAllData();
1625 // Initialize a handler to manually delete the DOM storage files and directories.
1626 Handler deleteDomStorageHandler = new Handler();
1628 // Setup a runnable to manually delete the DOM storage files and directories.
1629 Runnable deleteDomStorageRunnable = () -> {
1631 // Get a handle for the runtime.
1632 Runtime runtime = Runtime.getRuntime();
1634 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1635 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1636 String privateDataDirectoryString = getApplicationInfo().dataDir;
1638 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1639 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1641 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1642 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1643 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1644 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1645 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1647 // Wait for the processes to finish.
1648 deleteLocalStorageProcess.waitFor();
1649 deleteIndexProcess.waitFor();
1650 deleteQuotaManagerProcess.waitFor();
1651 deleteQuotaManagerJournalProcess.waitFor();
1652 deleteDatabasesProcess.waitFor();
1653 } catch (Exception exception) {
1654 // Do nothing if an error is thrown.
1658 // Manually delete the DOM storage files after 200 milliseconds.
1659 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1666 // Form data can be remove once the minimum API >= 26.
1667 case R.id.clear_form_data:
1668 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1669 .setAction(R.string.undo, v -> {
1670 // Do nothing because everything will be handled by `onDismissed()` below.
1672 .addCallback(new Snackbar.Callback() {
1673 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1675 public void onDismissed(Snackbar snackbar, int event) {
1676 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1677 // Delete the form data.
1678 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1679 mainWebViewDatabase.clearFormData();
1687 // Toggle the EasyList status.
1688 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1690 // Update the menu checkbox.
1691 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1693 // Reload the current WebView.
1694 currentWebView.reload();
1697 case R.id.easyprivacy:
1698 // Toggle the EasyPrivacy status.
1699 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1701 // Update the menu checkbox.
1702 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1704 // Reload the current WebView.
1705 currentWebView.reload();
1708 case R.id.fanboys_annoyance_list:
1709 // Toggle Fanboy's Annoyance List status.
1710 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1712 // Update the menu checkbox.
1713 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1715 // Update the staus of Fanboy's Social Blocking List.
1716 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1717 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1719 // Reload the current WebView.
1720 currentWebView.reload();
1723 case R.id.fanboys_social_blocking_list:
1724 // Toggle Fanboy's Social Blocking List status.
1725 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1727 // Update the menu checkbox.
1728 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1730 // Reload the current WebView.
1731 currentWebView.reload();
1734 case R.id.ultraprivacy:
1735 // Toggle the UltraPrivacy status.
1736 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1738 // Update the menu checkbox.
1739 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1741 // Reload the current WebView.
1742 currentWebView.reload();
1745 case R.id.block_all_third_party_requests:
1746 //Toggle the third-party requests blocker status.
1747 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1749 // Update the menu checkbox.
1750 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1752 // Reload the current WebView.
1753 currentWebView.reload();
1756 case R.id.user_agent_privacy_browser:
1757 // Update the user agent.
1758 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1760 // Reload the current WebView.
1761 currentWebView.reload();
1764 case R.id.user_agent_webview_default:
1765 // Update the user agent.
1766 currentWebView.getSettings().setUserAgentString("");
1768 // Reload the current WebView.
1769 currentWebView.reload();
1772 case R.id.user_agent_firefox_on_android:
1773 // Update the user agent.
1774 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1776 // Reload the current WebView.
1777 currentWebView.reload();
1780 case R.id.user_agent_chrome_on_android:
1781 // Update the user agent.
1782 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1784 // Reload the current WebView.
1785 currentWebView.reload();
1788 case R.id.user_agent_safari_on_ios:
1789 // Update the user agent.
1790 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1792 // Reload the current WebView.
1793 currentWebView.reload();
1796 case R.id.user_agent_firefox_on_linux:
1797 // Update the user agent.
1798 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1800 // Reload the current WebView.
1801 currentWebView.reload();
1804 case R.id.user_agent_chromium_on_linux:
1805 // Update the user agent.
1806 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1808 // Reload the current WebView.
1809 currentWebView.reload();
1812 case R.id.user_agent_firefox_on_windows:
1813 // Update the user agent.
1814 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1816 // Reload the current WebView.
1817 currentWebView.reload();
1820 case R.id.user_agent_chrome_on_windows:
1821 // Update the user agent.
1822 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1824 // Reload the current WebView.
1825 currentWebView.reload();
1828 case R.id.user_agent_edge_on_windows:
1829 // Update the user agent.
1830 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1832 // Reload the current WebView.
1833 currentWebView.reload();
1836 case R.id.user_agent_internet_explorer_on_windows:
1837 // Update the user agent.
1838 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1840 // Reload the current WebView.
1841 currentWebView.reload();
1844 case R.id.user_agent_safari_on_macos:
1845 // Update the user agent.
1846 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1848 // Reload the current WebView.
1849 currentWebView.reload();
1852 case R.id.user_agent_custom:
1853 // Update the user agent.
1854 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1856 // Reload the current WebView.
1857 currentWebView.reload();
1860 case R.id.font_size_twenty_five_percent:
1861 currentWebView.getSettings().setTextZoom(25);
1864 case R.id.font_size_fifty_percent:
1865 currentWebView.getSettings().setTextZoom(50);
1868 case R.id.font_size_seventy_five_percent:
1869 currentWebView.getSettings().setTextZoom(75);
1872 case R.id.font_size_one_hundred_percent:
1873 currentWebView.getSettings().setTextZoom(100);
1876 case R.id.font_size_one_hundred_twenty_five_percent:
1877 currentWebView.getSettings().setTextZoom(125);
1880 case R.id.font_size_one_hundred_fifty_percent:
1881 currentWebView.getSettings().setTextZoom(150);
1884 case R.id.font_size_one_hundred_seventy_five_percent:
1885 currentWebView.getSettings().setTextZoom(175);
1888 case R.id.font_size_two_hundred_percent:
1889 currentWebView.getSettings().setTextZoom(200);
1892 case R.id.swipe_to_refresh:
1893 // Toggle the stored status of swipe to refresh.
1894 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1896 // Get a handle for the swipe refresh layout.
1897 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1899 // Update the swipe refresh layout.
1900 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1901 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.
1902 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1903 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1904 } else { // For API < 23, the swipe refresh layout is always enabled.
1905 // Enable the swipe refresh layout.
1906 swipeRefreshLayout.setEnabled(true);
1908 } else { // Swipe to refresh is disabled.
1909 // Disable the swipe refresh layout.
1910 swipeRefreshLayout.setEnabled(false);
1914 case R.id.display_images:
1915 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1916 // Disable loading of images.
1917 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1919 // Reload the website to remove existing images.
1920 currentWebView.reload();
1921 } else { // Images are not currently loaded automatically.
1922 // Enable loading of images. Missing images will be loaded without the need for a reload.
1923 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1927 case R.id.night_mode:
1928 // Toggle night mode.
1929 currentWebView.setNightMode(!currentWebView.getNightMode());
1931 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1932 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1933 // Enable JavaScript.
1934 currentWebView.getSettings().setJavaScriptEnabled(true);
1935 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1936 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1937 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1938 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1939 // Apply the JavaScript preference.
1940 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1943 // Update the privacy icons.
1944 updatePrivacyIcons(false);
1946 // Reload the website.
1947 currentWebView.reload();
1950 case R.id.find_on_page:
1951 // Get a handle for the views.
1952 Toolbar toolbar = findViewById(R.id.toolbar);
1953 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1954 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1956 // Set the minimum height of the find on page linear layout to match the toolbar.
1957 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1959 // Hide the toolbar.
1960 toolbar.setVisibility(View.GONE);
1962 // Show the find on page linear layout.
1963 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1965 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1966 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1967 findOnPageEditText.postDelayed(() -> {
1968 // Set the focus on `findOnPageEditText`.
1969 findOnPageEditText.requestFocus();
1971 // Get a handle for the input method manager.
1972 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1974 // Remove the lint warning below that the input method manager might be null.
1975 assert inputMethodManager != null;
1977 // Display the keyboard. `0` sets no input flags.
1978 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1982 case R.id.view_source:
1983 // Create an intent to launch the view source activity.
1984 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1986 // Add the variables to the intent.
1987 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1988 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1991 startActivity(viewSourceIntent);
1994 case R.id.share_url:
1995 // Setup the share string.
1996 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1998 // Create the share intent.
1999 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2000 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2001 shareIntent.setType("text/plain");
2004 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2008 // Get a print manager instance.
2009 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2011 // Remove the lint error below that print manager might be null.
2012 assert printManager != null;
2014 // Create a print document adapter from the current WebView.
2015 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2017 // Print the document.
2018 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2021 case R.id.open_with_app:
2022 openWithApp(currentWebView.getUrl());
2025 case R.id.open_with_browser:
2026 openWithBrowser(currentWebView.getUrl());
2029 case R.id.add_to_homescreen:
2030 // Instantiate the create home screen shortcut dialog.
2031 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2032 currentWebView.getFavoriteOrDefaultIcon());
2034 // Show the create home screen shortcut dialog.
2035 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2038 case R.id.proxy_through_orbot:
2039 // Toggle the proxy through Orbot variable.
2040 proxyThroughOrbot = !proxyThroughOrbot;
2042 // Apply the proxy through Orbot settings.
2043 applyProxyThroughOrbot(true);
2047 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2048 // Reload the current WebView.
2049 currentWebView.reload();
2050 } else { // The stop button was pushed.
2051 // Stop the loading of the WebView.
2052 currentWebView.stopLoading();
2056 case R.id.ad_consent:
2057 // Display the ad consent dialog.
2058 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2059 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2063 // Don't consume the event.
2064 return super.onOptionsItemSelected(menuItem);
2068 // removeAllCookies is deprecated, but it is required for API < 21.
2070 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2071 // Get the menu item ID.
2072 int menuItemId = menuItem.getItemId();
2074 // Get a handle for the shared preferences.
2075 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2077 // Run the commands that correspond to the selected menu item.
2078 switch (menuItemId) {
2079 case R.id.close_tab:
2080 // Get a handle for the tab layout and the view pager.
2081 TabLayout tabLayout = findViewById(R.id.tablayout);
2082 ViewPager webViewPager = findViewById(R.id.webviewpager);
2084 // Get the current tab number.
2085 int currentTabNumber = tabLayout.getSelectedTabPosition();
2087 // Delete the current tab.
2088 tabLayout.removeTabAt(currentTabNumber);
2090 // 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.
2091 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2092 setCurrentWebView(currentTabNumber);
2096 case R.id.clear_and_exit:
2097 // Close the bookmarks cursor and database.
2098 bookmarksCursor.close();
2099 bookmarksDatabaseHelper.close();
2101 // Get the status of the clear everything preference.
2102 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2104 // Get a handle for the runtime.
2105 Runtime runtime = Runtime.getRuntime();
2107 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
2108 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
2109 String privateDataDirectoryString = getApplicationInfo().dataDir;
2112 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2113 // The command to remove cookies changed slightly in API 21.
2114 if (Build.VERSION.SDK_INT >= 21) {
2115 CookieManager.getInstance().removeAllCookies(null);
2117 CookieManager.getInstance().removeAllCookie();
2120 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2122 // Two commands must be used because `Runtime.exec()` does not like `*`.
2123 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2124 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2126 // Wait until the processes have finished.
2127 deleteCookiesProcess.waitFor();
2128 deleteCookiesJournalProcess.waitFor();
2129 } catch (Exception exception) {
2130 // Do nothing if an error is thrown.
2134 // Clear DOM storage.
2135 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2136 // Ask `WebStorage` to clear the DOM storage.
2137 WebStorage webStorage = WebStorage.getInstance();
2138 webStorage.deleteAllData();
2140 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2142 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2143 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2145 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2146 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2147 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2148 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2149 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2151 // Wait until the processes have finished.
2152 deleteLocalStorageProcess.waitFor();
2153 deleteIndexProcess.waitFor();
2154 deleteQuotaManagerProcess.waitFor();
2155 deleteQuotaManagerJournalProcess.waitFor();
2156 deleteDatabaseProcess.waitFor();
2157 } catch (Exception exception) {
2158 // Do nothing if an error is thrown.
2162 // Clear form data if the API < 26.
2163 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2164 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2165 webViewDatabase.clearFormData();
2167 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2169 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2170 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2171 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2173 // Wait until the processes have finished.
2174 deleteWebDataProcess.waitFor();
2175 deleteWebDataJournalProcess.waitFor();
2176 } catch (Exception exception) {
2177 // Do nothing if an error is thrown.
2182 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2183 // Clear the cache from each WebView.
2184 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2185 // Get the WebView tab fragment.
2186 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2188 // Get the fragment view.
2189 View fragmentView = webViewTabFragment.getView();
2191 // Only clear the cache if the WebView exists.
2192 if (fragmentView != null) {
2193 // Get the nested scroll WebView from the tab fragment.
2194 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2196 // Clear the cache for this WebView.
2197 nestedScrollWebView.clearCache(true);
2201 // Manually delete the cache directories.
2203 // Delete the main cache directory.
2204 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2206 // Delete the secondary `Service Worker` cache directory.
2207 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2208 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2210 // Wait until the processes have finished.
2211 deleteCacheProcess.waitFor();
2212 deleteServiceWorkerProcess.waitFor();
2213 } catch (Exception exception) {
2214 // Do nothing if an error is thrown.
2218 // Wipe out each WebView.
2219 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2220 // Get the WebView tab fragment.
2221 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2223 // Get the fragment view.
2224 View fragmentView = webViewTabFragment.getView();
2226 // Only wipe out the WebView if it exists.
2227 if (fragmentView != null) {
2228 // Get the nested scroll WebView from the tab fragment.
2229 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2231 // Clear SSL certificate preferences for this WebView.
2232 nestedScrollWebView.clearSslPreferences();
2234 // Clear the back/forward history for this WebView.
2235 nestedScrollWebView.clearHistory();
2237 // Destroy the internal state of `mainWebView`.
2238 nestedScrollWebView.destroy();
2242 // Clear the custom headers.
2243 customHeaders.clear();
2245 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2246 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2247 if (clearEverything) {
2249 // Delete the folder.
2250 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2252 // Wait until the process has finished.
2253 deleteAppWebviewProcess.waitFor();
2254 } catch (Exception exception) {
2255 // Do nothing if an error is thrown.
2259 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2260 if (Build.VERSION.SDK_INT >= 21) {
2261 finishAndRemoveTask();
2266 // Remove the terminated program from RAM. The status code is `0`.
2271 // Select the homepage based on the proxy through Orbot status.
2272 if (proxyThroughOrbot) {
2273 // Load the Tor homepage.
2274 loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2276 // Load the normal homepage.
2277 loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2282 if (currentWebView.canGoBack()) {
2283 // Reset the current domain name so that navigation works if third-party requests are blocked.
2284 currentWebView.resetCurrentDomainName();
2286 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2287 currentWebView.setNavigatingHistory(true);
2289 // Load the previous website in the history.
2290 currentWebView.goBack();
2295 if (currentWebView.canGoForward()) {
2296 // Reset the current domain name so that navigation works if third-party requests are blocked.
2297 currentWebView.resetCurrentDomainName();
2299 // Set navigating history so that the domain settings are applied when the new URL is loaded.
2300 currentWebView.setNavigatingHistory(true);
2302 // Load the next website in the history.
2303 currentWebView.goForward();
2308 // Instantiate the URL history dialog.
2309 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2311 // Show the URL history dialog.
2312 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2316 // Populate the resource requests.
2317 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2319 // Create an intent to launch the Requests activity.
2320 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2322 // Add the block third-party requests status to the intent.
2323 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2326 startActivity(requestsIntent);
2329 case R.id.downloads:
2330 // Launch the system Download Manager.
2331 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2333 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2334 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2336 startActivity(downloadManagerIntent);
2340 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2341 reapplyDomainSettingsOnRestart = true;
2343 // Launch the domains activity.
2344 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2346 // Add the extra information to the intent.
2347 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2349 // Get the current certificate.
2350 SslCertificate sslCertificate = currentWebView.getCertificate();
2352 // Check to see if the SSL certificate is populated.
2353 if (sslCertificate != null) {
2354 // Extract the certificate to strings.
2355 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2356 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2357 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2358 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2359 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2360 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2361 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2362 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2364 // Add the certificate to the intent.
2365 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2366 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2367 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2368 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2369 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2370 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2371 domainsIntent.putExtra("ssl_start_date", startDateLong);
2372 domainsIntent.putExtra("ssl_end_date", endDateLong);
2375 // Check to see if the current IP addresses have been received.
2376 if (currentWebView.hasCurrentIpAddresses()) {
2377 // Add the current IP addresses to the intent.
2378 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2382 startActivity(domainsIntent);
2386 // Set the flag to reapply app settings on restart when returning from Settings.
2387 reapplyAppSettingsOnRestart = true;
2389 // Set the flag to reapply the domain settings on restart when returning from Settings.
2390 reapplyDomainSettingsOnRestart = true;
2392 // Launch the settings activity.
2393 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2394 startActivity(settingsIntent);
2397 case R.id.import_export:
2398 // Launch the import/export activity.
2399 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2400 startActivity(importExportIntent);
2404 // Launch the logcat activity.
2405 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2406 startActivity(logcatIntent);
2410 // Launch `GuideActivity`.
2411 Intent guideIntent = new Intent(this, GuideActivity.class);
2412 startActivity(guideIntent);
2416 // Create an intent to launch the about activity.
2417 Intent aboutIntent = new Intent(this, AboutActivity.class);
2419 // Create a string array for the blocklist versions.
2420 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],
2421 ultraPrivacy.get(0).get(0)[0]};
2423 // Add the blocklist versions to the intent.
2424 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2427 startActivity(aboutIntent);
2431 // Get a handle for the drawer layout.
2432 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2434 // Close the navigation drawer.
2435 drawerLayout.closeDrawer(GravityCompat.START);
2440 public void onPostCreate(Bundle savedInstanceState) {
2441 // Run the default commands.
2442 super.onPostCreate(savedInstanceState);
2444 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2445 actionBarDrawerToggle.syncState();
2449 public void onConfigurationChanged(Configuration newConfig) {
2450 // Run the default commands.
2451 super.onConfigurationChanged(newConfig);
2453 // Get the status bar pixel size.
2454 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2455 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2457 // Get the resource density.
2458 float screenDensity = getResources().getDisplayMetrics().density;
2460 // Recalculate the drawer header padding.
2461 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2462 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2463 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2465 // Reload the ad for the free flavor if not in full screen mode.
2466 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2467 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2468 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2471 // `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:
2472 // https://code.google.com/p/android/issues/detail?id=20493#c8
2473 // ActivityCompat.invalidateOptionsMenu(this);
2477 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2478 // Store the hit test result.
2479 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2481 // Create the URL strings.
2482 final String imageUrl;
2483 final String linkUrl;
2485 // Get handles for the system managers.
2486 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2487 FragmentManager fragmentManager = getSupportFragmentManager();
2488 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2490 // Remove the lint errors below that the clipboard manager might be null.
2491 assert clipboardManager != null;
2493 // Process the link according to the type.
2494 switch (hitTestResult.getType()) {
2495 // `SRC_ANCHOR_TYPE` is a link.
2496 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2497 // Get the target URL.
2498 linkUrl = hitTestResult.getExtra();
2500 // Set the target URL as the title of the `ContextMenu`.
2501 menu.setHeaderTitle(linkUrl);
2503 // Add a Load URL entry.
2504 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2513 // Add an Open with App entry.
2514 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2515 openWithApp(linkUrl);
2519 // Add an Open with Browser entry.
2520 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2521 openWithBrowser(linkUrl);
2525 // Add a Copy URL entry.
2526 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2527 // Save the link URL in a `ClipData`.
2528 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2530 // Set the `ClipData` as the clipboard's primary clip.
2531 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2535 // Add a Download URL entry.
2536 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2537 // Check if the download should be processed by an external app.
2538 if (sharedPreferences.getBoolean("download_with_external_app", false)) { // Download with an external app.
2539 openUrlWithExternalApp(linkUrl);
2540 } else { // Download with Android's download manager.
2541 // Check to see if the storage permission has already been granted.
2542 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2543 // Store the variables for future use by `onRequestPermissionsResult()`.
2544 downloadUrl = linkUrl;
2545 downloadContentDisposition = "none";
2546 downloadContentLength = -1;
2548 // Show a dialog if the user has previously denied the permission.
2549 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2550 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2551 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2553 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2554 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2555 } else { // Show the permission request directly.
2556 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2557 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2559 } else { // The storage permission has already been granted.
2560 // Get a handle for the download file alert dialog.
2561 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2563 // Show the download file alert dialog.
2564 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2570 // Add a Cancel entry, which by default closes the context menu.
2571 menu.add(R.string.cancel);
2574 case WebView.HitTestResult.EMAIL_TYPE:
2575 // Get the target URL.
2576 linkUrl = hitTestResult.getExtra();
2578 // Set the target URL as the title of the `ContextMenu`.
2579 menu.setHeaderTitle(linkUrl);
2581 // Add a Write Email entry.
2582 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2583 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2584 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2586 // Parse the url and set it as the data for the `Intent`.
2587 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2589 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2590 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2593 startActivity(emailIntent);
2597 // Add a Copy Email Address entry.
2598 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2599 // Save the email address in a `ClipData`.
2600 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2602 // Set the `ClipData` as the clipboard's primary clip.
2603 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2607 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2608 menu.add(R.string.cancel);