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.widget.Toolbar;
53 import android.util.Patterns;
54 import android.view.KeyEvent;
55 import android.view.Menu;
56 import android.view.MenuItem;
57 import android.view.View;
58 import android.view.inputmethod.InputMethodManager;
59 import android.webkit.CookieManager;
60 import android.webkit.DownloadListener;
61 import android.webkit.SslErrorHandler;
62 import android.webkit.WebChromeClient;
63 import android.webkit.WebStorage;
64 import android.webkit.WebView;
65 import android.webkit.WebViewClient;
66 import android.webkit.WebViewDatabase;
67 import android.widget.EditText;
68 import android.widget.FrameLayout;
69 import android.widget.ImageView;
70 import android.widget.ProgressBar;
72 import java.io.UnsupportedEncodingException;
73 import java.net.MalformedURLException;
75 import java.net.URLEncoder;
76 import java.util.HashMap;
79 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
80 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
81 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener {
83 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
84 // It is also used in `onCreate()` and `onOptionsItemSelected()`.
85 public static ActionBar appBar;
87 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
88 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
89 public static Bitmap favoriteIcon;
91 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
92 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
93 public static String formattedUrlString;
95 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
96 public static SslCertificate sslCertificate;
99 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `loadUrlFromTextBox()`.
100 private WebView mainWebView;
102 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
103 private SwipeRefreshLayout swipeRefreshLayout;
105 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
106 private CookieManager cookieManager;
108 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
109 private final Map<String, String> customHeaders = new HashMap<>();
111 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
112 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
113 private Boolean javaScriptEnabled;
115 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
116 private boolean firstPartyCookiesEnabled;
118 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
119 private boolean thirdPartyCookiesEnabled;
121 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
122 private boolean domStorageEnabled;
124 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
125 private boolean saveFormDataEnabled;
127 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
128 private boolean swipeToRefreshEnabled;
130 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
131 private String homepage;
133 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
134 private String javaScriptDisabledSearchURL;
136 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
137 private String javaScriptEnabledSearchURL;
139 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
140 private Menu mainMenu;
142 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
143 private ActionBarDrawerToggle drawerToggle;
145 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
146 private DrawerLayout drawerLayout;
148 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
149 private EditText urlTextBox;
151 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
154 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
155 private SslErrorHandler sslErrorHandler;
157 private MenuItem toggleJavaScript;
160 // 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.
161 @SuppressLint("SetJavaScriptEnabled")
162 protected void onCreate(Bundle savedInstanceState) {
163 super.onCreate(savedInstanceState);
164 setContentView(R.layout.main_coordinatorlayout);
166 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
167 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
168 setSupportActionBar(supportAppBar);
169 appBar = getSupportActionBar();
171 // This is needed to get rid of the Android Studio warning that appBar might be null.
172 assert appBar != null;
174 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
175 appBar.setCustomView(R.layout.url_app_bar);
176 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
178 // Set the "go" button on the keyboard to load the URL in urlTextBox.
179 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
180 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
181 public boolean onKey(View v, int keyCode, KeyEvent event) {
182 // If the event is a key-down event on the "enter" button, load the URL.
183 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
184 // Load the URL into the mainWebView and consume the event.
186 loadUrlFromTextBox();
187 } catch (UnsupportedEncodingException e) {
190 // If the enter key was pressed, consume the event.
193 // If any other key was pressed, do not consume the event.
199 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
201 // Implement swipe to refresh
202 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
203 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
204 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
206 public void onRefresh() {
207 mainWebView.reload();
211 mainWebView = (WebView) findViewById(R.id.mainWebView);
213 // Create the navigation drawer.
214 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
215 // The DrawerTitle identifies the drawer in accessibility mode.
216 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
218 // Listen for touches on the navigation menu.
219 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
220 navigationView.setNavigationItemSelectedListener(this);
222 // drawerToggle creates the hamburger icon at the start of the AppBar.
223 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
225 mainWebView.setWebViewClient(new WebViewClient() {
226 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
227 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
228 @SuppressWarnings("deprecation")
230 public boolean shouldOverrideUrlLoading(WebView view, String url) {
231 // Use an external email program if the link begins with "mailto:".
232 if (url.startsWith("mailto:")) {
233 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
234 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
236 // Parse the url and set it as the data for the `Intent`.
237 emailIntent.setData(Uri.parse(url));
239 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
240 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
243 startActivity(emailIntent);
245 } else { // Load the URL in Privacy Browser.
246 mainWebView.loadUrl(url, customHeaders);
251 // Update the URL in urlTextBox when the page starts to load.
253 public void onPageStarted(WebView view, String url, Bitmap favicon) {
254 // 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.
255 formattedUrlString = url;
257 // Display the loading URL is the URL text box.
258 urlTextBox.setText(url);
261 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
263 public void onPageFinished(WebView view, String url) {
264 formattedUrlString = url;
266 // Only update urlTextBox if the user is not typing in it.
267 if (!urlTextBox.hasFocus()) {
268 urlTextBox.setText(formattedUrlString);
271 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
272 sslCertificate = mainWebView.getCertificate();
275 // Handle SSL Certificate errors.
277 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
278 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
279 sslErrorHandler = handler;
281 // Display the SSL error `AlertDialog`.
282 DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
283 sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
287 mainWebView.setWebChromeClient(new WebChromeClient() {
288 // Update the progress bar when a page is loading.
290 public void onProgressChanged(WebView view, int progress) {
291 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
292 progressBar.setProgress(progress);
293 if (progress < 100) {
294 progressBar.setVisibility(View.VISIBLE);
296 progressBar.setVisibility(View.GONE);
298 //Stop the `SwipeToRefresh` indicator if it is running
299 swipeRefreshLayout.setRefreshing(false);
303 // Set the favorite icon when it changes.
305 public void onReceivedIcon(WebView view, Bitmap icon) {
306 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
309 // Place the favorite icon in the appBar.
310 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
311 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
314 // Enter full screen video
316 public void onShowCustomView(View view, CustomViewCallback callback) {
319 // Show the fullScreenVideoFrameLayout.
320 fullScreenVideoFrameLayout.addView(view);
321 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
323 // Hide the mainWebView.
324 mainWebView.setVisibility(View.GONE);
326 // Hide the ad if this is the free flavor.
327 BannerAd.hideAd(adView);
329 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
330 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
331 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
333 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
336 // Exit full screen video
337 public void onHideCustomView() {
340 // Show the mainWebView.
341 mainWebView.setVisibility(View.VISIBLE);
343 // Show the ad if this is the free flavor.
344 BannerAd.showAd(adView);
346 // Hide the fullScreenVideoFrameLayout.
347 fullScreenVideoFrameLayout.removeAllViews();
348 fullScreenVideoFrameLayout.setVisibility(View.GONE);
352 // Allow the downloading of files.
353 mainWebView.setDownloadListener(new DownloadListener() {
355 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
356 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
357 DialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
358 downloadFileDialogFragment.show(getFragmentManager(), getResources().getString(R.string.download));
362 // Allow pinch to zoom.
363 mainWebView.getSettings().setBuiltInZoomControls(true);
365 // Hide zoom controls.
366 mainWebView.getSettings().setDisplayZoomControls(false);
368 // Initialize cookieManager.
369 cookieManager = CookieManager.getInstance();
371 // 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).
372 customHeaders.put("X-Requested-With", "");
374 // Initialize the default preference values the first time the program is run.
375 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
377 // Apply the settings from the shared preferences.
380 // Get the intent information that started the app.
381 final Intent intent = getIntent();
383 if (intent.getData() != null) {
384 // Get the intent data and convert it to a string.
385 final Uri intentUriData = intent.getData();
386 formattedUrlString = intentUriData.toString();
389 // If formattedUrlString is null assign the homepage to it.
390 if (formattedUrlString == null) {
391 formattedUrlString = homepage;
394 // Load the initial website.
395 mainWebView.loadUrl(formattedUrlString, customHeaders);
397 // If the favorite icon is null, load the default.
398 if (favoriteIcon == null) {
399 // We have to use `ContextCompat` until API >= 21.
400 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
401 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
402 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
405 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
406 adView = findViewById(R.id.adView);
407 BannerAd.requestAd(adView);
412 protected void onNewIntent(Intent intent) {
413 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
416 if (intent.getData() != null) {
417 // Get the intent data and convert it to a string.
418 final Uri intentUriData = intent.getData();
419 formattedUrlString = intentUriData.toString();
422 // Close the navigation drawer if it is open.
423 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
424 drawerLayout.closeDrawer(GravityCompat.START);
428 mainWebView.loadUrl(formattedUrlString, customHeaders);
430 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
431 mainWebView.requestFocus();
435 public boolean onCreateOptionsMenu(Menu menu) {
436 // Inflate the menu; this adds items to the action bar if it is present.
437 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
439 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
442 // Set the initial status of the privacy icons.
443 updatePrivacyIcons();
445 // Get handles for the menu items.
446 toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
447 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
448 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
449 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
450 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
452 // Only display third-Party Cookies if SDK >= 21
453 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
455 // Get the shared preference values. `this` references the current context.
456 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
458 // Set the status of the additional app bar icons. The default is `false`.
459 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
460 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
461 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
462 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
463 } else { //Do not display the additional icons.
464 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
465 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
466 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
473 public boolean onPrepareOptionsMenu(Menu menu) {
474 // Get handles for the menu items.
475 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
476 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
477 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
478 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
479 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
480 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
481 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
483 // Set the status of the menu item checkboxes.
484 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
485 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
486 toggleDomStorage.setChecked(domStorageEnabled);
487 toggleSaveFormData.setChecked(saveFormDataEnabled);
489 // Enable third-party cookies if first-party cookies are enabled.
490 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
492 // Enable DOM Storage if JavaScript is enabled.
493 toggleDomStorage.setEnabled(javaScriptEnabled);
495 // Enable Clear Cookies if there are any.
496 clearCookies.setEnabled(cookieManager.hasCookies());
498 // Enable Clear Form Data is there is any.
499 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
500 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
502 // Only show `Refresh` if `swipeToRefresh` is disabled.
503 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
505 // Initialize font size variables.
506 int fontSize = mainWebView.getSettings().getTextZoom();
507 String fontSizeTitle;
508 MenuItem selectedFontSizeMenuItem;
510 // Prepare the font size title and current size menu item.
513 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
514 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
518 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
519 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
523 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
524 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
528 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
529 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
533 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
534 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
538 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
539 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
543 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
544 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
548 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
549 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
553 // Set the font size title and select the current size menu item.
554 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
555 fontSizeMenuItem.setTitle(fontSizeTitle);
556 selectedFontSizeMenuItem.setChecked(true);
558 // Run all the other default commands.
559 super.onPrepareOptionsMenu(menu);
561 // `return true` displays the menu.
566 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
567 @SuppressLint("SetJavaScriptEnabled")
568 // removeAllCookies is deprecated, but it is required for API < 21.
569 @SuppressWarnings("deprecation")
570 public boolean onOptionsItemSelected(MenuItem menuItem) {
571 int menuItemId = menuItem.getItemId();
573 // Set the commands that relate to the menu entries.
574 switch (menuItemId) {
575 case R.id.toggleJavaScript:
576 // Switch the status of javaScriptEnabled.
577 javaScriptEnabled = !javaScriptEnabled;
579 // Apply the new JavaScript status.
580 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
582 // Update the privacy icon.
583 updatePrivacyIcons();
585 // Display a `Snackbar`.
586 if (javaScriptEnabled) { // JavaScrip is enabled.
587 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
588 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
589 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
590 } else { // Privacy mode.
591 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
594 // Reload the WebView.
595 mainWebView.reload();
598 case R.id.toggleFirstPartyCookies:
599 // Switch the status of firstPartyCookiesEnabled.
600 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
602 // Update the menu checkbox.
603 menuItem.setChecked(firstPartyCookiesEnabled);
605 // Apply the new cookie status.
606 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
608 // Update the privacy icon.
609 updatePrivacyIcons();
611 // Display a `Snackbar`.
612 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
613 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
614 } else if (javaScriptEnabled){ // JavaScript is still enabled.
615 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
616 } else { // Privacy mode.
617 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
620 // Reload the WebView.
621 mainWebView.reload();
624 case R.id.toggleThirdPartyCookies:
625 if (Build.VERSION.SDK_INT >= 21) {
626 // Switch the status of thirdPartyCookiesEnabled.
627 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
629 // Update the menu checkbox.
630 menuItem.setChecked(thirdPartyCookiesEnabled);
632 // Apply the new cookie status.
633 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
635 // Display a `Snackbar`.
636 if (thirdPartyCookiesEnabled) {
637 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
639 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
642 // Reload the WebView.
643 mainWebView.reload();
644 } // Else do nothing because SDK < 21.
647 case R.id.toggleDomStorage:
648 // Switch the status of domStorageEnabled.
649 domStorageEnabled = !domStorageEnabled;
651 // Update the menu checkbox.
652 menuItem.setChecked(domStorageEnabled);
654 // Apply the new DOM Storage status.
655 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
657 // Display a `Snackbar`.
658 if (domStorageEnabled) {
659 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
661 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
664 // Reload the WebView.
665 mainWebView.reload();
668 case R.id.toggleSaveFormData:
669 // Switch the status of saveFormDataEnabled.
670 saveFormDataEnabled = !saveFormDataEnabled;
672 // Update the menu checkbox.
673 menuItem.setChecked(saveFormDataEnabled);
675 // Apply the new form data status.
676 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
678 // Display a `Snackbar`.
679 if (saveFormDataEnabled) {
680 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
682 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
685 // Reload the WebView.
686 mainWebView.reload();
689 case R.id.clearCookies:
690 if (Build.VERSION.SDK_INT < 21) {
691 cookieManager.removeAllCookie();
693 cookieManager.removeAllCookies(null);
695 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
698 case R.id.clearDomStorage:
699 WebStorage webStorage = WebStorage.getInstance();
700 webStorage.deleteAllData();
701 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
704 case R.id.clearFormData:
705 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
706 mainWebViewDatabase.clearFormData();
707 mainWebView.reload();
710 case R.id.fontSizeFiftyPercent:
711 mainWebView.getSettings().setTextZoom(50);
714 case R.id.fontSizeSeventyFivePercent:
715 mainWebView.getSettings().setTextZoom(75);
718 case R.id.fontSizeOneHundredPercent:
719 mainWebView.getSettings().setTextZoom(100);
722 case R.id.fontSizeOneHundredTwentyFivePercent:
723 mainWebView.getSettings().setTextZoom(125);
726 case R.id.fontSizeOneHundredFiftyPercent:
727 mainWebView.getSettings().setTextZoom(150);
730 case R.id.fontSizeOneHundredSeventyFivePercent:
731 mainWebView.getSettings().setTextZoom(175);
734 case R.id.fontSizeTwoHundredPercent:
735 mainWebView.getSettings().setTextZoom(200);
738 case R.id.find_on_page:
739 appBar.setCustomView(R.layout.find_on_page_app_bar);
740 toggleJavaScript.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
741 appBar.invalidateOptionsMenu();
745 Intent shareIntent = new Intent();
746 shareIntent.setAction(Intent.ACTION_SEND);
747 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
748 shareIntent.setType("text/plain");
749 startActivity(Intent.createChooser(shareIntent, "Share URL"));
752 case R.id.addToHomescreen:
753 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
754 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
755 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
757 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
761 // Get a `PrintManager` instance.
762 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
764 // Convert `mainWebView` to `printDocumentAdapter`.
765 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
767 // Print the document. The print attributes are `null`.
768 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
772 mainWebView.reload();
776 // Don't consume the event.
777 return super.onOptionsItemSelected(menuItem);
781 // removeAllCookies is deprecated, but it is required for API < 21.
782 @SuppressWarnings("deprecation")
784 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
785 int menuItemId = menuItem.getItemId();
787 switch (menuItemId) {
789 mainWebView.loadUrl(homepage, customHeaders);
793 if (mainWebView.canGoBack()) {
794 mainWebView.goBack();
799 if (mainWebView.canGoForward()) {
800 mainWebView.goForward();
805 // Launch BookmarksActivity.
806 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
807 startActivity(bookmarksIntent);
811 // Launch the system Download Manager.
812 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
814 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
815 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
817 startActivity(downloadManagerIntent);
821 // Launch `SettingsActivity`.
822 Intent settingsIntent = new Intent(this, SettingsActivity.class);
823 startActivity(settingsIntent);
827 // Launch `GuideActivity`.
828 Intent guideIntent = new Intent(this, GuideActivity.class);
829 startActivity(guideIntent);
833 // Launch `AboutActivity`.
834 Intent aboutIntent = new Intent(this, AboutActivity.class);
835 startActivity(aboutIntent);
838 case R.id.clearAndExit:
839 // Clear cookies. The commands changed slightly in API 21.
840 if (Build.VERSION.SDK_INT >= 21) {
841 cookieManager.removeAllCookies(null);
843 cookieManager.removeAllCookie();
846 // Clear DOM storage.
847 WebStorage domStorage = WebStorage.getInstance();
848 domStorage.deleteAllData();
851 WebViewDatabase formData = WebViewDatabase.getInstance(this);
852 formData.clearFormData();
854 // Clear cache. The argument of "true" includes disk files.
855 mainWebView.clearCache(true);
857 // Clear the back/forward history.
858 mainWebView.clearHistory();
860 // Clear any SSL certificate preferences.
861 mainWebView.clearSslPreferences();
863 // Clear `formattedUrlString`.
864 formattedUrlString = null;
866 // Clear `customHeaders`.
867 customHeaders.clear();
869 // Destroy the internal state of the webview.
870 mainWebView.destroy();
872 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
873 if (Build.VERSION.SDK_INT >= 21) {
874 finishAndRemoveTask();
884 // Close the navigation drawer.
885 drawerLayout.closeDrawer(GravityCompat.START);
890 public void onPostCreate(Bundle savedInstanceState) {
891 super.onPostCreate(savedInstanceState);
893 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
894 drawerToggle.syncState();
898 public void onConfigurationChanged(Configuration newConfig) {
899 super.onConfigurationChanged(newConfig);
901 // Reload the ad if this is the free flavor.
902 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
904 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
905 adView = findViewById(R.id.adView);
907 // `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
908 // invalidateOptionsMenu();
912 public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
913 // Get shortcutNameEditText from the alert dialog.
914 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
916 // Create the bookmark shortcut based on formattedUrlString.
917 Intent bookmarkShortcut = new Intent();
918 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
919 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
921 // Place the bookmark shortcut on the home screen.
922 Intent placeBookmarkShortcut = new Intent();
923 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
924 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
925 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
926 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
927 sendBroadcast(placeBookmarkShortcut);
931 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
932 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
933 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
935 // Get the file name from `dialogFragment`.
936 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
937 String fileName = downloadFileNameEditText.getText().toString();
939 // Set the download save in the the `DIRECTORY_DOWNLOADS`using `fileName`.
940 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
941 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
943 // Allow `MediaScanner` to index the download if it is a media file.
944 downloadRequest.allowScanningByMediaScanner();
946 // Add the URL as the description for the download.
947 downloadRequest.setDescription(downloadUrl);
949 // Show the download notification after the download is completed.
950 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
952 // Initiate the download and display a Snackbar.
953 downloadManager.enqueue(downloadRequest);
956 public void viewSslCertificate(View view) {
957 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
958 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
959 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
963 public void onSslErrorCancel() {
964 sslErrorHandler.cancel();
968 public void onSslErrorProceed() {
969 sslErrorHandler.proceed();
972 // Override onBackPressed to handle the navigation drawer and mainWebView.
974 public void onBackPressed() {
975 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
977 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
978 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
979 drawerLayout.closeDrawer(GravityCompat.START);
981 // Load the previous URL if available.
982 if (mainWebView.canGoBack()) {
983 mainWebView.goBack();
985 // Pass onBackPressed to the system.
986 super.onBackPressed();
992 public void onPause() {
993 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
994 BannerAd.pauseAd(adView);
1000 public void onResume() {
1003 // We need to resume the adView for the free flavor.
1004 BannerAd.resumeAd(adView);
1008 public void onRestart() {
1011 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1014 // Update the privacy icons.
1015 updatePrivacyIcons();
1019 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1020 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1021 String unformattedUrlString = urlTextBox.getText().toString().trim();
1023 URL unformattedUrl = null;
1024 Uri.Builder formattedUri = new Uri.Builder();
1026 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1027 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1028 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1029 if (!unformattedUrlString.startsWith("http")) {
1030 unformattedUrlString = "http://" + unformattedUrlString;
1033 // 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.
1035 unformattedUrl = new URL(unformattedUrlString);
1036 } catch (MalformedURLException e) {
1037 e.printStackTrace();
1040 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1041 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1042 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1043 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1044 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1045 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1047 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1048 formattedUrlString = formattedUri.build().toString();
1050 // Sanitize the search input and convert it to a DuckDuckGo search.
1051 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1053 // Use the correct search URL.
1054 if (javaScriptEnabled) { // JavaScript is enabled.
1055 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1056 } else { // JavaScript is disabled.
1057 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1061 mainWebView.loadUrl(formattedUrlString, customHeaders);
1063 // Hides the keyboard so we can see the webpage.
1064 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1065 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1068 private void applySettings() {
1069 // Get the shared preference values. `this` references the current context.
1070 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1072 // Store the values from `sharedPreferences` in variables.
1073 String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
1074 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1075 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1076 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1077 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1078 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1079 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1080 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1081 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1082 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1083 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1085 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1086 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1087 // Get the values from `sharedPreferences`.
1088 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1089 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1090 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1091 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1092 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1094 // Apply the default settings.
1095 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1096 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1097 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1098 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1099 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1101 // Set third-party cookies status if API >= 21.
1102 if (Build.VERSION.SDK_INT >= 21) {
1103 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1107 // Apply the other settings from `sharedPreferences`.
1108 homepage = homepageString;
1109 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1111 // Set the user agent initial status.
1112 switch (userAgentString) {
1113 case "Default user agent":
1114 // Set the user agent to `""`, which uses the default value.
1115 mainWebView.getSettings().setUserAgentString("");
1118 case "Custom user agent":
1119 // Set the custom user agent.
1120 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1124 // Use the selected user agent.
1125 mainWebView.getSettings().setUserAgentString(userAgentString);
1129 // Set JavaScript disabled search.
1130 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1131 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1132 } else { // Use the string from the pre-built list.
1133 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1136 // Set JavaScript enabled search.
1137 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1138 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1139 } else { // Use the string from the pre-built list.
1140 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1143 // Set Do Not Track status.
1144 if (doNotTrackEnabled) {
1145 customHeaders.put("DNT", "1");
1147 customHeaders.remove("DNT");
1150 // Set Orbot proxy status.
1151 if (proxyThroughOrbot) {
1152 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1153 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1154 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1155 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1159 private void updatePrivacyIcons() {
1160 // Get handles for the icons.
1161 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1162 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1163 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1164 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1166 // Update `privacyIcon`.
1167 if (javaScriptEnabled) { // JavaScript is enabled.
1168 privacyIcon.setIcon(R.drawable.javascript_enabled);
1169 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1170 privacyIcon.setIcon(R.drawable.warning);
1171 } else { // All the dangerous features are disabled.
1172 privacyIcon.setIcon(R.drawable.privacy_mode);
1175 // Update `firstPartyCookiesIcon`.
1176 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1177 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1178 } else { // First-party cookies are disabled.
1179 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1182 // Update `domStorageIcon`.
1183 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1184 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1185 } else if (javaScriptEnabled){ // JavaScript is enabled but DOM storage is disabled.
1186 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1187 } else { // JavaScript is disabled, so DOM storage is ghosted.
1188 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1191 // Update `formDataIcon`.
1192 if (saveFormDataEnabled) { // Form data is enabled.
1193 formDataIcon.setIcon(R.drawable.form_data_enabled);
1194 } else { // Form data is disabled.
1195 formDataIcon.setIcon(R.drawable.form_data_disabled);
1198 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
1199 // `this` references the current activity.
1200 ActivityCompat.invalidateOptionsMenu(this);