2 * Copyright 2015-2017 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.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.TextWatcher;
63 import android.util.Patterns;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.WindowManager;
72 import android.view.inputmethod.InputMethodManager;
73 import android.webkit.CookieManager;
74 import android.webkit.DownloadListener;
75 import android.webkit.SslErrorHandler;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ProgressBar;
88 import android.widget.RelativeLayout;
89 import android.widget.TextView;
91 import com.stoutner.privacybrowser.BannerAd;
92 import com.stoutner.privacybrowser.BuildConfig;
93 import com.stoutner.privacybrowser.R;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
95 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
96 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
98 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
99 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
100 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
101 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
103 import java.io.BufferedReader;
104 import java.io.ByteArrayInputStream;
105 import java.io.IOException;
106 import java.io.InputStreamReader;
107 import java.io.UnsupportedEncodingException;
108 import java.net.MalformedURLException;
110 import java.net.URLDecoder;
111 import java.net.URLEncoder;
112 import java.util.HashMap;
113 import java.util.HashSet;
114 import java.util.Map;
115 import java.util.Set;
117 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
118 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
119 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
121 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
122 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
123 public static ActionBar appBar;
125 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, and `EditBookmarkDialog`.
126 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
127 public static Bitmap favoriteIcon;
129 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
130 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
131 public static String formattedUrlString;
133 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
134 public static SslCertificate sslCertificate;
136 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
137 public static String orbotStatus;
139 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
140 public static String webViewTitle;
143 // `navigatingHistory` is used in `onCreate()` and `onNavigationItemSelected()`.
144 private boolean navigatingHistory;
146 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
147 private DrawerLayout drawerLayout;
149 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
150 private CoordinatorLayout rootCoordinatorLayout;
152 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
153 private WebView mainWebView;
155 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
156 private FrameLayout fullScreenVideoFrameLayout;
158 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
159 private SwipeRefreshLayout swipeRefreshLayout;
161 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
162 private CookieManager cookieManager;
164 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
165 private final Map<String, String> customHeaders = new HashMap<>();
167 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
168 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
169 private Boolean javaScriptEnabled;
171 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applySettings()`.
172 private boolean firstPartyCookiesEnabled;
174 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
175 private boolean thirdPartyCookiesEnabled;
177 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
178 private boolean domStorageEnabled;
180 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
181 private boolean saveFormDataEnabled;
183 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
184 private boolean swipeToRefreshEnabled;
186 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
187 private String homepage;
189 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
190 private String javaScriptDisabledSearchURL;
192 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
193 private String javaScriptEnabledSearchURL;
195 // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
196 private boolean adBlockerEnabled;
198 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
199 private boolean fullScreenBrowsingModeEnabled;
201 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applySettings()`.
202 private boolean inFullScreenBrowsingMode;
204 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
205 private boolean hideSystemBarsOnFullscreen;
207 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
208 private boolean translucentNavigationBarOnFullscreen;
210 // `proxyThroughOrbot` is used in `onCreate()` and `applySettings()`
211 private boolean proxyThroughOrbot;
213 // `currentDomain` is used in `onCreate(), `onNavigationItemSelected()`, and `applyDomainSettings()`.
214 private String currentDomain;
216 // `pendingUrl` is used in `onCreate()` and `applySettings()`
217 private static String pendingUrl;
219 // `waitingForOrbotData` is used in `onCreate()` and `applySettings()`.
220 private String waitingForOrbotHTMLString;
222 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
223 private LinearLayout findOnPageLinearLayout;
225 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
226 private EditText findOnPageEditText;
228 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
229 private Menu mainMenu;
231 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
232 private ActionBarDrawerToggle drawerToggle;
234 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
235 private Toolbar supportAppBar;
237 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `loadUrl()`.
238 private EditText urlTextBox;
240 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
243 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
244 private SslErrorHandler sslErrorHandler;
246 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
247 private InputMethodManager inputMethodManager;
249 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
250 private RelativeLayout mainWebViewRelativeLayout;
253 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers.
254 @SuppressLint("SetJavaScriptEnabled")
255 protected void onCreate(Bundle savedInstanceState) {
256 super.onCreate(savedInstanceState);
257 setContentView(R.layout.main_drawerlayout);
259 // Get a handle for `inputMethodManager`.
260 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
262 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
263 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
264 setSupportActionBar(supportAppBar);
265 appBar = getSupportActionBar();
267 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
268 assert appBar != null;
270 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
271 appBar.setCustomView(R.layout.url_app_bar);
272 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
274 // Set the "go" button on the keyboard to load the URL in urlTextBox.
275 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
276 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
278 public boolean onKey(View v, int keyCode, KeyEvent event) {
279 // If the event is a key-down event on the `enter` button, load the URL.
280 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
281 // Load the URL into the mainWebView and consume the event.
283 loadUrlFromTextBox();
284 } catch (UnsupportedEncodingException e) {
287 // If the enter key was pressed, consume the event.
290 // If any other key was pressed, do not consume the event.
296 // Set `waitingForOrbotHTMLString`.
297 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
299 // Initialize `currentDomain`, `pendingUrl`, and `orbotStatus`.
302 orbotStatus = "unknown";
304 // Create an Orbot status `BroadcastReceiver`.
305 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
307 public void onReceive(Context context, Intent intent) {
308 // Store the content of the status message in `orbotStatus`.
309 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
311 // If we are waiting on `pendingUrl`, load it now that Orbot is connected.
312 if (orbotStatus.equals("ON") && !pendingUrl.isEmpty()) {
314 // Wait 500 milliseconds, because Orbot isn't really ready yet.
317 } catch (InterruptedException exception) {
321 // Copy `pendingUrl` to `formattedUrlString` and reset `pendingUrl` to be empty.
322 formattedUrlString = pendingUrl;
325 // Load `formattedUrlString
326 loadUrl(formattedUrlString);
331 // Register `orbotStatusBroadcastReceiver` on `this` context.
332 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
334 // Get handles for views that need to be accessed.
335 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
336 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
337 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
338 mainWebView = (WebView) findViewById(R.id.main_webview);
339 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
340 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
341 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
343 // Create a double-tap listener to toggle full-screen mode.
344 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
345 // Override `onDoubleTap()`. All other events are handled using the default settings.
347 public boolean onDoubleTap(MotionEvent event) {
348 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
349 // Toggle `inFullScreenBrowsingMode`.
350 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
352 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
353 // Hide the `appBar`.
356 // Hide the `BannerAd` in the free flavor.
357 if (BuildConfig.FLAVOR.contentEquals("free")) {
358 BannerAd.hideAd(adView);
361 // Modify the system bars.
362 if (hideSystemBarsOnFullscreen) { // Hide everything.
363 // Remove the translucent overlays.
364 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
366 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
367 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
369 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
370 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
371 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
373 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
375 // Set `rootCoordinatorLayout` to fill the whole screen.
376 rootCoordinatorLayout.setFitsSystemWindows(false);
377 } else { // Hide everything except the status and navigation bars.
378 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
379 rootCoordinatorLayout.setFitsSystemWindows(false);
381 if (translucentNavigationBarOnFullscreen) { // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
382 // Set the navigation bar to be translucent.
383 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
386 } else { // Switch to normal viewing mode.
387 // Show the `appBar`.
390 // Show the `BannerAd` in the free flavor.
391 if (BuildConfig.FLAVOR.contentEquals("free")) {
392 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
393 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
395 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
396 adView = findViewById(R.id.adview);
399 // Remove the translucent navigation bar flag if it is set.
400 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
402 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
403 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
405 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
406 rootCoordinatorLayout.setSystemUiVisibility(0);
408 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
409 rootCoordinatorLayout.setFitsSystemWindows(true);
412 // Consume the double-tap.
414 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
420 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
421 mainWebView.setOnTouchListener(new View.OnTouchListener() {
423 public boolean onTouch(View v, MotionEvent event) {
424 // Send the `event` to `gestureDetector`.
425 return gestureDetector.onTouchEvent(event);
429 // Update `findOnPageCountTextView`.
430 mainWebView.setFindListener(new WebView.FindListener() {
431 // Get a handle for `findOnPageCountTextView`.
432 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
435 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
436 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
437 // Set `findOnPageCountTextView` to `0/0`.
438 findOnPageCountTextView.setText(R.string.zero_of_zero);
439 } else if (isDoneCounting) { // There are matches.
440 // `activeMatchOrdinal` is zero-based.
441 int activeMatch = activeMatchOrdinal + 1;
443 // Set `findOnPageCountTextView`.
444 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
449 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
450 findOnPageEditText.addTextChangedListener(new TextWatcher() {
452 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
457 public void onTextChanged(CharSequence s, int start, int before, int count) {
462 public void afterTextChanged(Editable s) {
463 // Search for the text in `mainWebView`.
464 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
468 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
469 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
471 public boolean onKey(View v, int keyCode, KeyEvent event) {
472 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
473 // Hide the soft keyboard. `0` indicates no additional flags.
474 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
476 // Consume the event.
478 } else { // A different key was pressed.
479 // Do not consume the event.
485 // Implement swipe to refresh
486 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
487 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
488 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
490 public void onRefresh() {
491 mainWebView.reload();
495 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
496 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
498 // Listen for touches on the navigation menu.
499 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
500 navigationView.setNavigationItemSelectedListener(this);
502 // Get handles for `navigationMenu` and the back and forward menu items. The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
503 final Menu navigationMenu = navigationView.getMenu();
504 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
505 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
506 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
508 // The `DrawerListener` allows us to update the Navigation Menu.
509 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
511 public void onDrawerSlide(View drawerView, float slideOffset) {
515 public void onDrawerOpened(View drawerView) {
519 public void onDrawerClosed(View drawerView) {
523 public void onDrawerStateChanged(int newState) {
524 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
525 // Update the `Back`, `Forward`, and `History` menu items.
526 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
527 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
528 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
530 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
531 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
536 // drawerToggle creates the hamburger icon at the start of the AppBar.
537 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
539 // Initialize `adServerSet`.
540 final Set<String> adServersSet = new HashSet<>();
542 // Load the list of ad servers into memory.
544 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
545 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
547 // Create a string for storing each ad server.
550 // Populate `adServersSet`.
551 while ((adServer = bufferedReader.readLine()) != null) {
552 adServersSet.add(adServer);
555 // Close `bufferedReader`.
556 bufferedReader.close();
557 } catch (IOException ioException) {
558 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
561 mainWebView.setWebViewClient(new WebViewClient() {
562 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
563 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
564 @SuppressWarnings("deprecation")
566 public boolean shouldOverrideUrlLoading(WebView view, String url) {
567 // Use an external email program if the link begins with `mailto:`.
568 if (url.startsWith("mailto:")) {
569 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
570 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
572 // Parse the url and set it as the data for the `Intent`.
573 emailIntent.setData(Uri.parse(url));
575 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
576 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
579 startActivity(emailIntent);
581 } else { // Load the URL in Privacy Browser.
587 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
588 @SuppressWarnings("deprecation")
590 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
591 if (adBlockerEnabled) { // Block ads.
592 // Extract the host from `url`.
593 Uri requestUri = Uri.parse(url);
594 String requestHost = requestUri.getHost();
596 // Initialize a variable to track if this is an ad server.
597 boolean requestHostIsAdServer = false;
599 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
600 if (requestHost != null) {
601 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
602 if (adServersSet.contains(requestHost)) {
603 requestHostIsAdServer = true;
606 // Strip out the lowest subdomain of `requestHost`.
607 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
611 if (requestHostIsAdServer) { // It is an ad server.
612 // Return an empty `WebResourceResponse`.
613 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
614 } else { // It is not an ad server.
615 // `return null` loads the requested resource.
618 } else { // Ad blocking is disabled.
619 // `return null` loads the requested resource.
624 // Update the URL in urlTextBox when the page starts to load.
626 public void onPageStarted(WebView view, String url, Bitmap favicon) {
627 // Check to see if we are waiting on Orbot.
628 if (pendingUrl.isEmpty()) { // We are not waiting on Orbot, so we need to process the URL.
629 // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
630 formattedUrlString = url;
632 // Display the loading URL is the URL text box.
633 urlTextBox.setText(url);
635 // Apply any custom domain settings if the URL was loaded by navigating history.
636 if (navigatingHistory) {
637 applyDomainSettings(url);
642 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
644 public void onPageFinished(WebView view, String url) {
645 // Check to see if we are waiting on Orbot.
646 if (pendingUrl.isEmpty()) { // we are not waiting on Orbot, so we need to process the URL.
647 // Check to see if `WebView` has set `url` to be `about:blank`.
648 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
649 // Set `formattedUrlString` to `""`.
650 formattedUrlString = "";
652 // Update `urlTextBox`.
653 urlTextBox.setText(formattedUrlString);
655 // Request focus for `urlTextBox`.
656 urlTextBox.requestFocus();
658 // Display the keyboard.
659 inputMethodManager.showSoftInput(urlTextBox, 0);
660 } else { // `WebView` has loaded a webpage.
661 // Set `formattedUrlString`.
662 formattedUrlString = url;
664 // Only update `urlTextBox` if the user is not typing in it.
665 if (!urlTextBox.hasFocus()) {
666 urlTextBox.setText(formattedUrlString);
670 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
671 sslCertificate = mainWebView.getCertificate();
675 // Handle SSL Certificate errors.
677 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
678 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
679 sslErrorHandler = handler;
681 // Display the SSL error `AlertDialog`.
682 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
683 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
687 // Get a handle for the progress bar.
688 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
690 mainWebView.setWebChromeClient(new WebChromeClient() {
691 // Update the progress bar when a page is loading.
693 public void onProgressChanged(WebView view, int progress) {
694 progressBar.setProgress(progress);
695 if (progress < 100) {
696 progressBar.setVisibility(View.VISIBLE);
698 progressBar.setVisibility(View.GONE);
700 //Stop the `SwipeToRefresh` indicator if it is running
701 swipeRefreshLayout.setRefreshing(false);
705 // Set the favorite icon when it changes.
707 public void onReceivedIcon(WebView view, Bitmap icon) {
708 // Save a copy of the favorite icon.
711 // Place the favorite icon in the appBar.
712 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favorite_icon);
713 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
716 // Save a copy of the title when it changes.
718 public void onReceivedTitle(WebView view, String title) {
719 // Save a copy of the title.
720 webViewTitle = title;
723 // Enter full screen video
725 public void onShowCustomView(View view, CustomViewCallback callback) {
726 // Pause the ad if this is the free flavor.
727 if (BuildConfig.FLAVOR.contentEquals("free")) {
728 BannerAd.pauseAd(adView);
731 // Remove the translucent overlays.
732 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
734 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
735 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
737 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
738 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
739 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
741 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
743 // Set `rootCoordinatorLayout` to fill the entire screen.
744 rootCoordinatorLayout.setFitsSystemWindows(false);
746 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
747 fullScreenVideoFrameLayout.addView(view);
748 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
751 // Exit full screen video
752 public void onHideCustomView() {
753 // Hide `fullScreenVideoFrameLayout`.
754 fullScreenVideoFrameLayout.removeAllViews();
755 fullScreenVideoFrameLayout.setVisibility(View.GONE);
757 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
758 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
760 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
761 rootCoordinatorLayout.setFitsSystemWindows(true);
763 // Show the ad if this is the free flavor.
764 if (BuildConfig.FLAVOR.contentEquals("free")) {
765 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
766 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
768 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
769 adView = findViewById(R.id.adview);
774 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
775 registerForContextMenu(mainWebView);
777 // Allow the downloading of files.
778 mainWebView.setDownloadListener(new DownloadListener() {
780 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
781 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
782 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
783 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
787 // Allow pinch to zoom.
788 mainWebView.getSettings().setBuiltInZoomControls(true);
790 // Hide zoom controls.
791 mainWebView.getSettings().setDisplayZoomControls(false);
793 // Initialize cookieManager.
794 cookieManager = CookieManager.getInstance();
796 // 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).
797 customHeaders.put("X-Requested-With", "");
799 // Initialize the default preference values the first time the program is run. `this` is the context. `false` keeps this command from resetting any current preferences back to default.
800 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
802 // Get the intent that started the app.
803 final Intent launchingIntent = getIntent();
805 // Extract the launching intent data as `launchingIntentUriData`.
806 final Uri launchingIntentUriData = launchingIntent.getData();
808 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
809 if (launchingIntentUriData != null) {
810 formattedUrlString = launchingIntentUriData.toString();
813 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
814 inFullScreenBrowsingMode = false;
816 // Initialize AdView for the free flavor.
817 adView = findViewById(R.id.adview);
819 // Initialize the privacy settings variables.
820 javaScriptEnabled = false;
821 firstPartyCookiesEnabled = false;
822 thirdPartyCookiesEnabled = false;
823 domStorageEnabled = false;
824 saveFormDataEnabled = false;
826 // Apply the app settings from the shared preferences.
829 // Load `formattedUrlString` if we are not proxying through Orbot and waiting for Orbot to connect.
830 if (!(proxyThroughOrbot && !orbotStatus.equals("ON"))) {
831 loadUrl(formattedUrlString);
834 // If the favorite icon is null, load the default.
835 if (favoriteIcon == null) {
836 // We have to use `ContextCompat` until API >= 21.
837 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
838 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
839 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
845 protected void onNewIntent(Intent intent) {
846 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
849 if (intent.getData() != null) {
850 // Get the intent data and convert it to a string.
851 final Uri intentUriData = intent.getData();
852 formattedUrlString = intentUriData.toString();
855 // Close the navigation drawer if it is open.
856 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
857 drawerLayout.closeDrawer(GravityCompat.START);
861 loadUrl(formattedUrlString);
863 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
864 mainWebView.requestFocus();
868 public boolean onCreateOptionsMenu(Menu menu) {
869 // Inflate the menu; this adds items to the action bar if it is present.
870 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
872 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
875 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
876 updatePrivacyIcons(false);
878 // Get handles for the menu items.
879 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
880 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
881 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
882 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
884 // Only display third-party cookies if SDK >= 21
885 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
887 // Get the shared preference values. `this` references the current context.
888 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
890 // Set the status of the additional app bar icons. The default is `false`.
891 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
892 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
893 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
894 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
895 } else { //Do not display the additional icons.
896 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
897 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
898 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
905 public boolean onPrepareOptionsMenu(Menu menu) {
906 // Get handles for the menu items.
907 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
908 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
909 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
910 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
911 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
912 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
913 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
915 // Set the status of the menu item checkboxes.
916 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
917 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
918 toggleDomStorage.setChecked(domStorageEnabled);
919 toggleSaveFormData.setChecked(saveFormDataEnabled);
921 // Enable third-party cookies if first-party cookies are enabled.
922 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
924 // Enable DOM Storage if JavaScript is enabled.
925 toggleDomStorage.setEnabled(javaScriptEnabled);
927 // Enable Clear Cookies if there are any.
928 clearCookies.setEnabled(cookieManager.hasCookies());
930 // Enable Clear Form Data is there is any.
931 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
932 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
934 // Only show `Refresh` if `swipeToRefresh` is disabled.
935 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
937 // Initialize font size variables.
938 int fontSize = mainWebView.getSettings().getTextZoom();
939 String fontSizeTitle;
940 MenuItem selectedFontSizeMenuItem;
942 // Prepare the font size title and current size menu item.
945 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
946 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
950 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
951 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
955 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
956 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
960 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
961 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
965 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
966 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
970 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
971 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
975 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
976 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
980 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
981 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
985 // Set the font size title and select the current size menu item.
986 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
987 fontSizeMenuItem.setTitle(fontSizeTitle);
988 selectedFontSizeMenuItem.setChecked(true);
990 // Run all the other default commands.
991 super.onPrepareOptionsMenu(menu);
993 // `return true` displays the menu.
998 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
999 @SuppressLint("SetJavaScriptEnabled")
1000 // removeAllCookies is deprecated, but it is required for API < 21.
1001 @SuppressWarnings("deprecation")
1002 public boolean onOptionsItemSelected(MenuItem menuItem) {
1003 int menuItemId = menuItem.getItemId();
1005 // Set the commands that relate to the menu entries.
1006 switch (menuItemId) {
1007 case R.id.toggleJavaScript:
1008 // Switch the status of javaScriptEnabled.
1009 javaScriptEnabled = !javaScriptEnabled;
1011 // Apply the new JavaScript status.
1012 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1014 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1015 updatePrivacyIcons(true);
1017 // Display a `Snackbar`.
1018 if (javaScriptEnabled) { // JavaScrip is enabled.
1019 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1020 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1021 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1022 } else { // Privacy mode.
1023 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1026 // Reload the WebView.
1027 mainWebView.reload();
1030 case R.id.toggleFirstPartyCookies:
1031 // Switch the status of firstPartyCookiesEnabled.
1032 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1034 // Update the menu checkbox.
1035 menuItem.setChecked(firstPartyCookiesEnabled);
1037 // Apply the new cookie status.
1038 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1040 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1041 updatePrivacyIcons(true);
1043 // Display a `Snackbar`.
1044 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1045 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1046 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1047 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1048 } else { // Privacy mode.
1049 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1052 // Reload the WebView.
1053 mainWebView.reload();
1056 case R.id.toggleThirdPartyCookies:
1057 if (Build.VERSION.SDK_INT >= 21) {
1058 // Switch the status of thirdPartyCookiesEnabled.
1059 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1061 // Update the menu checkbox.
1062 menuItem.setChecked(thirdPartyCookiesEnabled);
1064 // Apply the new cookie status.
1065 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1067 // Display a `Snackbar`.
1068 if (thirdPartyCookiesEnabled) {
1069 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1071 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1074 // Reload the WebView.
1075 mainWebView.reload();
1076 } // Else do nothing because SDK < 21.
1079 case R.id.toggleDomStorage:
1080 // Switch the status of domStorageEnabled.
1081 domStorageEnabled = !domStorageEnabled;
1083 // Update the menu checkbox.
1084 menuItem.setChecked(domStorageEnabled);
1086 // Apply the new DOM Storage status.
1087 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1089 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1090 updatePrivacyIcons(true);
1092 // Display a `Snackbar`.
1093 if (domStorageEnabled) {
1094 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1096 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1099 // Reload the WebView.
1100 mainWebView.reload();
1103 case R.id.toggleSaveFormData:
1104 // Switch the status of saveFormDataEnabled.
1105 saveFormDataEnabled = !saveFormDataEnabled;
1107 // Update the menu checkbox.
1108 menuItem.setChecked(saveFormDataEnabled);
1110 // Apply the new form data status.
1111 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1113 // Display a `Snackbar`.
1114 if (saveFormDataEnabled) {
1115 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1117 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1120 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1121 updatePrivacyIcons(true);
1123 // Reload the WebView.
1124 mainWebView.reload();
1127 case R.id.clearCookies:
1128 if (Build.VERSION.SDK_INT < 21) {
1129 cookieManager.removeAllCookie();
1131 cookieManager.removeAllCookies(null);
1133 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1136 case R.id.clearDomStorage:
1137 WebStorage webStorage = WebStorage.getInstance();
1138 webStorage.deleteAllData();
1139 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1142 case R.id.clearFormData:
1143 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1144 mainWebViewDatabase.clearFormData();
1145 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1148 case R.id.fontSizeFiftyPercent:
1149 mainWebView.getSettings().setTextZoom(50);
1152 case R.id.fontSizeSeventyFivePercent:
1153 mainWebView.getSettings().setTextZoom(75);
1156 case R.id.fontSizeOneHundredPercent:
1157 mainWebView.getSettings().setTextZoom(100);
1160 case R.id.fontSizeOneHundredTwentyFivePercent:
1161 mainWebView.getSettings().setTextZoom(125);
1164 case R.id.fontSizeOneHundredFiftyPercent:
1165 mainWebView.getSettings().setTextZoom(150);
1168 case R.id.fontSizeOneHundredSeventyFivePercent:
1169 mainWebView.getSettings().setTextZoom(175);
1172 case R.id.fontSizeTwoHundredPercent:
1173 mainWebView.getSettings().setTextZoom(200);
1177 Intent shareIntent = new Intent();
1178 shareIntent.setAction(Intent.ACTION_SEND);
1179 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1180 shareIntent.setType("text/plain");
1181 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1184 case R.id.find_on_page:
1185 // Hide the URL app bar.
1186 supportAppBar.setVisibility(View.GONE);
1188 // Show the Find on Page `RelativeLayout`.
1189 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1191 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1192 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1193 findOnPageEditText.postDelayed(new Runnable()
1198 // Set the focus on `findOnPageEditText`.
1199 findOnPageEditText.requestFocus();
1201 // Display the keyboard.
1202 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1208 mainWebView.reload();
1212 // Get a `PrintManager` instance.
1213 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1215 // Convert `mainWebView` to `printDocumentAdapter`.
1216 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1218 // Print the document. The print attributes are `null`.
1219 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1222 case R.id.addToHomescreen:
1223 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1224 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1225 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1227 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1231 // Don't consume the event.
1232 return super.onOptionsItemSelected(menuItem);
1236 // removeAllCookies is deprecated, but it is required for API < 21.
1237 @SuppressWarnings("deprecation")
1239 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1240 int menuItemId = menuItem.getItemId();
1242 switch (menuItemId) {
1248 if (mainWebView.canGoBack()) {
1249 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1250 navigatingHistory = true;
1252 // Load the previous website in the history.
1253 mainWebView.goBack();
1258 if (mainWebView.canGoForward()) {
1259 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1260 navigatingHistory = true;
1262 // Load the next website in the history.
1263 mainWebView.goForward();
1268 // Gte the `WebBackForwardList`.
1269 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1271 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1272 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1273 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1276 case R.id.bookmarks:
1277 // Launch BookmarksActivity.
1278 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1279 startActivity(bookmarksIntent);
1282 case R.id.downloads:
1283 // Launch the system Download Manager.
1284 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1286 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1287 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1289 startActivity(downloadManagerIntent);
1293 // Reset `currentDomain` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1296 // Launch `SettingsActivity`.
1297 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1298 startActivity(settingsIntent);
1302 // Reset `currentDomain` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1305 // Launch `DomainsActivity`.
1306 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1307 startActivity(domainsIntent);
1311 // Launch `GuideActivity`.
1312 Intent guideIntent = new Intent(this, GuideActivity.class);
1313 startActivity(guideIntent);
1317 // Launch `AboutActivity`.
1318 Intent aboutIntent = new Intent(this, AboutActivity.class);
1319 startActivity(aboutIntent);
1322 case R.id.clearAndExit:
1323 // Clear cookies. The commands changed slightly in API 21.
1324 if (Build.VERSION.SDK_INT >= 21) {
1325 cookieManager.removeAllCookies(null);
1327 cookieManager.removeAllCookie();
1330 // Clear DOM storage.
1331 WebStorage domStorage = WebStorage.getInstance();
1332 domStorage.deleteAllData();
1335 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1336 webViewDatabase.clearFormData();
1338 // Clear cache. The argument of "true" includes disk files.
1339 mainWebView.clearCache(true);
1341 // Clear the back/forward history.
1342 mainWebView.clearHistory();
1344 // Clear any SSL certificate preferences.
1345 mainWebView.clearSslPreferences();
1347 // Clear `formattedUrlString`.
1348 formattedUrlString = null;
1350 // Clear `customHeaders`.
1351 customHeaders.clear();
1353 // Detach all views from `mainWebViewRelativeLayout`.
1354 mainWebViewRelativeLayout.removeAllViews();
1356 // Destroy the internal state of `mainWebView`.
1357 mainWebView.destroy();
1359 // Manually delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1360 Runtime runtime = Runtime.getRuntime();
1361 String dataDirString = getApplicationInfo().dataDir; // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1363 runtime.exec("rm -rf " + dataDirString + "/app_webview");
1364 } catch (IOException e) {
1365 // Do nothing if the files do not exist.
1368 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1369 if (Build.VERSION.SDK_INT >= 21) {
1370 finishAndRemoveTask();
1375 // Remove the terminated program from RAM. The status code is `0`.
1383 // Close the navigation drawer.
1384 drawerLayout.closeDrawer(GravityCompat.START);
1389 public void onPostCreate(Bundle savedInstanceState) {
1390 super.onPostCreate(savedInstanceState);
1392 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1393 drawerToggle.syncState();
1397 public void onConfigurationChanged(Configuration newConfig) {
1398 super.onConfigurationChanged(newConfig);
1400 // Reload the ad for the free flavor if we are not in full screen mode.
1401 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1403 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1405 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1406 adView = findViewById(R.id.adview);
1409 // `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: https://code.google.com/p/android/issues/detail?id=20493#c8
1410 // ActivityCompat.invalidateOptionsMenu(this);
1414 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1415 // Store the `HitTestResult`.
1416 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1419 final String imageUrl;
1420 final String linkUrl;
1422 // Get a handle for the `ClipboardManager`.
1423 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1425 switch (hitTestResult.getType()) {
1426 // `SRC_ANCHOR_TYPE` is a link.
1427 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1428 // Get the target URL.
1429 linkUrl = hitTestResult.getExtra();
1431 // Set the target URL as the title of the `ContextMenu`.
1432 menu.setHeaderTitle(linkUrl);
1434 // Add a `Load URL` entry.
1435 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1437 public boolean onMenuItemClick(MenuItem item) {
1443 // Add a `Copy URL` entry.
1444 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1446 public boolean onMenuItemClick(MenuItem item) {
1447 // Save the link URL in a `ClipData`.
1448 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1450 // Set the `ClipData` as the clipboard's primary clip.
1451 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1456 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1457 menu.add(R.string.cancel);
1460 case WebView.HitTestResult.EMAIL_TYPE:
1461 // Get the target URL.
1462 linkUrl = hitTestResult.getExtra();
1464 // Set the target URL as the title of the `ContextMenu`.
1465 menu.setHeaderTitle(linkUrl);
1467 // Add a `Write Email` entry.
1468 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1470 public boolean onMenuItemClick(MenuItem item) {
1471 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1472 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1474 // Parse the url and set it as the data for the `Intent`.
1475 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1477 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1478 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1481 startActivity(emailIntent);
1486 // Add a `Copy Email Address` entry.
1487 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1489 public boolean onMenuItemClick(MenuItem item) {
1490 // Save the email address in a `ClipData`.
1491 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1493 // Set the `ClipData` as the clipboard's primary clip.
1494 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1499 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1500 menu.add(R.string.cancel);
1503 // `IMAGE_TYPE` is an image.
1504 case WebView.HitTestResult.IMAGE_TYPE:
1505 // Get the image URL.
1506 imageUrl = hitTestResult.getExtra();
1508 // Set the image URL as the title of the `ContextMenu`.
1509 menu.setHeaderTitle(imageUrl);
1511 // Add a `View Image` entry.
1512 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1514 public boolean onMenuItemClick(MenuItem item) {
1520 // Add a `Download Image` entry.
1521 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1523 public boolean onMenuItemClick(MenuItem item) {
1524 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1525 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1526 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1531 // Add a `Copy URL` entry.
1532 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1534 public boolean onMenuItemClick(MenuItem item) {
1535 // Save the image URL in a `ClipData`.
1536 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1538 // Set the `ClipData` as the clipboard's primary clip.
1539 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1544 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1545 menu.add(R.string.cancel);
1549 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1550 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1551 // Get the image URL.
1552 imageUrl = hitTestResult.getExtra();
1554 // Set the image URL as the title of the `ContextMenu`.
1555 menu.setHeaderTitle(imageUrl);
1557 // Add a `View Image` entry.
1558 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1560 public boolean onMenuItemClick(MenuItem item) {
1566 // Add a `Download Image` entry.
1567 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1569 public boolean onMenuItemClick(MenuItem item) {
1570 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1571 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1572 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1577 // Add a `Copy URL` entry.
1578 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1580 public boolean onMenuItemClick(MenuItem item) {
1581 // Save the image URL in a `ClipData`.
1582 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1584 // Set the `ClipData` as the clipboard's primary clip.
1585 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1590 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1591 menu.add(R.string.cancel);
1597 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1598 // Get shortcutNameEditText from the alert dialog.
1599 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1601 // Create the bookmark shortcut based on formattedUrlString.
1602 Intent bookmarkShortcut = new Intent();
1603 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1604 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1606 // Place the bookmark shortcut on the home screen.
1607 Intent placeBookmarkShortcut = new Intent();
1608 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1609 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1610 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1611 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1612 sendBroadcast(placeBookmarkShortcut);
1616 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1617 // Download the image if it has an HTTP or HTTPS URI.
1618 if (imageUrl.startsWith("http")) {
1619 // Get a handle for the system `DOWNLOAD_SERVICE`.
1620 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1622 // Parse `imageUrl`.
1623 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1625 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1626 if (firstPartyCookiesEnabled) {
1627 // Get the cookies for `imageUrl`.
1628 String cookies = cookieManager.getCookie(imageUrl);
1630 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1631 downloadRequest.addRequestHeader("Cookie", cookies);
1634 // Get the file name from `dialogFragment`.
1635 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1636 String imageName = downloadImageNameEditText.getText().toString();
1638 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1639 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1640 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1641 } else { // Only set the title using `imageName`.
1642 downloadRequest.setTitle(imageName);
1645 // Allow `MediaScanner` to index the download if it is a media file.
1646 downloadRequest.allowScanningByMediaScanner();
1648 // Add the URL as the description for the download.
1649 downloadRequest.setDescription(imageUrl);
1651 // Show the download notification after the download is completed.
1652 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1654 // Initiate the download.
1655 downloadManager.enqueue(downloadRequest);
1656 } else { // The image is not an HTTP or HTTPS URI.
1657 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1662 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1663 // Download the file if it has an HTTP or HTTPS URI.
1664 if (downloadUrl.startsWith("http")) {
1666 // Get a handle for the system `DOWNLOAD_SERVICE`.
1667 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1669 // Parse `downloadUrl`.
1670 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1672 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1673 if (firstPartyCookiesEnabled) {
1674 // Get the cookies for `downloadUrl`.
1675 String cookies = cookieManager.getCookie(downloadUrl);
1677 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1678 downloadRequest.addRequestHeader("Cookie", cookies);
1681 // Get the file name from `dialogFragment`.
1682 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1683 String fileName = downloadFileNameEditText.getText().toString();
1685 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1686 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1687 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1688 } else { // Only set the title using `fileName`.
1689 downloadRequest.setTitle(fileName);
1692 // Allow `MediaScanner` to index the download if it is a media file.
1693 downloadRequest.allowScanningByMediaScanner();
1695 // Add the URL as the description for the download.
1696 downloadRequest.setDescription(downloadUrl);
1698 // Show the download notification after the download is completed.
1699 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1701 // Initiate the download.
1702 downloadManager.enqueue(downloadRequest);
1703 } else { // The download is not an HTTP or HTTPS URI.
1704 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1708 public void viewSslCertificate(View view) {
1709 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1710 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1711 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1715 public void onSslErrorCancel() {
1716 sslErrorHandler.cancel();
1720 public void onSslErrorProceed() {
1721 sslErrorHandler.proceed();
1725 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1726 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1727 navigatingHistory = true;
1729 // Load the history entry.
1730 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1734 public void onClearHistory() {
1735 // Clear the history.
1736 mainWebView.clearHistory();
1739 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1741 public void onBackPressed() {
1742 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1743 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1744 drawerLayout.closeDrawer(GravityCompat.START);
1746 // Load the previous URL if available.
1747 if (mainWebView.canGoBack()) {
1748 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1749 navigatingHistory = true;
1752 mainWebView.goBack();
1754 // Pass `onBackPressed()` to the system.
1755 super.onBackPressed();
1761 public void onPause() {
1762 // Pause `mainWebView`.
1763 mainWebView.onPause();
1765 // Stop all JavaScript.
1766 mainWebView.pauseTimers();
1768 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1769 if (BuildConfig.FLAVOR.contentEquals("free")) {
1770 BannerAd.pauseAd(adView);
1777 public void onResume() {
1780 // Resume JavaScript (if enabled).
1781 mainWebView.resumeTimers();
1783 // Resume `mainWebView`.
1784 mainWebView.onResume();
1786 // Resume the adView for the free flavor.
1787 if (BuildConfig.FLAVOR.contentEquals("free")) {
1788 BannerAd.resumeAd(adView);
1793 public void onRestart() {
1796 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1799 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1800 updatePrivacyIcons(true);
1804 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1805 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1806 String unformattedUrlString = urlTextBox.getText().toString().trim();
1808 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1809 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1810 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1811 if (!unformattedUrlString.startsWith("http")) {
1812 unformattedUrlString = "http://" + unformattedUrlString;
1815 // Initialize `unformattedUrl`.
1816 URL unformattedUrl = null;
1818 // Convert unformattedUrlString to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
1820 unformattedUrl = new URL(unformattedUrlString);
1821 } catch (MalformedURLException e) {
1822 e.printStackTrace();
1825 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
1826 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1827 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1828 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1829 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1830 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1833 Uri.Builder formattedUri = new Uri.Builder();
1834 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1836 // Decode `formattedUri` as a `String` in `UTF-8`.
1837 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
1839 // Sanitize the search input and convert it to a search.
1840 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1842 // Use the correct search URL.
1843 if (javaScriptEnabled) { // JavaScript is enabled.
1844 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1845 } else { // JavaScript is disabled.
1846 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1850 loadUrl(formattedUrlString);
1852 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1853 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1857 private void loadUrl(String url) {
1858 // Apply any custom domain settings.
1859 applyDomainSettings(url);
1862 mainWebView.loadUrl(url, customHeaders);
1865 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
1866 @SuppressWarnings("deprecation")
1867 private void applyDomainSettings(String url) {
1868 // Parse the URL into a URI.
1869 Uri uri = Uri.parse(url);
1871 // Extract the domain from `uri`.
1872 String hostname = uri.getHost();
1874 // Only apply the domain settings if `hostname` is not the same as `currentDomain`. This allows the user to set temporary settings for JavaScript, Cookies, DOM Storage, etc.
1875 if (hostname != null && !hostname.equals(currentDomain)) {
1876 // Set the new `hostname` as the `currentDomain`.
1877 currentDomain = hostname;
1879 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
1880 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1881 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1883 // Get a full cursor from `domainsDatabaseHelper`.
1884 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
1886 // Initialize `domainSettingsSet`.
1887 Set<String> domainSettingsSet = new HashSet<>();
1889 // Get the domain name column index.
1890 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
1892 // Populate `domainSettingsSet`.
1893 for (int i = 0; i < domainNameCursor.getCount(); i++) {
1894 // Move `domainsCursor` to the current row.
1895 domainNameCursor.moveToPosition(i);
1897 // Store the domain name in `domainSettingsSet`.
1898 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
1901 // Close `domainNameCursor.
1902 domainNameCursor.close();
1904 // Initialize variables to track if this domain has stored domain settings, and if so, under which name.
1905 boolean hostHasDomainSettings = false;
1906 String domainNameInDatabase = null;
1908 // Check the hostname.
1909 if (domainSettingsSet.contains(hostname)) {
1910 hostHasDomainSettings = true;
1911 domainNameInDatabase = hostname;
1914 // Check all the subdomains of `hostname` against wildcard domains in `domainCursor`.
1915 while (hostname.contains(".") && !hostHasDomainSettings) { // Stop checking if we run out of `.` or if we already know that `hostHasDomainSettings` is `true`.
1916 if (domainSettingsSet.contains("*." + hostname)) { // Check the host name prepended by `*.`.
1917 hostHasDomainSettings = true;
1918 domainNameInDatabase = "*." + hostname;
1921 // Strip out the lowest subdomain of `host`.
1922 hostname = hostname.substring(hostname.indexOf(".") + 1);
1925 RelativeLayout urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
1927 if (hostHasDomainSettings) { // The url we are loading has custom domain settings.
1928 // Get a cursor for the current host and move it to the first position.
1929 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
1930 currentHostDomainSettingsCursor.moveToFirst();
1932 // Get the settings from the cursor.
1933 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
1934 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
1935 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
1936 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
1937 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
1938 String userAgentString = (currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT)));
1939 int fontSize = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE)));
1941 // Close `currentHostDomainSettingsCursor`.
1942 currentHostDomainSettingsCursor.close();
1944 // Apply the domain settings.
1945 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1946 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1947 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1948 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1949 mainWebView.getSettings().setTextZoom(fontSize);
1951 // Set third-party cookies status if API >= 21.
1952 if (Build.VERSION.SDK_INT >= 21) {
1953 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1956 // Set the user agent.
1957 if (userAgentString.equals("WebView default user agent")) {
1958 // Set the user agent to `""`, which uses the default value.
1959 mainWebView.getSettings().setUserAgentString("");
1961 // Use the selected user agent.
1962 mainWebView.getSettings().setUserAgentString(userAgentString);
1965 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
1966 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
1967 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
1968 // Get the shared preference values. `this` references the current context.
1969 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1971 // Store the values from `sharedPreferences` in variables.
1972 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1973 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1974 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1975 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1976 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1977 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1978 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1979 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1981 // Apply the default settings.
1982 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1983 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1984 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1985 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1986 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1988 // Set third-party cookies status if API >= 21.
1989 if (Build.VERSION.SDK_INT >= 21) {
1990 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1993 // Set the default user agent.
1994 switch (userAgentString) {
1995 case "WebView default user agent":
1996 // Set the user agent to `""`, which uses the default value.
1997 mainWebView.getSettings().setUserAgentString("");
2000 case "Custom user agent":
2001 // Set the custom user agent.
2002 mainWebView.getSettings().setUserAgentString(customUserAgentString);
2006 // Use the selected user agent.
2007 mainWebView.getSettings().setUserAgentString(userAgentString);
2011 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2012 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2015 // Close `domainsDatabaseHelper`.
2016 domainsDatabaseHelper.close();
2018 // Update the privacy icons, but only if `mainMenu` has already been populated.
2019 if (mainMenu != null) {
2020 updatePrivacyIcons(true);
2025 public void findPreviousOnPage(View view) {
2026 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2027 mainWebView.findNext(false);
2030 public void findNextOnPage(View view) {
2031 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2032 mainWebView.findNext(true);
2035 public void closeFindOnPage(View view) {
2036 // Delete the contents of `find_on_page_edittext`.
2037 findOnPageEditText.setText(null);
2039 // Clear the highlighted phrases.
2040 mainWebView.clearMatches();
2042 // Hide the Find on Page `RelativeLayout`.
2043 findOnPageLinearLayout.setVisibility(View.GONE);
2045 // Show the URL app bar.
2046 supportAppBar.setVisibility(View.VISIBLE);
2048 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2049 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2052 private void applyAppSettings() {
2053 // Get the shared preference values. `this` references the current context.
2054 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2056 // Store the values from `sharedPreferences` in variables.
2057 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
2058 String javaScriptDisabledSearchCustomURLString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
2059 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
2060 String javaScriptEnabledSearchCustomURLString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
2061 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
2062 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2063 String torJavaScriptDisabledSearchString = sharedPreferences.getString("tor_javascript_disabled_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2064 String torJavaScriptDisabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_disabled_search_custom_url", "");
2065 String torJavaScriptEnabledSearchString = sharedPreferences.getString("tor_javascript_enabled_search", "https://3g2upl4pq6kufc4m.onion/?q=");
2066 String torJavaScriptEnabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_enabled_search_custom_url", "");
2067 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
2068 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2069 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2070 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2071 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
2072 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2073 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2075 // Set the homepage, search, and proxy options.
2076 if (proxyThroughOrbot) { // Set the Tor options.
2077 // Set `torHomepageString` as `homepage`.
2078 homepage = torHomepageString;
2080 // If formattedUrlString is null assign the homepage to it.
2081 if (formattedUrlString == null) {
2082 formattedUrlString = homepage;
2085 // Set JavaScript disabled search.
2086 if (torJavaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2087 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchCustomURLString;
2088 } else { // Use the string from the pre-built list.
2089 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchString;
2092 // Set JavaScript enabled search.
2093 if (torJavaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2094 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchCustomURLString;
2095 } else { // Use the string from the pre-built list.
2096 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchString;
2099 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2100 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2102 // Display a message to the user if we are waiting on Orbot.
2103 if (!orbotStatus.equals("ON")) {
2104 // Save `formattedUrlString` in `pendingUrl`.
2105 pendingUrl = formattedUrlString;
2107 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2108 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2110 } else { // Set the non-Tor options.
2111 // Set `homepageString` as `homepage`.
2112 homepage = homepageString;
2114 // If formattedUrlString is null assign the homepage to it.
2115 if (formattedUrlString == null) {
2116 formattedUrlString = homepage;
2119 // Set JavaScript disabled search.
2120 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2121 javaScriptDisabledSearchURL = javaScriptDisabledSearchCustomURLString;
2122 } else { // Use the string from the pre-built list.
2123 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
2126 // Set JavaScript enabled search.
2127 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
2128 javaScriptEnabledSearchURL = javaScriptEnabledSearchCustomURLString;
2129 } else { // Use the string from the pre-built list.
2130 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
2133 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2134 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2136 // Reset `pendingUrl` if we are currently waiting for Orbot to connect.
2137 if (!pendingUrl.isEmpty()) {
2138 formattedUrlString = pendingUrl;
2143 // Set swipe to refresh.
2144 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2146 // Set Do Not Track status.
2147 if (doNotTrackEnabled) {
2148 customHeaders.put("DNT", "1");
2150 customHeaders.remove("DNT");
2153 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2154 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2155 if (hideSystemBarsOnFullscreen) { // Hide everything.
2156 // Remove the translucent navigation setting if it is currently flagged.
2157 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2159 // Remove the translucent status bar overlay.
2160 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2162 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2163 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2165 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2166 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2167 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2169 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2170 } else { // Hide everything except the status and navigation bars.
2171 // Add the translucent status flag if it is unset.
2172 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2174 if (translucentNavigationBarOnFullscreen) {
2175 // Set the navigation bar to be translucent.
2176 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2178 // Set the navigation bar to be black.
2179 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2182 } else { // Switch to normal viewing mode.
2183 // Reset `inFullScreenBrowsingMode` to `false`.
2184 inFullScreenBrowsingMode = false;
2186 // Show the `appBar`.
2189 // Show the `BannerAd` in the free flavor.
2190 if (BuildConfig.FLAVOR.contentEquals("free")) {
2191 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2192 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2194 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2195 adView = findViewById(R.id.adview);
2198 // Remove the translucent navigation bar flag if it is set.
2199 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2201 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2202 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2204 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2205 rootCoordinatorLayout.setSystemUiVisibility(0);
2207 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2208 rootCoordinatorLayout.setFitsSystemWindows(true);
2212 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2213 // Get handles for the icons.
2214 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
2215 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
2216 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
2217 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
2219 // Update `privacyIcon`.
2220 if (javaScriptEnabled) { // JavaScript is enabled.
2221 privacyIcon.setIcon(R.drawable.javascript_enabled);
2222 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2223 privacyIcon.setIcon(R.drawable.warning);
2224 } else { // All the dangerous features are disabled.
2225 privacyIcon.setIcon(R.drawable.privacy_mode);
2228 // Update `firstPartyCookiesIcon`.
2229 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2230 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
2231 } else { // First-party cookies are disabled.
2232 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
2235 // Update `domStorageIcon`.
2236 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2237 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
2238 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2239 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2240 } else { // JavaScript is disabled, so DOM storage is ghosted.
2241 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2244 // Update `formDataIcon`.
2245 if (saveFormDataEnabled) { // Form data is enabled.
2246 formDataIcon.setIcon(R.drawable.form_data_enabled);
2247 } else { // Form data is disabled.
2248 formDataIcon.setIcon(R.drawable.form_data_disabled);
2251 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2252 if (runInvalidateOptionsMenu) {
2253 ActivityCompat.invalidateOptionsMenu(this);