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. `false` does not call `invalidateOptionsMenu` as the last step.
444 updatePrivacyIcons(false);
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. `true` runs `invalidateOptionsMenu` as the last step.
584 updatePrivacyIcons(true);
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. `true` runs `invalidateOptionsMenu` as the last step.
610 updatePrivacyIcons(true);
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 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
659 updatePrivacyIcons(true);
661 // Display a `Snackbar`.
662 if (domStorageEnabled) {
663 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
665 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
668 // Reload the WebView.
669 mainWebView.reload();
672 case R.id.toggleSaveFormData:
673 // Switch the status of saveFormDataEnabled.
674 saveFormDataEnabled = !saveFormDataEnabled;
676 // Update the menu checkbox.
677 menuItem.setChecked(saveFormDataEnabled);
679 // Apply the new form data status.
680 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
682 // Display a `Snackbar`.
683 if (saveFormDataEnabled) {
684 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
686 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
689 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
690 updatePrivacyIcons(true);
692 // Reload the WebView.
693 mainWebView.reload();
696 case R.id.clearCookies:
697 if (Build.VERSION.SDK_INT < 21) {
698 cookieManager.removeAllCookie();
700 cookieManager.removeAllCookies(null);
702 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
705 case R.id.clearDomStorage:
706 WebStorage webStorage = WebStorage.getInstance();
707 webStorage.deleteAllData();
708 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
711 case R.id.clearFormData:
712 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
713 mainWebViewDatabase.clearFormData();
714 mainWebView.reload();
717 case R.id.fontSizeFiftyPercent:
718 mainWebView.getSettings().setTextZoom(50);
721 case R.id.fontSizeSeventyFivePercent:
722 mainWebView.getSettings().setTextZoom(75);
725 case R.id.fontSizeOneHundredPercent:
726 mainWebView.getSettings().setTextZoom(100);
729 case R.id.fontSizeOneHundredTwentyFivePercent:
730 mainWebView.getSettings().setTextZoom(125);
733 case R.id.fontSizeOneHundredFiftyPercent:
734 mainWebView.getSettings().setTextZoom(150);
737 case R.id.fontSizeOneHundredSeventyFivePercent:
738 mainWebView.getSettings().setTextZoom(175);
741 case R.id.fontSizeTwoHundredPercent:
742 mainWebView.getSettings().setTextZoom(200);
746 case R.id.find_on_page:
747 appBar.setCustomView(R.layout.find_on_page_app_bar);
748 toggleJavaScript.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
749 appBar.invalidateOptionsMenu();
754 Intent shareIntent = new Intent();
755 shareIntent.setAction(Intent.ACTION_SEND);
756 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
757 shareIntent.setType("text/plain");
758 startActivity(Intent.createChooser(shareIntent, "Share URL"));
761 case R.id.addToHomescreen:
762 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
763 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
764 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
766 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
770 // Get a `PrintManager` instance.
771 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
773 // Convert `mainWebView` to `printDocumentAdapter`.
774 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
776 // Print the document. The print attributes are `null`.
777 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
781 mainWebView.reload();
785 // Don't consume the event.
786 return super.onOptionsItemSelected(menuItem);
790 // removeAllCookies is deprecated, but it is required for API < 21.
791 @SuppressWarnings("deprecation")
793 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
794 int menuItemId = menuItem.getItemId();
796 switch (menuItemId) {
798 mainWebView.loadUrl(homepage, customHeaders);
802 if (mainWebView.canGoBack()) {
803 mainWebView.goBack();
808 if (mainWebView.canGoForward()) {
809 mainWebView.goForward();
814 // Launch BookmarksActivity.
815 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
816 startActivity(bookmarksIntent);
820 // Launch the system Download Manager.
821 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
823 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
824 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
826 startActivity(downloadManagerIntent);
830 // Launch `SettingsActivity`.
831 Intent settingsIntent = new Intent(this, SettingsActivity.class);
832 startActivity(settingsIntent);
836 // Launch `GuideActivity`.
837 Intent guideIntent = new Intent(this, GuideActivity.class);
838 startActivity(guideIntent);
842 // Launch `AboutActivity`.
843 Intent aboutIntent = new Intent(this, AboutActivity.class);
844 startActivity(aboutIntent);
847 case R.id.clearAndExit:
848 // Clear cookies. The commands changed slightly in API 21.
849 if (Build.VERSION.SDK_INT >= 21) {
850 cookieManager.removeAllCookies(null);
852 cookieManager.removeAllCookie();
855 // Clear DOM storage.
856 WebStorage domStorage = WebStorage.getInstance();
857 domStorage.deleteAllData();
860 WebViewDatabase formData = WebViewDatabase.getInstance(this);
861 formData.clearFormData();
863 // Clear cache. The argument of "true" includes disk files.
864 mainWebView.clearCache(true);
866 // Clear the back/forward history.
867 mainWebView.clearHistory();
869 // Clear any SSL certificate preferences.
870 mainWebView.clearSslPreferences();
872 // Clear `formattedUrlString`.
873 formattedUrlString = null;
875 // Clear `customHeaders`.
876 customHeaders.clear();
878 // Destroy the internal state of the webview.
879 mainWebView.destroy();
881 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
882 if (Build.VERSION.SDK_INT >= 21) {
883 finishAndRemoveTask();
888 // Remove the terminated program from RAM. The status code is `0`.
896 // Close the navigation drawer.
897 drawerLayout.closeDrawer(GravityCompat.START);
902 public void onPostCreate(Bundle savedInstanceState) {
903 super.onPostCreate(savedInstanceState);
905 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
906 drawerToggle.syncState();
910 public void onConfigurationChanged(Configuration newConfig) {
911 super.onConfigurationChanged(newConfig);
913 // Reload the ad if this is the free flavor.
914 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
916 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
917 adView = findViewById(R.id.adView);
919 // `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
920 // ActivityCompat.invalidateOptionsMenu(this);
924 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
925 // Get shortcutNameEditText from the alert dialog.
926 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
928 // Create the bookmark shortcut based on formattedUrlString.
929 Intent bookmarkShortcut = new Intent();
930 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
931 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
933 // Place the bookmark shortcut on the home screen.
934 Intent placeBookmarkShortcut = new Intent();
935 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
936 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
937 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
938 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
939 sendBroadcast(placeBookmarkShortcut);
943 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
944 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
945 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
947 // Get the file name from `dialogFragment`.
948 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
949 String fileName = downloadFileNameEditText.getText().toString();
951 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
952 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `fileName`.
953 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
954 } else { // Only set the title using `fileName`.
955 downloadRequest.setTitle(fileName);
958 // Allow `MediaScanner` to index the download if it is a media file.
959 downloadRequest.allowScanningByMediaScanner();
961 // Add the URL as the description for the download.
962 downloadRequest.setDescription(downloadUrl);
964 // Show the download notification after the download is completed.
965 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
967 // Initiate the download and display a Snackbar.
968 downloadManager.enqueue(downloadRequest);
971 public void viewSslCertificate(View view) {
972 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
973 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
974 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
978 public void onSslErrorCancel() {
979 sslErrorHandler.cancel();
983 public void onSslErrorProceed() {
984 sslErrorHandler.proceed();
987 // Override onBackPressed to handle the navigation drawer and mainWebView.
989 public void onBackPressed() {
990 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
992 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
993 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
994 drawerLayout.closeDrawer(GravityCompat.START);
996 // Load the previous URL if available.
997 if (mainWebView.canGoBack()) {
998 mainWebView.goBack();
1000 // Pass onBackPressed to the system.
1001 super.onBackPressed();
1007 public void onPause() {
1008 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
1009 BannerAd.pauseAd(adView);
1015 public void onResume() {
1018 // We need to resume the adView for the free flavor.
1019 BannerAd.resumeAd(adView);
1023 public void onRestart() {
1026 // Apply the settings from shared preferences, which might have been changed in `SettingsActivity`.
1029 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1030 updatePrivacyIcons(true);
1034 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1035 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1036 String unformattedUrlString = urlTextBox.getText().toString().trim();
1038 URL unformattedUrl = null;
1039 Uri.Builder formattedUri = new Uri.Builder();
1041 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1042 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1043 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1044 if (!unformattedUrlString.startsWith("http")) {
1045 unformattedUrlString = "http://" + unformattedUrlString;
1048 // 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.
1050 unformattedUrl = new URL(unformattedUrlString);
1051 } catch (MalformedURLException e) {
1052 e.printStackTrace();
1055 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1056 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1057 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1058 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1059 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1060 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1062 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1063 formattedUrlString = formattedUri.build().toString();
1065 // Sanitize the search input and convert it to a DuckDuckGo search.
1066 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1068 // Use the correct search URL.
1069 if (javaScriptEnabled) { // JavaScript is enabled.
1070 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1071 } else { // JavaScript is disabled.
1072 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1076 mainWebView.loadUrl(formattedUrlString, customHeaders);
1078 // Hides the keyboard so we can see the webpage.
1079 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1080 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1083 private void applySettings() {
1084 // Get the shared preference values. `this` references the current context.
1085 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1087 // Store the values from `sharedPreferences` in variables.
1088 String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
1089 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1090 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1091 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1092 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1093 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1094 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1095 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1096 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1097 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1098 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1100 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1101 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1102 // Get the values from `sharedPreferences`.
1103 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1104 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1105 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1106 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1107 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1109 // Apply the default settings.
1110 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1111 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1112 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1113 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1114 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1116 // Set third-party cookies status if API >= 21.
1117 if (Build.VERSION.SDK_INT >= 21) {
1118 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1122 // Apply the other settings from `sharedPreferences`.
1123 homepage = homepageString;
1124 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1126 // Set the user agent initial status.
1127 switch (userAgentString) {
1128 case "Default user agent":
1129 // Set the user agent to `""`, which uses the default value.
1130 mainWebView.getSettings().setUserAgentString("");
1133 case "Custom user agent":
1134 // Set the custom user agent.
1135 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1139 // Use the selected user agent.
1140 mainWebView.getSettings().setUserAgentString(userAgentString);
1144 // Set JavaScript disabled search.
1145 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1146 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1147 } else { // Use the string from the pre-built list.
1148 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1151 // Set JavaScript enabled search.
1152 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1153 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1154 } else { // Use the string from the pre-built list.
1155 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1158 // Set Do Not Track status.
1159 if (doNotTrackEnabled) {
1160 customHeaders.put("DNT", "1");
1162 customHeaders.remove("DNT");
1165 // Set Orbot proxy status.
1166 if (proxyThroughOrbot) {
1167 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1168 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1169 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1170 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1174 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1175 // Get handles for the icons.
1176 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1177 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1178 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1179 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1181 // Update `privacyIcon`.
1182 if (javaScriptEnabled) { // JavaScript is enabled.
1183 privacyIcon.setIcon(R.drawable.javascript_enabled);
1184 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1185 privacyIcon.setIcon(R.drawable.warning);
1186 } else { // All the dangerous features are disabled.
1187 privacyIcon.setIcon(R.drawable.privacy_mode);
1190 // Update `firstPartyCookiesIcon`.
1191 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1192 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1193 } else { // First-party cookies are disabled.
1194 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1197 // Update `domStorageIcon`.
1198 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1199 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1200 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1201 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1202 } else { // JavaScript is disabled, so DOM storage is ghosted.
1203 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1206 // Update `formDataIcon`.
1207 if (saveFormDataEnabled) { // Form data is enabled.
1208 formDataIcon.setIcon(R.drawable.form_data_enabled);
1209 } else { // Form data is disabled.
1210 formDataIcon.setIcon(R.drawable.form_data_disabled);
1213 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1214 if (runInvalidateOptionsMenu) {
1215 ActivityCompat.invalidateOptionsMenu(this);