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.WebBackForwardList;
75 import android.webkit.WebChromeClient;
76 import android.webkit.WebResourceResponse;
77 import android.webkit.WebSettings;
78 import android.webkit.WebStorage;
79 import android.webkit.WebView;
80 import android.webkit.WebViewClient;
81 import android.webkit.WebViewDatabase;
82 import android.widget.ArrayAdapter;
83 import android.widget.CursorAdapter;
84 import android.widget.EditText;
85 import android.widget.FrameLayout;
86 import android.widget.ImageView;
87 import android.widget.LinearLayout;
88 import android.widget.ListView;
89 import android.widget.ProgressBar;
90 import android.widget.RadioButton;
91 import android.widget.RelativeLayout;
92 import android.widget.TextView;
94 import androidx.annotation.NonNull;
95 import androidx.appcompat.app.ActionBar;
96 import androidx.appcompat.app.ActionBarDrawerToggle;
97 import androidx.appcompat.app.AppCompatActivity;
98 import androidx.appcompat.widget.Toolbar;
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.floatingactionbutton.FloatingActionButton;
109 import com.google.android.material.navigation.NavigationView;
110 import com.google.android.material.snackbar.Snackbar;
111 import com.google.android.material.tabs.TabLayout;
113 import com.stoutner.privacybrowser.BuildConfig;
114 import com.stoutner.privacybrowser.R;
115 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
116 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
117 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
118 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
120 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
121 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
123 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
124 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
125 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
126 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
127 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
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 // TODO. Store up reloads for tabs that are not visible.
158 // TODO. New tabs are white in dark mode.
160 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
161 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
162 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
163 EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener,
164 PinnedMismatchDialog.PinnedMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
166 // `darkTheme` is public static so it can be accessed from everywhere.
167 public static boolean darkTheme;
169 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
170 public static boolean allowScreenshots;
172 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
173 public static String orbotStatus;
175 // The WebView pager adapter is accessed from `PinnedMismatchDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
176 public static WebViewPagerAdapter webViewPagerAdapter;
178 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is used in `onRestart()`
179 public static boolean reloadOnRestart;
181 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
182 public static boolean loadUrlOnRestart;
183 public static String urlToLoadOnRestart;
185 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
186 public static boolean restartFromBookmarksActivity;
188 // The blocklist versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
189 public static String easyListVersion;
190 public static String easyPrivacyVersion;
191 public static String fanboysAnnoyanceVersion;
192 public static String fanboysSocialVersion;
193 public static String ultraPrivacyVersion;
195 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
196 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
197 public static String currentBookmarksFolder;
199 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
200 public final static int UNRECOGNIZED_USER_AGENT = -1;
201 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
202 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
203 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
204 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
205 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
209 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
210 private boolean navigatingHistory; // TODO.
212 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
213 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
214 private NestedScrollWebView currentWebView;
216 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
217 private final Map<String, String> customHeaders = new HashMap<>();
219 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
220 private boolean firstPartyCookiesEnabled;
222 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyProxyThroughOrbot()`.
223 private String homepage; // TODO ?
225 // `searchURL` is used in `loadURLFromTextBox()` and `applyProxyThroughOrbot()`.
226 private String searchURL; // TODO ?
228 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
229 private Menu optionsMenu;
231 // TODO. This could probably be removed.
232 // The blocklist helper is used in `onCreate()` and `WebViewPagerAdapter`.
233 private BlockListHelper blockListHelper;
235 // The blocklists are populated in `onCreate()` and accessed from `WebViewPagerAdapter`.
236 private ArrayList<List<String[]>> easyList;
237 private ArrayList<List<String[]>> easyPrivacy;
238 private ArrayList<List<String[]>> fanboysAnnoyanceList;
239 private ArrayList<List<String[]>> fanboysSocialList;
240 private ArrayList<List<String[]>> ultraPrivacy;
242 // The blocklist menu items are used in `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `initializeWebView()`. // TODO.
243 private MenuItem blocklistsMenuItem;
244 private MenuItem easyListMenuItem;
245 private MenuItem easyPrivacyMenuItem;
246 private MenuItem fanboysAnnoyanceListMenuItem;
247 private MenuItem fanboysSocialBlockingListMenuItem;
248 private MenuItem ultraPrivacyMenuItem;
249 private MenuItem blockAllThirdPartyRequestsMenuItem;
251 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
252 private String webViewDefaultUserAgent;
254 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
255 private boolean proxyThroughOrbot;
257 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
258 private boolean incognitoModeEnabled; // TODO.
260 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
261 private boolean fullScreenBrowsingModeEnabled; // TODO.
263 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
264 private boolean inFullScreenBrowsingMode;
266 // Hide app bar is used in `onCreate()` and `applyAppSettings()`.
267 private boolean hideAppBar; // TODO.
269 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
270 private boolean reapplyDomainSettingsOnRestart;
272 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
273 private boolean reapplyAppSettingsOnRestart;
275 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
276 private boolean displayingFullScreenVideo;
278 // `downloadWithExternalApp` is used in `onCreate()`, `onCreateContextMenu()`, and `applyDomainSettings()`.
279 private boolean downloadWithExternalApp; // TODO.
281 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
282 private BroadcastReceiver orbotStatusBroadcastReceiver;
284 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
285 private boolean waitingForOrbot;
287 // `domainSettingsJavaScriptEnabled` is used in `onOptionsItemSelected()` and `applyDomainSettings()`.
288 private Boolean domainSettingsJavaScriptEnabled; // TODO.
290 // `waitingForOrbotHtmlString` is used in `onCreate()` and `applyProxyThroughOrbot()`.
291 private String waitingForOrbotHtmlString; // TODO.
293 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
294 private String privateDataDirectoryString; // TODO.
296 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
297 private ActionBarDrawerToggle actionBarDrawerToggle;
299 // The color spans are used in `onCreate()` and `highlightUrlText()`.
300 private ForegroundColorSpan redColorSpan;
301 private ForegroundColorSpan initialGrayColorSpan;
302 private ForegroundColorSpan finalGrayColorSpan;
304 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
305 private int drawerHeaderPaddingLeftAndRight;
306 private int drawerHeaderPaddingTop;
307 private int drawerHeaderPaddingBottom;
309 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
310 private SslErrorHandler sslErrorHandler; // TODO.
312 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
313 private static HttpAuthHandler httpAuthHandler; // TODO.
315 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
316 // and `loadBookmarksFolder()`.
317 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
319 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
320 private Cursor bookmarksCursor;
322 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
323 private CursorAdapter bookmarksCursorAdapter;
325 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
326 private String oldFolderNameString;
328 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
329 private ValueCallback<Uri[]> fileChooserCallback;
331 // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
332 private String downloadUrl;
333 private String downloadContentDisposition;
334 private long downloadContentLength;
336 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
337 private String downloadImageUrl;
339 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
340 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
341 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
344 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
345 @SuppressLint("ClickableViewAccessibility")
346 protected void onCreate(Bundle savedInstanceState) {
347 // Get a handle for the shared preferences.
348 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
350 // Get the theme and screenshot preferences.
351 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
352 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
354 // Disable screenshots if not allowed.
355 if (!allowScreenshots) {
356 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
359 // Set the activity theme.
361 setTheme(R.style.PrivacyBrowserDark);
363 setTheme(R.style.PrivacyBrowserLight);
366 // Run the default commands.
367 super.onCreate(savedInstanceState);
369 // Set the content view.
370 setContentView(R.layout.main_framelayout);
372 // Get a handle for the input method.
373 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
375 // Remove the lint warning below that the input method manager might be null.
376 assert inputMethodManager != null;
378 // Get a handle for the toolbar.
379 Toolbar toolbar = findViewById(R.id.toolbar);
381 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
382 setSupportActionBar(toolbar);
384 // Get a handle for the action bar.
385 ActionBar actionBar = getSupportActionBar();
387 // This is needed to get rid of the Android Studio warning that the action bar might be null.
388 assert actionBar != null;
390 // Add the custom layout, which shows the URL text bar.
391 actionBar.setCustomView(R.layout.url_app_bar);
392 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
394 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
395 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
396 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
397 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
399 // Get handles for the URL views.
400 EditText urlEditText = findViewById(R.id.url_edittext);
402 // Remove the formatting from `urlTextBar` when the user is editing the text.
403 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
404 if (hasFocus) { // The user is editing the URL text box.
405 // Remove the highlighting.
406 urlEditText.getText().removeSpan(redColorSpan);
407 urlEditText.getText().removeSpan(initialGrayColorSpan);
408 urlEditText.getText().removeSpan(finalGrayColorSpan);
409 } else { // The user has stopped editing the URL text box.
410 // Move to the beginning of the string.
411 urlEditText.setSelection(0);
413 // Reapply the highlighting.
418 // Set the go button on the keyboard to load the URL in `urlTextBox`.
419 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
420 // If the event is a key-down event on the `enter` button, load the URL.
421 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
422 // Load the URL into the mainWebView and consume the event.
423 loadUrlFromTextBox();
425 // If the enter key was pressed, consume the event.
428 // If any other key was pressed, do not consume the event.
433 // Set `waitingForOrbotHTMLString`.
434 waitingForOrbotHtmlString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
436 // Initialize the Orbot status and the waiting for Orbot trackers.
437 orbotStatus = "unknown";
438 waitingForOrbot = false;
440 // Create an Orbot status `BroadcastReceiver`.
441 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
443 public void onReceive(Context context, Intent intent) {
444 // Store the content of the status message in `orbotStatus`.
445 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
447 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
448 if (orbotStatus.equals("ON") && waitingForOrbot) {
449 // Reset the waiting for Orbot status.
450 waitingForOrbot = false;
452 // Get the intent that started the app.
453 Intent launchingIntent = getIntent();
455 // Get the information from the intent.
456 String launchingIntentAction = launchingIntent.getAction();
457 Uri launchingIntentUriData = launchingIntent.getData();
459 // If the intent action is a web search, perform the search.
460 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
461 // Create an encoded URL string.
462 String encodedUrlString;
464 // Sanitize the search input and convert it to a search.
466 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
467 } catch (UnsupportedEncodingException exception) {
468 encodedUrlString = "";
471 // Load the completed search URL.
472 loadUrl(searchURL + encodedUrlString);
473 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
474 // Load the URL from the intent.
475 loadUrl(launchingIntentUriData.toString());
476 } else { // The is no URL in the intent.
477 // Load the homepage.
484 // Register `orbotStatusBroadcastReceiver` on `this` context.
485 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
487 // Instantiate the block list helper.
488 blockListHelper = new BlockListHelper();
490 // Parse the block lists.
491 easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
492 easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
493 fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
494 fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
495 ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
497 // Store the list versions.
498 easyListVersion = easyList.get(0).get(0)[0];
499 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
500 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
501 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
502 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
504 // Get handles for views that need to be modified.
505 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
506 NavigationView navigationView = findViewById(R.id.navigationview);
507 TabLayout tabLayout = findViewById(R.id.tablayout);
508 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
509 ViewPager webViewPager = findViewById(R.id.webviewpager);
510 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
511 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
512 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
513 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
514 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
516 // Listen for touches on the navigation menu.
517 navigationView.setNavigationItemSelectedListener(this);
519 // Get handles for the navigation menu and the back and forward menu items. The menu is zero-based.
520 Menu navigationMenu = navigationView.getMenu();
521 MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
522 MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
523 MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
524 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
525 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
527 // Initialize the web view pager adapter.
528 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
530 // Set the pager adapter on the web view pager.
531 webViewPager.setAdapter(webViewPagerAdapter);
533 // Store up to 100 tabs in memory.
534 webViewPager.setOffscreenPageLimit(100);
536 // Update the web view pager every time a tab is modified.
537 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
539 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
544 public void onPageSelected(int position) {
545 // Set the current WebView.
546 setCurrentWebView(position);
548 // 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.
549 if (tabLayout.getSelectedTabPosition() != position) {
550 // Get a handle for the corresponding tab.
551 TabLayout.Tab correspondingTab = tabLayout.getTabAt(position);
553 // Assert that the corresponding tab is not null.
554 assert correspondingTab != null;
556 // Select the corresponding tab.
557 correspondingTab.select();
562 public void onPageScrollStateChanged(int state) {
567 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
568 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
570 public void onTabSelected(TabLayout.Tab tab) {
571 // Select the same page in the view pager.
572 webViewPager.setCurrentItem(tab.getPosition());
576 public void onTabUnselected(TabLayout.Tab tab) {
581 public void onTabReselected(TabLayout.Tab tab) {
582 // Instantiate the View SSL Certificate dialog.
583 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
585 // Display the View SSL Certificate dialog.
586 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
590 // Add the first tab.
593 // 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.
594 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
596 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
597 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
598 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
599 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
601 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
602 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
603 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
604 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
607 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
608 launchBookmarksActivityFab.setOnClickListener(v -> {
609 // Get a copy of the favorite icon bitmap.
610 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
612 // Create a favorite icon byte array output stream.
613 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
615 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
616 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
618 // Convert the favorite icon byte array stream to a byte array.
619 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
621 // Create an intent to launch the bookmarks activity.
622 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
624 // Add the extra information to the intent.
625 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
626 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
627 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
628 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
631 startActivity(bookmarksIntent);
634 // Set the create new bookmark folder FAB to display an alert dialog.
635 createBookmarkFolderFab.setOnClickListener(v -> {
636 // Create a create bookmark folder dialog.
637 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
639 // Show the create bookmark folder dialog.
640 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
643 // Set the create new bookmark FAB to display an alert dialog.
644 createBookmarkFab.setOnClickListener(view -> {
645 // Instantiate the create bookmark dialog.
646 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
648 // Display the create bookmark dialog.
649 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
652 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
653 findOnPageEditText.addTextChangedListener(new TextWatcher() {
655 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
660 public void onTextChanged(CharSequence s, int start, int before, int count) {
665 public void afterTextChanged(Editable s) {
666 // Search for the text in `mainWebView`.
667 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
671 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
672 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
673 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
674 // Hide the soft keyboard.
675 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
677 // Consume the event.
679 } else { // A different key was pressed.
680 // Do not consume the event.
685 // Implement swipe to refresh.
686 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
688 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
689 swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
691 // Set the swipe to refresh color according to the theme.
693 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
694 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
696 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
699 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
700 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
701 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
703 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
704 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
706 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
707 currentBookmarksFolder = "";
709 // Load the home folder, which is `""` in the database.
710 loadBookmarksFolder();
712 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
713 // Convert the id from long to int to match the format of the bookmarks database.
714 int databaseID = (int) id;
716 // Get the bookmark cursor for this ID and move it to the first row.
717 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
718 bookmarkCursor.moveToFirst();
720 // Act upon the bookmark according to the type.
721 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
722 // Store the new folder name in `currentBookmarksFolder`.
723 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
725 // Load the new folder.
726 loadBookmarksFolder();
727 } else { // The selected bookmark is not a folder.
728 // Load the bookmark URL.
729 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
731 // Close the bookmarks drawer.
732 drawerLayout.closeDrawer(GravityCompat.END);
735 // Close the `Cursor`.
736 bookmarkCursor.close();
739 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
740 // Convert the database ID from `long` to `int`.
741 int databaseId = (int) id;
743 // Find out if the selected bookmark is a folder.
744 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
747 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
748 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
750 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
751 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
752 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
754 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
755 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
756 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
759 // Consume the event.
763 // Get the status bar pixel size.
764 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
765 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
767 // Get the resource density.
768 float screenDensity = getResources().getDisplayMetrics().density;
770 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
771 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
772 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
773 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
775 // The drawer listener is used to update the navigation menu.`
776 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
778 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
782 public void onDrawerOpened(@NonNull View drawerView) {
786 public void onDrawerClosed(@NonNull View drawerView) {
790 public void onDrawerStateChanged(int newState) {
791 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
792 // Get handles for the drawer headers.
793 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
794 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
796 // 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.
797 if (navigationHeaderTextView != null) {
798 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
801 // 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.
802 if (bookmarksHeaderTextView != null) {
803 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
806 // Update the navigation menu items.
807 navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
808 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
809 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
810 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
811 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
813 // Hide the keyboard (if displayed).
814 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
816 // 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.
817 urlEditText.clearFocus();
818 currentWebView.clearFocus();
823 // Create the hamburger icon at the start of the AppBar.
824 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
826 // 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).
827 customHeaders.put("X-Requested-With", "");
829 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
830 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
832 // Store the application's private data directory.
833 privateDataDirectoryString = getApplicationInfo().dataDir;
834 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
836 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
837 inFullScreenBrowsingMode = false;
839 // Initialize the privacy settings variables.
840 firstPartyCookiesEnabled = false;
842 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
843 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
845 // Get a handle for the WebView.
846 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
848 // Store the default user agent.
849 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
851 // Destroy the bare WebView.
852 bareWebView.destroy();
856 protected void onNewIntent(Intent intent) {
857 // Get the information from the intent.
858 String intentAction = intent.getAction();
859 Uri intentUriData = intent.getData();
861 // 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.
862 if (intentUriData != null) {
863 // Sets the new intent as the activity intent, which replaces the one that originally started the app.
869 // Create a URL string.
872 // If the intent action is a web search, perform the search.
873 if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
874 // Create an encoded URL string.
875 String encodedUrlString;
877 // Sanitize the search input and convert it to a search.
879 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
880 } catch (UnsupportedEncodingException exception) {
881 encodedUrlString = "";
884 // Add the base search URL.
885 url = searchURL + encodedUrlString;
886 } else { // The intent should contain a URL.
887 // Set the intent data as the URL.
888 url = intentUriData.toString();
894 // Get a handle for the drawer layout.
895 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
897 // Close the navigation drawer if it is open.
898 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
899 drawerLayout.closeDrawer(GravityCompat.START);
902 // Close the bookmarks drawer if it is open.
903 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
904 drawerLayout.closeDrawer(GravityCompat.END);
907 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
908 currentWebView.requestFocus();
913 public void onRestart() {
914 // Run the default commands.
917 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
918 if (proxyThroughOrbot) {
919 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
920 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
922 // Send the intent to the Orbot package.
923 orbotIntent.setPackage("org.torproject.android");
926 sendBroadcast(orbotIntent);
929 // Apply the app settings if returning from the Settings activity.
930 if (reapplyAppSettingsOnRestart) {
931 // Apply the app settings.
934 // Reload the webpage to handle changes to night mode and displaying of images.
935 if (reloadOnRestart) {
936 // Reload the WebViews.
937 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
938 // Get the WebView tab fragment.
939 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
941 // Get the fragment view.
942 View fragmentView = webViewTabFragment.getView();
944 // Only reload the WebViews if they exist.
945 if (fragmentView != null) {
946 // Get the nested scroll WebView from the tab fragment.
947 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
949 // Reload the WebView. This doesn't seem to work if for WebViews that aren't visible.
950 nestedScrollWebView.reload();
954 // Reset `reloadOnRestartBoolean`.
955 reloadOnRestart = false;
958 // Reset the return from settings flag.
959 reapplyAppSettingsOnRestart = false;
962 // TODO apply to all the tabs.
963 // Apply the domain settings if returning from the Domains activity.
964 if (reapplyDomainSettingsOnRestart) {
965 // Reset the current domain name so the domain settings will be reapplied.
966 currentWebView.resetCurrentDomainName();
968 // Reapply the domain settings.
969 applyDomainSettings(currentWebView, currentWebView.getUrl(), false, true); // TODO.
971 // Reset the reapply domain settings on restart tracker.
972 reapplyDomainSettingsOnRestart = false;
975 // Load the URL on restart (used when loading a bookmark.
976 if (loadUrlOnRestart) {
977 // Load the specified URL.
978 loadUrl(urlToLoadOnRestart);
980 // Reset the load on restart tracker.
981 loadUrlOnRestart = false;
984 // Update the bookmarks drawer if returning from the Bookmarks activity.
985 if (restartFromBookmarksActivity) {
986 // Get a handle for the drawer layout.
987 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
989 // Close the bookmarks drawer.
990 drawerLayout.closeDrawer(GravityCompat.END);
992 // Reload the bookmarks drawer.
993 loadBookmarksFolder();
995 // Reset `restartFromBookmarksActivity`.
996 restartFromBookmarksActivity = false;
999 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1000 updatePrivacyIcons(true);
1003 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1005 public void onResume() {
1006 // Run the default commands.
1009 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1010 // Get the WebView tab fragment.
1011 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1013 // Get the fragment view.
1014 View fragmentView = webViewTabFragment.getView();
1016 // Only resume the WebViews if they exist (they won't when the app is first created).
1017 if (fragmentView != null) {
1018 // Get the nested scroll WebView from the tab fragment.
1019 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1021 // Resume the nested scroll WebView JavaScript timers.
1022 nestedScrollWebView.resumeTimers();
1024 // Resume the nested scroll WebView.
1025 nestedScrollWebView.onResume();
1029 // Display a message to the user if waiting for Orbot.
1030 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1031 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1032 currentWebView.getSettings().setUseWideViewPort(false);
1034 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1035 currentWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
1038 if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
1039 // Get a handle for the root frame layouts.
1040 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1042 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1043 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1045 /* Hide the system bars.
1046 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1047 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1048 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1049 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1051 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1052 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1053 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // Resume the adView for the free flavor.
1055 AdHelper.resumeAd(findViewById(R.id.adview));
1060 public void onPause() {
1061 // Run the default commands.
1064 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
1065 // Get the WebView tab fragment.
1066 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
1068 // Get the fragment view.
1069 View fragmentView = webViewTabFragment.getView();
1071 // Only pause the WebViews if they exist (they won't when the app is first created).
1072 if (fragmentView != null) {
1073 // Get the nested scroll WebView from the tab fragment.
1074 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1076 // Pause the nested scroll WebView.
1077 nestedScrollWebView.onPause();
1079 // Pause the nested scroll WebView JavaScript timers.
1080 nestedScrollWebView.pauseTimers();
1084 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1085 if (BuildConfig.FLAVOR.contentEquals("free")) {
1087 AdHelper.pauseAd(findViewById(R.id.adview));
1092 public void onDestroy() {
1093 // Unregister the Orbot status broadcast receiver.
1094 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1096 // Close the bookmarks cursor and database.
1097 bookmarksCursor.close();
1098 bookmarksDatabaseHelper.close();
1100 // Run the default commands.
1105 public boolean onCreateOptionsMenu(Menu menu) {
1106 // Inflate the menu. This adds items to the action bar if it is present.
1107 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1109 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1112 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1113 updatePrivacyIcons(false);
1115 // Get handles for the menu items.
1116 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1117 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1118 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1119 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1120 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1121 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1122 blocklistsMenuItem = menu.findItem(R.id.blocklists);
1123 easyListMenuItem = menu.findItem(R.id.easylist);
1124 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1125 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1126 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1127 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1128 blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1129 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1131 // Only display third-party cookies if API >= 21
1132 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1134 // Only display the form data menu items if the API < 26.
1135 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1136 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1138 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1139 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1141 // Only show Ad Consent if this is the free flavor.
1142 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1144 // Get the shared preference values.
1145 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1147 // Get the status of the additional AppBar icons.
1148 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1150 // 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.
1151 if (displayAdditionalAppBarIcons) {
1152 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1153 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1154 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1155 } else { //Do not display the additional icons.
1156 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1157 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1158 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1161 // Replace Refresh with Stop if a URL is already loading.
1162 if (currentWebView != null && currentWebView.getProgress() != 100) {
1164 refreshMenuItem.setTitle(R.string.stop);
1166 // If the icon is displayed in the AppBar, set it according to the theme.
1167 if (displayAdditionalAppBarIcons) {
1169 refreshMenuItem.setIcon(R.drawable.close_dark);
1171 refreshMenuItem.setIcon(R.drawable.close_light);
1180 public boolean onPrepareOptionsMenu(Menu menu) {
1181 // Get handles for the menu items.
1182 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1183 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1184 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1185 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1186 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1187 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1188 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1189 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1190 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1191 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1192 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1193 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1194 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1195 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1197 // Get a handle for the cookie manager.
1198 CookieManager cookieManager = CookieManager.getInstance();
1200 // Initialize the current user agent string and the font size.
1201 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1204 // 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.
1205 if (currentWebView != null) {
1206 // Set the add or edit domain text.
1207 if (currentWebView.getDomainSettingsApplied()) {
1208 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1210 addOrEditDomain.setTitle(R.string.add_domain_settings);
1213 // Get the current user agent from the WebView.
1214 currentUserAgent = currentWebView.getSettings().getUserAgentString();
1216 // Get the current font size from the
1217 fontSize = currentWebView.getSettings().getTextZoom();
1219 // Set the status of the menu item checkboxes.
1220 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1221 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
1222 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1223 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1224 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1225 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1226 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1227 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1228 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1229 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1230 nightModeMenuItem.setChecked(currentWebView.getNightMode());
1232 // Initialize the display names for the blocklists with the number of blocked requests.
1233 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1234 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1235 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1236 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1237 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1238 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1239 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1241 // Only modify third-party cookies if the API >= 21.
1242 if (Build.VERSION.SDK_INT >= 21) {
1243 // Set the status of the third-party cookies checkbox.
1244 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1246 // Enable third-party cookies if first-party cookies are enabled.
1247 thirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1250 // Enable DOM Storage if JavaScript is enabled.
1251 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1254 // Set the status of the menu item checkboxes.
1255 firstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1256 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1258 // Enable Clear Cookies if there are any.
1259 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1261 // Get a count of the number of files in the Local Storage directory.
1262 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1263 int localStorageDirectoryNumberOfFiles = 0;
1264 if (localStorageDirectory.exists()) {
1265 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1268 // Get a count of the number of files in the IndexedDB directory.
1269 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1270 int indexedDBDirectoryNumberOfFiles = 0;
1271 if (indexedDBDirectory.exists()) {
1272 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1275 // Enable Clear DOM Storage if there is any.
1276 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1278 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1279 if (Build.VERSION.SDK_INT < 26) {
1280 // Get the WebView database.
1281 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1283 // Enable the clear form data menu item if there is anything to clear.
1284 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1287 // Enable Clear Data if any of the submenu items are enabled.
1288 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1290 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1291 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1293 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
1294 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
1295 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1296 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
1297 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1298 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
1299 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1300 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
1301 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1302 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
1303 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1304 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
1305 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1306 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
1307 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1308 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
1309 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1310 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
1311 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1312 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
1313 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1314 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
1315 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1316 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
1317 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1318 } else { // Custom user agent.
1319 menu.findItem(R.id.user_agent_custom).setChecked(true);
1322 // Instantiate the font size title and the selected font size menu item.
1323 String fontSizeTitle;
1324 MenuItem selectedFontSizeMenuItem;
1326 // Prepare the font size title and current size menu item.
1329 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1330 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1334 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1335 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1339 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1340 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1344 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1345 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1349 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1350 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1354 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1355 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1359 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1360 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1364 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1365 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1369 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1370 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1374 // Set the font size title and select the current size menu item.
1375 fontSizeMenuItem.setTitle(fontSizeTitle);
1376 selectedFontSizeMenuItem.setChecked(true);
1378 // Run all the other default commands.
1379 super.onPrepareOptionsMenu(menu);
1381 // Display the menu.
1386 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1387 @SuppressLint("SetJavaScriptEnabled")
1388 // removeAllCookies is deprecated, but it is required for API < 21.
1389 @SuppressWarnings("deprecation")
1390 public boolean onOptionsItemSelected(MenuItem menuItem) {
1391 // Reenter full screen browsing mode if it was interrupted by the options menu. <https://redmine.stoutner.com/issues/389>
1392 if (inFullScreenBrowsingMode) {
1393 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
1394 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1396 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1398 /* Hide the system bars.
1399 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1400 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1401 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1402 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1404 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1405 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1408 // Get the selected menu item ID.
1409 int menuItemId = menuItem.getItemId();
1411 // Get a handle for the shared preferences.
1412 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1414 // Get a handle for the cookie manager.
1415 CookieManager cookieManager = CookieManager.getInstance();
1417 // Run the commands that correlate to the selected menu item.
1418 switch (menuItemId) {
1419 case R.id.toggle_javascript:
1420 // Toggle the JavaScript status.
1421 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1423 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1424 updatePrivacyIcons(true);
1426 // Display a `Snackbar`.
1427 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1428 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1429 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1430 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1431 } else { // Privacy mode.
1432 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1435 // Reload the current WebView.
1436 currentWebView.reload();
1439 case R.id.add_or_edit_domain:
1440 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1441 // Reapply the domain settings on returning to `MainWebViewActivity`.
1442 reapplyDomainSettingsOnRestart = true;
1444 // TODO. Move these to `putExtra`. The certificate can be stored as strings.
1445 // Store the current SSL certificate and IP addresses in the domains activity.
1446 DomainsActivity.currentSslCertificate = currentWebView.getCertificate();
1447 DomainsActivity.currentIpAddresses = currentWebView.getCurrentIpAddresses();
1449 // Create an intent to launch the domains activity.
1450 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1452 // Add the extra information to the intent.
1453 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1454 domainsIntent.putExtra("close_on_back", true);
1455 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1458 startActivity(domainsIntent);
1459 } else { // Add a new domain.
1460 // Apply the new domain settings on returning to `MainWebViewActivity`.
1461 reapplyDomainSettingsOnRestart = true;
1463 // Get the current domain
1464 Uri currentUri = Uri.parse(currentWebView.getUrl());
1465 String currentDomain = currentUri.getHost();
1467 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1468 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1470 // Create the domain and store the database ID.
1471 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1473 // TODO. Move these to `putExtra`. The certificate can be stored as strings.
1474 // Store the current SSL certificate and IP addresses in the domains activity.
1475 DomainsActivity.currentSslCertificate = currentWebView.getCertificate();
1476 DomainsActivity.currentIpAddresses = currentWebView.getCurrentIpAddresses();
1478 // Create an intent to launch the domains activity.
1479 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1481 // Add the extra information to the intent.
1482 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1483 domainsIntent.putExtra("close_on_back", true);
1484 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1487 startActivity(domainsIntent);
1491 case R.id.toggle_first_party_cookies:
1492 // Switch the status of firstPartyCookiesEnabled.
1493 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1495 // Update the menu checkbox.
1496 menuItem.setChecked(firstPartyCookiesEnabled);
1498 // Apply the new cookie status.
1499 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1501 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1502 updatePrivacyIcons(true);
1504 // Display a `Snackbar`.
1505 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1506 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1507 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1508 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1509 } else { // Privacy mode.
1510 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1513 // Reload the current WebView.
1514 currentWebView.reload();
1517 case R.id.toggle_third_party_cookies:
1518 if (Build.VERSION.SDK_INT >= 21) {
1519 // Switch the status of thirdPartyCookiesEnabled.
1520 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1522 // Update the menu checkbox.
1523 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1525 // Display a snackbar.
1526 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1527 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1529 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1532 // Reload the current WebView.
1533 currentWebView.reload();
1534 } // Else do nothing because SDK < 21.
1537 case R.id.toggle_dom_storage:
1538 // Toggle the status of domStorageEnabled.
1539 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1541 // Update the menu checkbox.
1542 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1544 // Update the privacy icon. `true` refreshes the app bar icons.
1545 updatePrivacyIcons(true);
1547 // Display a snackbar.
1548 if (currentWebView.getSettings().getDomStorageEnabled()) {
1549 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1551 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1554 // Reload the current WebView.
1555 currentWebView.reload();
1558 // Form data can be removed once the minimum API >= 26.
1559 case R.id.toggle_save_form_data:
1560 // Switch the status of saveFormDataEnabled.
1561 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1563 // Update the menu checkbox.
1564 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1566 // Display a snackbar.
1567 if (currentWebView.getSettings().getSaveFormData()) {
1568 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1570 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1573 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1574 updatePrivacyIcons(true);
1576 // Reload the current WebView.
1577 currentWebView.reload();
1580 case R.id.clear_cookies:
1581 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1582 .setAction(R.string.undo, v -> {
1583 // Do nothing because everything will be handled by `onDismissed()` below.
1585 .addCallback(new Snackbar.Callback() {
1586 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1588 public void onDismissed(Snackbar snackbar, int event) {
1590 // The user pushed the undo button.
1591 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1595 // The snackbar was dismissed without the undo button being pushed.
1597 // `cookieManager.removeAllCookie()` varies by SDK.
1598 if (Build.VERSION.SDK_INT < 21) {
1599 cookieManager.removeAllCookie();
1601 cookieManager.removeAllCookies(null);
1609 case R.id.clear_dom_storage:
1610 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1611 .setAction(R.string.undo, v -> {
1612 // Do nothing because everything will be handled by `onDismissed()` below.
1614 .addCallback(new Snackbar.Callback() {
1615 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1617 public void onDismissed(Snackbar snackbar, int event) {
1619 // The user pushed the undo button.
1620 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1624 // The snackbar was dismissed without the undo button being pushed.
1626 // Delete the DOM Storage.
1627 WebStorage webStorage = WebStorage.getInstance();
1628 webStorage.deleteAllData();
1630 // Initialize a handler to manually delete the DOM storage files and directories.
1631 Handler deleteDomStorageHandler = new Handler();
1633 // Setup a runnable to manually delete the DOM storage files and directories.
1634 Runnable deleteDomStorageRunnable = () -> {
1636 // Get a handle for the runtime.
1637 Runtime runtime = Runtime.getRuntime();
1639 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1640 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1642 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1643 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1644 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1645 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1646 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1648 // Wait for the processes to finish.
1649 deleteLocalStorageProcess.waitFor();
1650 deleteIndexProcess.waitFor();
1651 deleteQuotaManagerProcess.waitFor();
1652 deleteQuotaManagerJournalProcess.waitFor();
1653 deleteDatabasesProcess.waitFor();
1654 } catch (Exception exception) {
1655 // Do nothing if an error is thrown.
1659 // Manually delete the DOM storage files after 200 milliseconds.
1660 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1667 // Form data can be remove once the minimum API >= 26.
1668 case R.id.clear_form_data:
1669 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1670 .setAction(R.string.undo, v -> {
1671 // Do nothing because everything will be handled by `onDismissed()` below.
1673 .addCallback(new Snackbar.Callback() {
1674 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1676 public void onDismissed(Snackbar snackbar, int event) {
1678 // The user pushed the undo button.
1679 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1683 // The snackbar was dismissed without the `Undo` button being pushed.
1685 // Delete the form data.
1686 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1687 mainWebViewDatabase.clearFormData();
1695 // Toggle the EasyList status.
1696 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1698 // Update the menu checkbox.
1699 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1701 // Reload the current WebView.
1702 currentWebView.reload();
1705 case R.id.easyprivacy:
1706 // Toggle the EasyPrivacy status.
1707 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1709 // Update the menu checkbox.
1710 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1712 // Reload the current WebView.
1713 currentWebView.reload();
1716 case R.id.fanboys_annoyance_list:
1717 // Toggle Fanboy's Annoyance List status.
1718 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1720 // Update the menu checkbox.
1721 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1723 // Update the staus of Fanboy's Social Blocking List.
1724 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1725 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1727 // Reload the current WebView.
1728 currentWebView.reload();
1731 case R.id.fanboys_social_blocking_list:
1732 // Toggle Fanboy's Social Blocking List status.
1733 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1735 // Update the menu checkbox.
1736 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1738 // Reload the current WebView.
1739 currentWebView.reload();
1742 case R.id.ultraprivacy:
1743 // Toggle the UltraPrivacy status.
1744 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1746 // Update the menu checkbox.
1747 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1749 // Reload the current WebView.
1750 currentWebView.reload();
1753 case R.id.block_all_third_party_requests:
1754 //Toggle the third-party requests blocker status.
1755 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1757 // Update the menu checkbox.
1758 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1760 // Reload the current WebView.
1761 currentWebView.reload();
1764 case R.id.user_agent_privacy_browser:
1765 // Update the user agent.
1766 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1768 // Reload the current WebView.
1769 currentWebView.reload();
1772 case R.id.user_agent_webview_default:
1773 // Update the user agent.
1774 currentWebView.getSettings().setUserAgentString("");
1776 // Reload the current WebView.
1777 currentWebView.reload();
1780 case R.id.user_agent_firefox_on_android:
1781 // Update the user agent.
1782 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1784 // Reload the current WebView.
1785 currentWebView.reload();
1788 case R.id.user_agent_chrome_on_android:
1789 // Update the user agent.
1790 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1792 // Reload the current WebView.
1793 currentWebView.reload();
1796 case R.id.user_agent_safari_on_ios:
1797 // Update the user agent.
1798 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1800 // Reload the current WebView.
1801 currentWebView.reload();
1804 case R.id.user_agent_firefox_on_linux:
1805 // Update the user agent.
1806 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1808 // Reload the current WebView.
1809 currentWebView.reload();
1812 case R.id.user_agent_chromium_on_linux:
1813 // Update the user agent.
1814 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1816 // Reload the current WebView.
1817 currentWebView.reload();
1820 case R.id.user_agent_firefox_on_windows:
1821 // Update the user agent.
1822 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1824 // Reload the current WebView.
1825 currentWebView.reload();
1828 case R.id.user_agent_chrome_on_windows:
1829 // Update the user agent.
1830 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1832 // Reload the current WebView.
1833 currentWebView.reload();
1836 case R.id.user_agent_edge_on_windows:
1837 // Update the user agent.
1838 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1840 // Reload the current WebView.
1841 currentWebView.reload();
1844 case R.id.user_agent_internet_explorer_on_windows:
1845 // Update the user agent.
1846 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1848 // Reload the current WebView.
1849 currentWebView.reload();
1852 case R.id.user_agent_safari_on_macos:
1853 // Update the user agent.
1854 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1856 // Reload the current WebView.
1857 currentWebView.reload();
1860 case R.id.user_agent_custom:
1861 // Update the user agent.
1862 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1864 // Reload the current WebView.
1865 currentWebView.reload();
1868 case R.id.font_size_twenty_five_percent:
1869 currentWebView.getSettings().setTextZoom(25);
1872 case R.id.font_size_fifty_percent:
1873 currentWebView.getSettings().setTextZoom(50);
1876 case R.id.font_size_seventy_five_percent:
1877 currentWebView.getSettings().setTextZoom(75);
1880 case R.id.font_size_one_hundred_percent:
1881 currentWebView.getSettings().setTextZoom(100);
1884 case R.id.font_size_one_hundred_twenty_five_percent:
1885 currentWebView.getSettings().setTextZoom(125);
1888 case R.id.font_size_one_hundred_fifty_percent:
1889 currentWebView.getSettings().setTextZoom(150);
1892 case R.id.font_size_one_hundred_seventy_five_percent:
1893 currentWebView.getSettings().setTextZoom(175);
1896 case R.id.font_size_two_hundred_percent:
1897 currentWebView.getSettings().setTextZoom(200);
1900 case R.id.swipe_to_refresh:
1901 // Toggle the stored status of swipe to refresh.
1902 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1904 // Get a handle for the swipe refresh layout.
1905 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1907 // Update the swipe refresh layout.
1908 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1909 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.
1910 // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1911 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1912 } else { // For API < 23, the swipe refresh layout is always enabled.
1913 // Enable the swipe refresh layout.
1914 swipeRefreshLayout.setEnabled(true);
1916 } else { // Swipe to refresh is disabled.
1917 // Disable the swipe refresh layout.
1918 swipeRefreshLayout.setEnabled(false);
1922 case R.id.display_images:
1923 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1924 // Disable loading of images.
1925 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1927 // Reload the website to remove existing images.
1928 currentWebView.reload();
1929 } else { // Images are not currently loaded automatically.
1930 // Enable loading of images. Missing images will be loaded without the need for a reload.
1931 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1935 case R.id.night_mode:
1936 // Toggle night mode.
1937 currentWebView.setNightMode(!currentWebView.getNightMode());
1939 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1940 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1941 // Enable JavaScript.
1942 currentWebView.getSettings().setJavaScriptEnabled(true);
1943 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1944 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1945 currentWebView.getSettings().setJavaScriptEnabled(domainSettingsJavaScriptEnabled); // TODO.
1946 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1947 // Apply the JavaScript preference.
1948 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1951 // Update the privacy icons.
1952 updatePrivacyIcons(false);
1954 // Reload the website.
1955 currentWebView.reload();
1958 case R.id.find_on_page:
1959 // Get a handle for the views.
1960 Toolbar toolbar = findViewById(R.id.toolbar);
1961 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1962 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1964 // Hide the toolbar.
1965 toolbar.setVisibility(View.GONE);
1967 // Show the find on page linear layout.
1968 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1970 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1971 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1972 findOnPageEditText.postDelayed(() -> {
1973 // Set the focus on `findOnPageEditText`.
1974 findOnPageEditText.requestFocus();
1976 // Get a handle for the input method manager.
1977 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1979 // Remove the lint warning below that the input method manager might be null.
1980 assert inputMethodManager != null;
1982 // Display the keyboard. `0` sets no input flags.
1983 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1987 case R.id.view_source:
1988 // Create an intent to launch the view source activity.
1989 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1991 // Add the variables to the intent.
1992 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1993 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1996 startActivity(viewSourceIntent);
1999 case R.id.share_url:
2000 // Setup the share string.
2001 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
2003 // Create the share intent.
2004 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2005 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2006 shareIntent.setType("text/plain");
2009 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2013 // Get a `PrintManager` instance.
2014 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2016 // Create a print document adapter form the current WebView.
2017 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2019 // Remove the lint error below that `printManager` might be `null`.
2020 assert printManager != null;
2022 // Print the document. The print attributes are `null`.
2023 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2026 case R.id.open_with_app:
2027 openWithApp(currentWebView.getUrl());
2030 case R.id.open_with_browser:
2031 openWithBrowser(currentWebView.getUrl());
2034 case R.id.add_to_homescreen:
2035 // Instantiate the create home screen shortcut dialog.
2036 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2037 currentWebView.getFavoriteOrDefaultIcon());
2039 // Show the create home screen shortcut dialog.
2040 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2043 case R.id.proxy_through_orbot:
2044 // Toggle the proxy through Orbot variable.
2045 proxyThroughOrbot = !proxyThroughOrbot;
2047 // Apply the proxy through Orbot settings.
2048 applyProxyThroughOrbot(true);
2052 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2053 // Reload the current WebView.
2054 currentWebView.reload();
2055 } else { // The stop button was pushed.
2056 // Stop the loading of the WebView.
2057 currentWebView.stopLoading();
2061 case R.id.ad_consent:
2062 // Display the ad consent dialog.
2063 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2064 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2068 // Don't consume the event.
2069 return super.onOptionsItemSelected(menuItem);
2073 // removeAllCookies is deprecated, but it is required for API < 21.
2074 @SuppressWarnings("deprecation")
2076 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2077 // Get the menu item ID.
2078 int menuItemId = menuItem.getItemId();
2080 // Run the commands that correspond to the selected menu item.
2081 switch (menuItemId) {
2082 case R.id.close_tab:
2083 // Get a handle for the tab layout and the view pager.
2084 TabLayout tabLayout = findViewById(R.id.tablayout);
2085 ViewPager webViewPager = findViewById(R.id.webviewpager);
2087 // Get the current tab number.
2088 int currentTabNumber = tabLayout.getSelectedTabPosition();
2090 // Delete the current tab.
2091 tabLayout.removeTabAt(currentTabNumber);
2093 // 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.
2094 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2095 setCurrentWebView(currentTabNumber);
2099 case R.id.clear_and_exit:
2100 // Close the bookmarks cursor and database.
2101 bookmarksCursor.close();
2102 bookmarksDatabaseHelper.close();
2104 // Get a handle for the shared preferences.
2105 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2107 // Get the status of the clear everything preference.
2108 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2110 // Get a handle for the runtime.
2111 Runtime runtime = Runtime.getRuntime();
2114 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2115 // The command to remove cookies changed slightly in API 21.
2116 if (Build.VERSION.SDK_INT >= 21) {
2117 CookieManager.getInstance().removeAllCookies(null);
2119 CookieManager.getInstance().removeAllCookie();
2122 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2124 // Two commands must be used because `Runtime.exec()` does not like `*`.
2125 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2126 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2128 // Wait until the processes have finished.
2129 deleteCookiesProcess.waitFor();
2130 deleteCookiesJournalProcess.waitFor();
2131 } catch (Exception exception) {
2132 // Do nothing if an error is thrown.
2136 // Clear DOM storage.
2137 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2138 // Ask `WebStorage` to clear the DOM storage.
2139 WebStorage webStorage = WebStorage.getInstance();
2140 webStorage.deleteAllData();
2142 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2144 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2145 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2147 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2148 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2149 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2150 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2151 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2153 // Wait until the processes have finished.
2154 deleteLocalStorageProcess.waitFor();
2155 deleteIndexProcess.waitFor();
2156 deleteQuotaManagerProcess.waitFor();
2157 deleteQuotaManagerJournalProcess.waitFor();
2158 deleteDatabaseProcess.waitFor();
2159 } catch (Exception exception) {
2160 // Do nothing if an error is thrown.
2164 // Clear form data if the API < 26.
2165 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2166 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2167 webViewDatabase.clearFormData();
2169 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2171 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2172 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2173 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2175 // Wait until the processes have finished.
2176 deleteWebDataProcess.waitFor();
2177 deleteWebDataJournalProcess.waitFor();
2178 } catch (Exception exception) {
2179 // Do nothing if an error is thrown.
2184 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2185 // Clear the cache from each WebView.
2186 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2187 // Get the WebView tab fragment.
2188 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2190 // Get the fragment view.
2191 View fragmentView = webViewTabFragment.getView();
2193 // Only clear the cache if the WebView exists.
2194 if (fragmentView != null) {
2195 // Get the nested scroll WebView from the tab fragment.
2196 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2198 // Clear the cache for this WebView.
2199 nestedScrollWebView.clearCache(true);
2203 // Manually delete the cache directories.
2205 // Delete the main cache directory.
2206 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2208 // Delete the secondary `Service Worker` cache directory.
2209 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2210 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2212 // Wait until the processes have finished.
2213 deleteCacheProcess.waitFor();
2214 deleteServiceWorkerProcess.waitFor();
2215 } catch (Exception exception) {
2216 // Do nothing if an error is thrown.
2220 // Wipe out each WebView.
2221 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2222 // Get the WebView tab fragment.
2223 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2225 // Get the fragment view.
2226 View fragmentView = webViewTabFragment.getView();
2228 // Only wipe out the WebView if it exists.
2229 if (fragmentView != null) {
2230 // Get the nested scroll WebView from the tab fragment.
2231 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2233 // Clear SSL certificate preferences for this WebView.
2234 nestedScrollWebView.clearSslPreferences();
2236 // Clear the back/forward history for this WebView.
2237 nestedScrollWebView.clearHistory();
2239 // Destroy the internal state of `mainWebView`.
2240 nestedScrollWebView.destroy();
2244 // Clear the custom headers.
2245 customHeaders.clear();
2247 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2248 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2249 if (clearEverything) {
2251 // Delete the folder.
2252 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2254 // Wait until the process has finished.
2255 deleteAppWebviewProcess.waitFor();
2256 } catch (Exception exception) {
2257 // Do nothing if an error is thrown.
2261 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2262 if (Build.VERSION.SDK_INT >= 21) {
2263 finishAndRemoveTask();
2268 // Remove the terminated program from RAM. The status code is `0`.
2277 if (currentWebView.canGoBack()) {
2278 // Reset the current domain name so that navigation works if third-party requests are blocked.
2279 currentWebView.resetCurrentDomainName();
2281 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2282 navigatingHistory = true;
2284 // Load the previous website in the history.
2285 currentWebView.goBack();
2290 if (currentWebView.canGoForward()) {
2291 // Reset the current domain name so that navigation works if third-party requests are blocked.
2292 currentWebView.resetCurrentDomainName();
2294 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2295 navigatingHistory = true;
2297 // Load the next website in the history.
2298 currentWebView.goForward();
2303 // Get the `WebBackForwardList`.
2304 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2306 // Show the URL history dialog and name this instance `R.string.history`.
2307 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2308 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2312 // Populate the resource requests.
2313 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2315 // Create an intent to launch the Requests activity.
2316 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2318 // Add the block third-party requests status to the intent.
2319 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2322 startActivity(requestsIntent);
2325 case R.id.downloads:
2326 // Launch the system Download Manager.
2327 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2329 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2330 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2332 startActivity(downloadManagerIntent);
2336 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2337 reapplyDomainSettingsOnRestart = true;
2339 // TODO. Move these to `putExtra`. The certificate can be stored as strings.
2340 // Store the current SSL certificate and IP addresses in the domains activity.
2341 DomainsActivity.currentSslCertificate = currentWebView.getCertificate();
2342 DomainsActivity.currentIpAddresses = currentWebView.getCurrentIpAddresses();
2344 // Launch the domains activity.
2345 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2347 // Add the extra information to the intent.
2348 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2351 startActivity(domainsIntent);
2355 // Set the flag to reapply app settings on restart when returning from Settings.
2356 reapplyAppSettingsOnRestart = true;
2358 // Set the flag to reapply the domain settings on restart when returning from Settings.
2359 reapplyDomainSettingsOnRestart = true;
2361 // Launch the settings activity.
2362 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2363 startActivity(settingsIntent);
2366 case R.id.import_export:
2367 // Launch the import/export activity.
2368 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2369 startActivity(importExportIntent);
2373 // Launch the logcat activity.
2374 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2375 startActivity(logcatIntent);
2379 // Launch `GuideActivity`.
2380 Intent guideIntent = new Intent(this, GuideActivity.class);
2381 startActivity(guideIntent);
2385 // Launch `AboutActivity`.
2386 Intent aboutIntent = new Intent(this, AboutActivity.class);
2387 startActivity(aboutIntent);
2391 // Get a handle for the drawer layout.
2392 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2394 // Close the navigation drawer.
2395 drawerLayout.closeDrawer(GravityCompat.START);
2400 public void onPostCreate(Bundle savedInstanceState) {
2401 // Run the default commands.
2402 super.onPostCreate(savedInstanceState);
2404 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2405 actionBarDrawerToggle.syncState();
2409 public void onConfigurationChanged(Configuration newConfig) {
2410 // Run the default commands.
2411 super.onConfigurationChanged(newConfig);
2413 // Get the status bar pixel size.
2414 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2415 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2417 // Get the resource density.
2418 float screenDensity = getResources().getDisplayMetrics().density;
2420 // Recalculate the drawer header padding.
2421 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2422 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2423 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2425 // Reload the ad for the free flavor if not in full screen mode.
2426 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2427 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2428 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2431 // `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:
2432 // https://code.google.com/p/android/issues/detail?id=20493#c8
2433 // ActivityCompat.invalidateOptionsMenu(this);
2437 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2438 // Store the hit test result.
2439 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2441 // Create the URL strings.
2442 final String imageUrl;
2443 final String linkUrl;
2445 // Get handles for the the clipboard and fragment managers.
2446 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2447 FragmentManager fragmentManager = getSupportFragmentManager();
2449 // Remove the lint errors below that the clipboard manager might be null.
2450 assert clipboardManager != null;
2452 // Process the link according to the type.
2453 switch (hitTestResult.getType()) {
2454 // `SRC_ANCHOR_TYPE` is a link.
2455 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2456 // Get the target URL.
2457 linkUrl = hitTestResult.getExtra();
2459 // Set the target URL as the title of the `ContextMenu`.
2460 menu.setHeaderTitle(linkUrl);
2462 // Add a Load URL entry.
2463 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2472 // Add an Open with App entry.
2473 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2474 openWithApp(linkUrl);
2478 // Add an Open with Browser entry.
2479 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2480 openWithBrowser(linkUrl);
2484 // Add a Copy URL entry.
2485 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2486 // Save the link URL in a `ClipData`.
2487 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2489 // Set the `ClipData` as the clipboard's primary clip.
2490 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2494 // Add a Download URL entry.
2495 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2496 // Check if the download should be processed by an external app.
2497 if (downloadWithExternalApp) { // Download with an external app.
2498 openUrlWithExternalApp(linkUrl);
2499 } else { // Download with Android's download manager.
2500 // Check to see if the storage permission has already been granted.
2501 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2502 // Store the variables for future use by `onRequestPermissionsResult()`.
2503 downloadUrl = linkUrl;
2504 downloadContentDisposition = "none";
2505 downloadContentLength = -1;
2507 // Show a dialog if the user has previously denied the permission.
2508 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2509 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2510 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2512 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2513 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2514 } else { // Show the permission request directly.
2515 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2516 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2518 } else { // The storage permission has already been granted.
2519 // Get a handle for the download file alert dialog.
2520 DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2522 // Show the download file alert dialog.
2523 downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2529 // Add a Cancel entry, which by default closes the context menu.
2530 menu.add(R.string.cancel);
2533 case WebView.HitTestResult.EMAIL_TYPE:
2534 // Get the target URL.
2535 linkUrl = hitTestResult.getExtra();
2537 // Set the target URL as the title of the `ContextMenu`.
2538 menu.setHeaderTitle(linkUrl);
2540 // Add a Write Email entry.
2541 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2542 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2543 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2545 // Parse the url and set it as the data for the `Intent`.
2546 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2548 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2549 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2552 startActivity(emailIntent);
2556 // Add a Copy Email Address entry.
2557 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2558 // Save the email address in a `ClipData`.
2559 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2561 // Set the `ClipData` as the clipboard's primary clip.
2562 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2566 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2567 menu.add(R.string.cancel);
2570 // `IMAGE_TYPE` is an image.
2571 case WebView.HitTestResult.IMAGE_TYPE:
2572 // Get the image URL.
2573 imageUrl = hitTestResult.getExtra();
2575 // Set the image URL as the title of the `ContextMenu`.
2576 menu.setHeaderTitle(imageUrl);
2578 // Add a View Image entry.
2579 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2584 // Add a Download Image entry.
2585 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2586 // Check if the download should be processed by an external app.
2587 if (downloadWithExternalApp) { // Download with an external app.
2588 openUrlWithExternalApp(imageUrl);
2589 } else { // Download with Android's download manager.
2590 // Check to see if the storage permission has already been granted.
2591 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
2592 // Store the image URL for use by `onRequestPermissionResult()`.
2593 downloadImageUrl = imageUrl;
2595 // Show a dialog if the user has previously denied the permission.
2596 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2597 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2598 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2600 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2601 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2602 } else { // Show the permission request directly.
2603 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2604 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2606 } else { // The storage permission has already been granted.
2607 // Get a handle for the download image alert dialog.
2608 DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2610 // Show the download image alert dialog.
2611 downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2617 // Add a Copy URL entry.
2618 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2619 // Save the image URL in a `ClipData`.
2620 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);