2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser;
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.app.DialogFragment;
25 import android.app.DownloadManager;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.SharedPreferences;
29 import android.content.res.Configuration;
30 import android.graphics.Bitmap;
31 import android.graphics.drawable.BitmapDrawable;
32 import android.graphics.drawable.Drawable;
33 import android.net.Uri;
34 import android.net.http.SslCertificate;
35 import android.net.http.SslError;
36 import android.os.Build;
37 import android.os.Bundle;
38 import android.preference.PreferenceManager;
39 import android.print.PrintDocumentAdapter;
40 import android.print.PrintManager;
41 import android.support.annotation.NonNull;
42 import android.support.design.widget.NavigationView;
43 import android.support.design.widget.Snackbar;
44 import android.support.v4.app.ActivityCompat;
45 import android.support.v4.content.ContextCompat;
46 import android.support.v4.view.GravityCompat;
47 import android.support.v4.widget.DrawerLayout;
48 import android.support.v4.widget.SwipeRefreshLayout;
49 import android.support.v7.app.ActionBar;
50 import android.support.v7.app.ActionBarDrawerToggle;
51 import android.support.v7.app.AppCompatActivity;
52 import android.support.v7.app.AppCompatDialogFragment;
53 import android.support.v7.widget.Toolbar;
54 import android.util.Patterns;
55 import android.view.KeyEvent;
56 import android.view.Menu;
57 import android.view.MenuItem;
58 import android.view.View;
59 import android.view.inputmethod.InputMethodManager;
60 import android.webkit.CookieManager;
61 import android.webkit.DownloadListener;
62 import android.webkit.SslErrorHandler;
63 import android.webkit.WebChromeClient;
64 import android.webkit.WebStorage;
65 import android.webkit.WebView;
66 import android.webkit.WebViewClient;
67 import android.webkit.WebViewDatabase;
68 import android.widget.EditText;
69 import android.widget.FrameLayout;
70 import android.widget.ImageView;
71 import android.widget.ProgressBar;
73 import java.io.UnsupportedEncodingException;
74 import java.net.MalformedURLException;
76 import java.net.URLEncoder;
77 import java.util.HashMap;
80 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
81 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
82 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener {
84 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
85 // It is also used in `onCreate()` and `onOptionsItemSelected()`.
86 public static ActionBar appBar;
88 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
89 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
90 public static Bitmap favoriteIcon;
92 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
93 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
94 public static String formattedUrlString;
96 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
97 public static SslCertificate sslCertificate;
100 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `loadUrlFromTextBox()`.
101 private WebView mainWebView;
103 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
104 private SwipeRefreshLayout swipeRefreshLayout;
106 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
107 private CookieManager cookieManager;
109 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
110 private final Map<String, String> customHeaders = new HashMap<>();
112 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
113 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
114 private Boolean javaScriptEnabled;
116 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
117 private boolean firstPartyCookiesEnabled;
119 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
120 private boolean thirdPartyCookiesEnabled;
122 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
123 private boolean domStorageEnabled;
125 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
126 private boolean saveFormDataEnabled;
128 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
129 private boolean swipeToRefreshEnabled;
131 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
132 private String homepage;
134 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
135 private String javaScriptDisabledSearchURL;
137 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
138 private String javaScriptEnabledSearchURL;
140 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
141 private Menu mainMenu;
143 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
144 private ActionBarDrawerToggle drawerToggle;
146 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
147 private DrawerLayout drawerLayout;
149 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
150 private EditText urlTextBox;
152 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
155 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
156 private SslErrorHandler sslErrorHandler;
158 private MenuItem toggleJavaScript;
161 // 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.
162 @SuppressLint("SetJavaScriptEnabled")
163 protected void onCreate(Bundle savedInstanceState) {
164 super.onCreate(savedInstanceState);
165 setContentView(R.layout.main_coordinatorlayout);
167 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
168 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
169 setSupportActionBar(supportAppBar);
170 appBar = getSupportActionBar();
172 // This is needed to get rid of the Android Studio warning that appBar might be null.
173 assert appBar != null;
175 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
176 appBar.setCustomView(R.layout.url_app_bar);
177 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
179 // Set the "go" button on the keyboard to load the URL in urlTextBox.
180 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
181 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
182 public boolean onKey(View v, int keyCode, KeyEvent event) {
183 // If the event is a key-down event on the "enter" button, load the URL.
184 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
185 // Load the URL into the mainWebView and consume the event.
187 loadUrlFromTextBox();
188 } catch (UnsupportedEncodingException e) {
191 // If the enter key was pressed, consume the event.
194 // If any other key was pressed, do not consume the event.
200 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
202 // Implement swipe to refresh
203 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
204 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
205 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
207 public void onRefresh() {
208 mainWebView.reload();
212 mainWebView = (WebView) findViewById(R.id.mainWebView);
214 // Create the navigation drawer.
215 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
216 // The DrawerTitle identifies the drawer in accessibility mode.
217 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
219 // Listen for touches on the navigation menu.
220 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
221 navigationView.setNavigationItemSelectedListener(this);
223 // drawerToggle creates the hamburger icon at the start of the AppBar.
224 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
226 mainWebView.setWebViewClient(new WebViewClient() {
227 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
228 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
229 @SuppressWarnings("deprecation")
231 public boolean shouldOverrideUrlLoading(WebView view, String url) {
232 // Use an external email program if the link begins with "mailto:".
233 if (url.startsWith("mailto:")) {
234 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
235 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
237 // Parse the url and set it as the data for the `Intent`.
238 emailIntent.setData(Uri.parse(url));
240 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
241 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
244 startActivity(emailIntent);
246 } else { // Load the URL in Privacy Browser.
247 mainWebView.loadUrl(url, customHeaders);
252 // Update the URL in urlTextBox when the page starts to load.
254 public void onPageStarted(WebView view, String url, Bitmap favicon) {
255 // 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.
256 formattedUrlString = url;
258 // Display the loading URL is the URL text box.
259 urlTextBox.setText(url);
262 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
264 public void onPageFinished(WebView view, String url) {
265 formattedUrlString = url;
267 // Only update urlTextBox if the user is not typing in it.
268 if (!urlTextBox.hasFocus()) {
269 urlTextBox.setText(formattedUrlString);
272 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
273 sslCertificate = mainWebView.getCertificate();
276 // Handle SSL Certificate errors.
278 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
279 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
280 sslErrorHandler = handler;
282 // Display the SSL error `AlertDialog`.
283 DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
284 sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
288 mainWebView.setWebChromeClient(new WebChromeClient() {
289 // Update the progress bar when a page is loading.
291 public void onProgressChanged(WebView view, int progress) {
292 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
293 progressBar.setProgress(progress);
294 if (progress < 100) {
295 progressBar.setVisibility(View.VISIBLE);
297 progressBar.setVisibility(View.GONE);
299 //Stop the `SwipeToRefresh` indicator if it is running
300 swipeRefreshLayout.setRefreshing(false);
304 // Set the favorite icon when it changes.
306 public void onReceivedIcon(WebView view, Bitmap icon) {
307 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
310 // Place the favorite icon in the appBar.
311 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
312 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
315 // Enter full screen video
317 public void onShowCustomView(View view, CustomViewCallback callback) {
320 // Show the fullScreenVideoFrameLayout.
321 fullScreenVideoFrameLayout.addView(view);
322 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
324 // Hide the mainWebView.
325 mainWebView.setVisibility(View.GONE);
327 // Hide the ad if this is the free flavor.
328 BannerAd.hideAd(adView);
330 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
331 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
332 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
334 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
337 // Exit full screen video
338 public void onHideCustomView() {
341 // Show the mainWebView.
342 mainWebView.setVisibility(View.VISIBLE);
344 // Show the ad if this is the free flavor.
345 BannerAd.showAd(adView);
347 // Hide the fullScreenVideoFrameLayout.
348 fullScreenVideoFrameLayout.removeAllViews();
349 fullScreenVideoFrameLayout.setVisibility(View.GONE);
353 // Allow the downloading of files.
354 mainWebView.setDownloadListener(new DownloadListener() {
356 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
357 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
358 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
359 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
363 // Allow pinch to zoom.
364 mainWebView.getSettings().setBuiltInZoomControls(true);
366 // Hide zoom controls.
367 mainWebView.getSettings().setDisplayZoomControls(false);
369 // Initialize cookieManager.
370 cookieManager = CookieManager.getInstance();
372 // 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).
373 customHeaders.put("X-Requested-With", "");
375 // Initialize the default preference values the first time the program is run.
376 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
378 // Apply the settings from the shared preferences.
381 // Get the intent information that started the app.
382 final Intent intent = getIntent();
384 if (intent.getData() != null) {
385 // Get the intent data and convert it to a string.
386 final Uri intentUriData = intent.getData();
387 formattedUrlString = intentUriData.toString();
390 // If formattedUrlString is null assign the homepage to it.
391 if (formattedUrlString == null) {
392 formattedUrlString = homepage;
395 // Load the initial website.
396 mainWebView.loadUrl(formattedUrlString, customHeaders);
398 // If the favorite icon is null, load the default.
399 if (favoriteIcon == null) {
400 // We have to use `ContextCompat` until API >= 21.
401 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
402 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
403 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
406 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
407 adView = findViewById(R.id.adView);
408 BannerAd.requestAd(adView);
413 protected void onNewIntent(Intent intent) {
414 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
417 if (intent.getData() != null) {
418 // Get the intent data and convert it to a string.
419 final Uri intentUriData = intent.getData();
420 formattedUrlString = intentUriData.toString();
423 // Close the navigation drawer if it is open.
424 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
425 drawerLayout.closeDrawer(GravityCompat.START);
429 mainWebView.loadUrl(formattedUrlString, customHeaders);
431 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
432 mainWebView.requestFocus();
436 public boolean onCreateOptionsMenu(Menu menu) {
437 // Inflate the menu; this adds items to the action bar if it is present.
438 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
440 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
443 // Set the initial status of the privacy icons.
444 updatePrivacyIcons();
446 // Get handles for the menu items.
447 toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
448 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
449 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
450 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
451 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
453 // Only display third-Party Cookies if SDK >= 21
454 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
456 // Get the shared preference values. `this` references the current context.
457 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
459 // Set the status of the additional app bar icons. The default is `false`.
460 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
461 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
462 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
463 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
464 } else { //Do not display the additional icons.
465 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
466 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
467 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
474 public boolean onPrepareOptionsMenu(Menu menu) {
475 // Get handles for the menu items.
476 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
477 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
478 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
479 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
480 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
481 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
482 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
484 // Set the status of the menu item checkboxes.
485 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
486 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
487 toggleDomStorage.setChecked(domStorageEnabled);
488 toggleSaveFormData.setChecked(saveFormDataEnabled);
490 // Enable third-party cookies if first-party cookies are enabled.
491 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
493 // Enable DOM Storage if JavaScript is enabled.
494 toggleDomStorage.setEnabled(javaScriptEnabled);
496 // Enable Clear Cookies if there are any.
497 clearCookies.setEnabled(cookieManager.hasCookies());
499 // Enable Clear Form Data is there is any.
500 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
501 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
503 // Only show `Refresh` if `swipeToRefresh` is disabled.
504 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
506 // Initialize font size variables.
507 int fontSize = mainWebView.getSettings().getTextZoom();
508 String fontSizeTitle;
509 MenuItem selectedFontSizeMenuItem;
511 // Prepare the font size title and current size menu item.
514 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
515 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
519 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
520 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
524 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
525 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
529 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
530 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
534 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
535 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
539 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
540 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
544 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
545 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
549 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
550 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
554 // Set the font size title and select the current size menu item.
555 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
556 fontSizeMenuItem.setTitle(fontSizeTitle);
557 selectedFontSizeMenuItem.setChecked(true);
559 // Run all the other default commands.
560 super.onPrepareOptionsMenu(menu);
562 // `return true` displays the menu.
567 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
568 @SuppressLint("SetJavaScriptEnabled")
569 // removeAllCookies is deprecated, but it is required for API < 21.
570 @SuppressWarnings("deprecation")
571 public boolean onOptionsItemSelected(MenuItem menuItem) {
572 int menuItemId = menuItem.getItemId();
574 // Set the commands that relate to the menu entries.
575 switch (menuItemId) {
576 case R.id.toggleJavaScript:
577 // Switch the status of javaScriptEnabled.
578 javaScriptEnabled = !javaScriptEnabled;
580 // Apply the new JavaScript status.
581 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
583 // Update the privacy icon.
584 updatePrivacyIcons();
586 // Display a `Snackbar`.
587 if (javaScriptEnabled) { // JavaScrip is enabled.
588 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
589 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
590 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
591 } else { // Privacy mode.
592 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
595 // Reload the WebView.
596 mainWebView.reload();
599 case R.id.toggleFirstPartyCookies:
600 // Switch the status of firstPartyCookiesEnabled.
601 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
603 // Update the menu checkbox.
604 menuItem.setChecked(firstPartyCookiesEnabled);
606 // Apply the new cookie status.
607 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
609 // Update the privacy icon.
610 updatePrivacyIcons();
612 // Display a `Snackbar`.
613 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
614 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
615 } else if (javaScriptEnabled){ // JavaScript is still enabled.
616 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
617 } else { // Privacy mode.
618 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
621 // Reload the WebView.
622 mainWebView.reload();
625 case R.id.toggleThirdPartyCookies:
626 if (Build.VERSION.SDK_INT >= 21) {
627 // Switch the status of thirdPartyCookiesEnabled.
628 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
630 // Update the menu checkbox.
631 menuItem.setChecked(thirdPartyCookiesEnabled);
633 // Apply the new cookie status.
634 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
636 // Display a `Snackbar`.
637 if (thirdPartyCookiesEnabled) {
638 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
640 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
643 // Reload the WebView.
644 mainWebView.reload();
645 } // Else do nothing because SDK < 21.
648 case R.id.toggleDomStorage:
649 // Switch the status of domStorageEnabled.
650 domStorageEnabled = !domStorageEnabled;
652 // Update the menu checkbox.
653 menuItem.setChecked(domStorageEnabled);
655 // Apply the new DOM Storage status.
656 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
658 // Display a `Snackbar`.
659 if (domStorageEnabled) {
660 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
662 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
665 // Reload the WebView.
666 mainWebView.reload();
669 case R.id.toggleSaveFormData:
670 // Switch the status of saveFormDataEnabled.
671 saveFormDataEnabled = !saveFormDataEnabled;
673 // Update the menu checkbox.
674 menuItem.setChecked(saveFormDataEnabled);
676 // Apply the new form data status.
677 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
679 // Display a `Snackbar`.
680 if (saveFormDataEnabled) {
681 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
683 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
686 // Reload the WebView.
687 mainWebView.reload();
690 case R.id.clearCookies:
691 if (Build.VERSION.SDK_INT < 21) {
692 cookieManager.removeAllCookie();
694 cookieManager.removeAllCookies(null);
696 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
699 case R.id.clearDomStorage:
700 WebStorage webStorage = WebStorage.getInstance();
701 webStorage.deleteAllData();
702 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
705 case R.id.clearFormData:
706 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
707 mainWebViewDatabase.clearFormData();
708 mainWebView.reload();
711 case R.id.fontSizeFiftyPercent:
712 mainWebView.getSettings().setTextZoom(50);
715 case R.id.fontSizeSeventyFivePercent:
716 mainWebView.getSettings().setTextZoom(75);
719 case R.id.fontSizeOneHundredPercent:
720 mainWebView.getSettings().setTextZoom(100);
723 case R.id.fontSizeOneHundredTwentyFivePercent:
724 mainWebView.getSettings().setTextZoom(125);
727 case R.id.fontSizeOneHundredFiftyPercent:
728 mainWebView.getSettings().setTextZoom(150);
731 case R.id.fontSizeOneHundredSeventyFivePercent:
732 mainWebView.getSettings().setTextZoom(175);
735 case R.id.fontSizeTwoHundredPercent:
736 mainWebView.getSettings().setTextZoom(200);
739 case R.id.find_on_page:
740 appBar.setCustomView(R.layout.find_on_page_app_bar);
741 toggleJavaScript.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
742 appBar.invalidateOptionsMenu();
746 Intent shareIntent = new Intent();
747 shareIntent.setAction(Intent.ACTION_SEND);
748 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
749 shareIntent.setType("text/plain");
750 startActivity(Intent.createChooser(shareIntent, "Share URL"));
753 case R.id.addToHomescreen:
754 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
755 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
756 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
758 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
762 // Get a `PrintManager` instance.
763 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
765 // Convert `mainWebView` to `printDocumentAdapter`.
766 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
768 // Print the document. The print attributes are `null`.
769 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
773 mainWebView.reload();
777 // Don't consume the event.
778 return super.onOptionsItemSelected(menuItem);
782 // removeAllCookies is deprecated, but it is required for API < 21.
783 @SuppressWarnings("deprecation")
785 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
786 int menuItemId = menuItem.getItemId();
788 switch (menuItemId) {
790 mainWebView.loadUrl(homepage, customHeaders);
794 if (mainWebView.canGoBack()) {
795 mainWebView.goBack();
800 if (mainWebView.canGoForward()) {
801 mainWebView.goForward();
806 // Launch BookmarksActivity.
807 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
808 startActivity(bookmarksIntent);
812 // Launch the system Download Manager.
813 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
815 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
816 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
818 startActivity(downloadManagerIntent);
822 // Launch `SettingsActivity`.
823 Intent settingsIntent = new Intent(this, SettingsActivity.class);
824 startActivity(settingsIntent);
828 // Launch `GuideActivity`.
829 Intent guideIntent = new Intent(this, GuideActivity.class);
830 startActivity(guideIntent);
834 // Launch `AboutActivity`.
835 Intent aboutIntent = new Intent(this, AboutActivity.class);
836 startActivity(aboutIntent);
839 case R.id.clearAndExit:
840 // Clear cookies. The commands changed slightly in API 21.
841 if (Build.VERSION.SDK_INT >= 21) {
842 cookieManager.removeAllCookies(null);
844 cookieManager.removeAllCookie();
847 // Clear DOM storage.
848 WebStorage domStorage = WebStorage.getInstance();
849 domStorage.deleteAllData();
852 WebViewDatabase formData = WebViewDatabase.getInstance(this);
853 formData.clearFormData();
855 // Clear cache. The argument of "true" includes disk files.
856 mainWebView.clearCache(true);
858 // Clear the back/forward history.
859 mainWebView.clearHistory();
861 // Clear any SSL certificate preferences.
862 mainWebView.clearSslPreferences();
864 // Clear `formattedUrlString`.
865 formattedUrlString = null;
867 // Clear `customHeaders`.
868 customHeaders.clear();
870 // Destroy the internal state of the webview.
871 mainWebView.destroy();
873 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
874 if (Build.VERSION.SDK_INT >= 21) {
875 finishAndRemoveTask();
885 // Close the navigation drawer.
886 drawerLayout.closeDrawer(GravityCompat.START);
891 public void onPostCreate(Bundle savedInstanceState) {
892 super.onPostCreate(savedInstanceState);
894 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
895 drawerToggle.syncState();
899 public void onConfigurationChanged(Configuration newConfig) {
900 super.onConfigurationChanged(newConfig);
902 // Reload the ad if this is the free flavor.
903 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
905 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
906 adView = findViewById(R.id.adView);
908 // `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
909 // invalidateOptionsMenu();
913 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
914 // Get shortcutNameEditText from the alert dialog.
915 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
917 // Create the bookmark shortcut based on formattedUrlString.
918 Intent bookmarkShortcut = new Intent();
919 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
920 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
922 // Place the bookmark shortcut on the home screen.
923 Intent placeBookmarkShortcut = new Intent();
924 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
925 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
926 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
927 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
928 sendBroadcast(placeBookmarkShortcut);
932 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
933 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
934 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
936 // Get the file name from `dialogFragment`.
937 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
938 String fileName = downloadFileNameEditText.getText().toString();
940 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
941 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `fileName`.
942 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
943 } else { // Only set the title using `fileName`.
944 downloadRequest.setTitle(fileName);
947 // Allow `MediaScanner` to index the download if it is a media file.
948 downloadRequest.allowScanningByMediaScanner();
950 // Add the URL as the description for the download.
951 downloadRequest.setDescription(downloadUrl);
953 // Show the download notification after the download is completed.
954 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
956 // Initiate the download and display a Snackbar.
957 downloadManager.enqueue(downloadRequest);
960 public void viewSslCertificate(View view) {
961 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
962 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
963 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
967 public void onSslErrorCancel() {
968 sslErrorHandler.cancel();
972 public void onSslErrorProceed() {
973 sslErrorHandler.proceed();
976 // Override onBackPressed to handle the navigation drawer and mainWebView.
978 public void onBackPressed() {
979 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
981 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
982 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
983 drawerLayout.closeDrawer(GravityCompat.START);
985 // Load the previous URL if available.
986 if (mainWebView.canGoBack()) {
987 mainWebView.goBack();
989 // Pass onBackPressed to the system.
990 super.onBackPressed();
996 public void onPause() {
997 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
998 BannerAd.pauseAd(adView);
1004 public void onResume() {
1007 // We need to resume the adView for the free flavor.
1008 BannerAd.resumeAd(adView);
1012 public void onRestart() {
1015 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1018 // Update the privacy icons.
1019 updatePrivacyIcons();
1023 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1024 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1025 String unformattedUrlString = urlTextBox.getText().toString().trim();
1027 URL unformattedUrl = null;
1028 Uri.Builder formattedUri = new Uri.Builder();
1030 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1031 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1032 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1033 if (!unformattedUrlString.startsWith("http")) {
1034 unformattedUrlString = "http://" + unformattedUrlString;
1037 // 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.
1039 unformattedUrl = new URL(unformattedUrlString);
1040 } catch (MalformedURLException e) {
1041 e.printStackTrace();
1044 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1045 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1046 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1047 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1048 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1049 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1051 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1052 formattedUrlString = formattedUri.build().toString();
1054 // Sanitize the search input and convert it to a DuckDuckGo search.
1055 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1057 // Use the correct search URL.
1058 if (javaScriptEnabled) { // JavaScript is enabled.
1059 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1060 } else { // JavaScript is disabled.
1061 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1065 mainWebView.loadUrl(formattedUrlString, customHeaders);
1067 // Hides the keyboard so we can see the webpage.
1068 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1069 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1072 private void applySettings() {
1073 // Get the shared preference values. `this` references the current context.
1074 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1076 // Store the values from `sharedPreferences` in variables.
1077 String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
1078 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1079 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1080 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1081 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1082 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1083 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1084 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1085 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1086 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1087 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1089 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1090 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1091 // Get the values from `sharedPreferences`.
1092 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1093 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1094 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1095 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1096 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1098 // Apply the default settings.
1099 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1100 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1101 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1102 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1103 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1105 // Set third-party cookies status if API >= 21.
1106 if (Build.VERSION.SDK_INT >= 21) {
1107 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1111 // Apply the other settings from `sharedPreferences`.
1112 homepage = homepageString;
1113 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1115 // Set the user agent initial status.
1116 switch (userAgentString) {
1117 case "Default user agent":
1118 // Set the user agent to `""`, which uses the default value.
1119 mainWebView.getSettings().setUserAgentString("");
1122 case "Custom user agent":
1123 // Set the custom user agent.
1124 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1128 // Use the selected user agent.
1129 mainWebView.getSettings().setUserAgentString(userAgentString);
1133 // Set JavaScript disabled search.
1134 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1135 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1136 } else { // Use the string from the pre-built list.
1137 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1140 // Set JavaScript enabled search.
1141 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1142 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1143 } else { // Use the string from the pre-built list.
1144 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1147 // Set Do Not Track status.
1148 if (doNotTrackEnabled) {
1149 customHeaders.put("DNT", "1");
1151 customHeaders.remove("DNT");
1154 // Set Orbot proxy status.
1155 if (proxyThroughOrbot) {
1156 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1157 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1158 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1159 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1163 private void updatePrivacyIcons() {
1164 // Get handles for the icons.
1165 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1166 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1167 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1168 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1170 // Update `privacyIcon`.
1171 if (javaScriptEnabled) { // JavaScript is enabled.
1172 privacyIcon.setIcon(R.drawable.javascript_enabled);
1173 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1174 privacyIcon.setIcon(R.drawable.warning);
1175 } else { // All the dangerous features are disabled.
1176 privacyIcon.setIcon(R.drawable.privacy_mode);
1179 // Update `firstPartyCookiesIcon`.
1180 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1181 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1182 } else { // First-party cookies are disabled.
1183 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1186 // Update `domStorageIcon`.
1187 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1188 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1189 } else if (javaScriptEnabled){ // JavaScript is enabled but DOM storage is disabled.
1190 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1191 } else { // JavaScript is disabled, so DOM storage is ghosted.
1192 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1195 // Update `formDataIcon`.
1196 if (saveFormDataEnabled) { // Form data is enabled.
1197 formDataIcon.setIcon(R.drawable.form_data_enabled);
1198 } else { // Form data is disabled.
1199 formDataIcon.setIcon(R.drawable.form_data_disabled);
1202 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
1203 // `this` references the current activity.
1204 ActivityCompat.invalidateOptionsMenu(this);