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.activities;
22 import android.annotation.SuppressLint;
23 import android.app.DialogFragment;
24 import android.app.DownloadManager;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.net.Uri;
33 import android.net.http.SslCertificate;
34 import android.net.http.SslError;
35 import android.os.Build;
36 import android.os.Bundle;
37 import android.preference.PreferenceManager;
38 import android.print.PrintDocumentAdapter;
39 import android.print.PrintManager;
40 import android.support.annotation.NonNull;
41 import android.support.design.widget.CoordinatorLayout;
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.text.Editable;
55 import android.text.TextWatcher;
56 import android.util.Patterns;
57 import android.view.ContextMenu;
58 import android.view.GestureDetector;
59 import android.view.KeyEvent;
60 import android.view.Menu;
61 import android.view.MenuItem;
62 import android.view.MotionEvent;
63 import android.view.View;
64 import android.view.WindowManager;
65 import android.view.inputmethod.InputMethodManager;
66 import android.webkit.CookieManager;
67 import android.webkit.DownloadListener;
68 import android.webkit.SslErrorHandler;
69 import android.webkit.WebBackForwardList;
70 import android.webkit.WebChromeClient;
71 import android.webkit.WebStorage;
72 import android.webkit.WebView;
73 import android.webkit.WebViewClient;
74 import android.webkit.WebViewDatabase;
75 import android.widget.EditText;
76 import android.widget.FrameLayout;
77 import android.widget.ImageView;
78 import android.widget.LinearLayout;
79 import android.widget.ProgressBar;
80 import android.widget.RelativeLayout;
81 import android.widget.TextView;
83 import com.stoutner.privacybrowser.BannerAd;
84 import com.stoutner.privacybrowser.BuildConfig;
85 import com.stoutner.privacybrowser.R;
86 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
87 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
88 import com.stoutner.privacybrowser.dialogs.DownloadFile;
89 import com.stoutner.privacybrowser.dialogs.DownloadImage;
90 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
91 import com.stoutner.privacybrowser.dialogs.UrlHistory;
92 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
94 import java.io.UnsupportedEncodingException;
95 import java.net.MalformedURLException;
97 import java.net.URLEncoder;
98 import java.util.HashMap;
101 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
102 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
103 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
105 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
106 // It is also used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
107 public static ActionBar appBar;
109 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
110 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
111 public static Bitmap favoriteIcon;
113 // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
114 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
115 public static String formattedUrlString;
117 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
118 public static SslCertificate sslCertificate;
122 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
123 private DrawerLayout drawerLayout;
125 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
126 private CoordinatorLayout rootCoordinatorLayout;
128 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
129 private WebView mainWebView;
131 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
132 private EditText findOnPageEditText;
134 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
135 private FrameLayout fullScreenVideoFrameLayout;
137 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
138 private SwipeRefreshLayout swipeRefreshLayout;
140 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
141 private CookieManager cookieManager;
143 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
144 private final Map<String, String> customHeaders = new HashMap<>();
146 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
147 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
148 private Boolean javaScriptEnabled;
150 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
151 private boolean firstPartyCookiesEnabled;
153 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
154 private boolean thirdPartyCookiesEnabled;
156 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
157 private boolean domStorageEnabled;
159 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
160 private boolean saveFormDataEnabled;
162 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
163 private boolean swipeToRefreshEnabled;
165 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
166 private String homepage;
168 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
169 private String javaScriptDisabledSearchURL;
171 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
172 private String javaScriptEnabledSearchURL;
174 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
175 private boolean hideSystemBarsOnFullscreen;
177 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
178 private boolean translucentNavigationBarOnFullscreen;
180 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
181 private Menu mainMenu;
183 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
184 private ActionBarDrawerToggle drawerToggle;
186 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
187 private EditText urlTextBox;
189 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
192 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
193 private SslErrorHandler sslErrorHandler;
195 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
196 private InputMethodManager inputMethodManager;
199 // 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.
200 @SuppressLint("SetJavaScriptEnabled")
201 protected void onCreate(Bundle savedInstanceState) {
202 super.onCreate(savedInstanceState);
203 setContentView(R.layout.drawerlayout);
205 // Get a handle for `inputMethodManager`.
206 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
208 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
209 Toolbar supportAppBar = (Toolbar) findViewById(R.id.app_bar);
210 setSupportActionBar(supportAppBar);
211 appBar = getSupportActionBar();
213 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
214 assert appBar != null;
216 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
217 appBar.setCustomView(R.layout.url_app_bar);
218 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
220 // Set the "go" button on the keyboard to load the URL in urlTextBox.
221 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
222 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
224 public boolean onKey(View v, int keyCode, KeyEvent event) {
225 // If the event is a key-down event on the `enter` button, load the URL.
226 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
227 // Load the URL into the mainWebView and consume the event.
229 loadUrlFromTextBox();
230 } catch (UnsupportedEncodingException e) {
233 // If the enter key was pressed, consume the event.
236 // If any other key was pressed, do not consume the event.
242 // Get handles for views that need to be accessed.
243 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
244 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
245 mainWebView = (WebView) findViewById(R.id.mainWebView);
246 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
247 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
249 // Create a double-tap listener to toggle full-screen mode.
250 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
251 // Override `onDoubleTap()`. All other events are handled using the default settings.
253 public boolean onDoubleTap(MotionEvent event) {
254 if (appBar.isShowing()) { // If `appBar` is visible, switch to full screen mode.
255 // Hide the `appBar`.
258 // Hide the `BannerAd` in the free flavor.
259 if (BuildConfig.FLAVOR.contentEquals("free")) {
260 BannerAd.hideAd(adView);
263 // Modify the system bars.
264 if (hideSystemBarsOnFullscreen) { // Hide everything.
265 // Remove the translucent overlays.
266 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
268 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
269 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
271 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
272 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
273 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
275 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
277 // Set `rootCoordinatorLayout` to fill the whole screen.
278 rootCoordinatorLayout.setFitsSystemWindows(false);
279 } else { // Hide everything except the status and navigation bars.
280 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
281 rootCoordinatorLayout.setFitsSystemWindows(false);
283 if (translucentNavigationBarOnFullscreen) { // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
284 // Set the navigation bar to be translucent.
285 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
288 } else { // Switch to normal viewing mode.
289 // Show the `appBar`.
292 // Show the `BannerAd` in the free flavor.
293 if (BuildConfig.FLAVOR.contentEquals("free")) {
294 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
295 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
297 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
298 adView = findViewById(R.id.adView);
301 // Remove the translucent navigation bar flag if it is set.
302 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
304 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
305 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
307 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
308 rootCoordinatorLayout.setSystemUiVisibility(0);
310 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
311 rootCoordinatorLayout.setFitsSystemWindows(true);
314 // Consume the double-tap.
319 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
320 mainWebView.setOnTouchListener(new View.OnTouchListener() {
322 public boolean onTouch(View v, MotionEvent event) {
323 // Send the `event` to `gestureDetector`.
324 return gestureDetector.onTouchEvent(event);
328 // Update `findOnPageCountTextView`.
329 mainWebView.setFindListener(new WebView.FindListener() {
330 // Get a handle for `findOnPageCountTextView`.
331 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
334 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
335 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
336 // Set `findOnPageCountTextView` to `0/0`.
337 findOnPageCountTextView.setText(R.string.zero_of_zero);
338 } else if (isDoneCounting) { // There are matches.
339 // `activeMatchOrdinal` is zero-based.
340 int activeMatch = activeMatchOrdinal + 1;
342 // Set `findOnPageCountTextView`.
343 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
348 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
349 findOnPageEditText.addTextChangedListener(new TextWatcher() {
351 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
356 public void onTextChanged(CharSequence s, int start, int before, int count) {
361 public void afterTextChanged(Editable s) {
362 // Search for the text in `mainWebView`.
363 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
367 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
368 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
370 public boolean onKey(View v, int keyCode, KeyEvent event) {
371 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
372 // Hide the soft keyboard. `0` indicates no additional flags.
373 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
375 // Consume the event.
377 } else { // A different key was pressed.
378 // Do not consume the event.
384 // Implement swipe to refresh
385 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
386 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
387 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
389 public void onRefresh() {
390 mainWebView.reload();
394 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
395 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
397 // Listen for touches on the navigation menu.
398 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
399 navigationView.setNavigationItemSelectedListener(this);
401 // Get handles for `navigationMenu` and the back and forward menu items. The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
402 final Menu navigationMenu = navigationView.getMenu();
403 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
404 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
405 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
407 // The `DrawerListener` allows us to update the Navigation Menu.
408 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
410 public void onDrawerSlide(View drawerView, float slideOffset) {
414 public void onDrawerOpened(View drawerView) {
418 public void onDrawerClosed(View drawerView) {
422 public void onDrawerStateChanged(int newState) {
423 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
424 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
425 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
426 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
428 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
429 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
433 // drawerToggle creates the hamburger icon at the start of the AppBar.
434 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
436 mainWebView.setWebViewClient(new WebViewClient() {
437 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
438 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
439 @SuppressWarnings("deprecation")
441 public boolean shouldOverrideUrlLoading(WebView view, String url) {
442 // Use an external email program if the link begins with `mailto:`.
443 if (url.startsWith("mailto:")) {
444 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
445 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
447 // Parse the url and set it as the data for the `Intent`.
448 emailIntent.setData(Uri.parse(url));
450 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
451 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
454 startActivity(emailIntent);
456 } else { // Load the URL in Privacy Browser.
457 mainWebView.loadUrl(url, customHeaders);
462 // Update the URL in urlTextBox when the page starts to load.
464 public void onPageStarted(WebView view, String url, Bitmap favicon) {
465 // 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.
466 formattedUrlString = url;
468 // Display the loading URL is the URL text box.
469 urlTextBox.setText(url);
472 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
474 public void onPageFinished(WebView view, String url) {
475 formattedUrlString = url;
477 // Only update urlTextBox if the user is not typing in it.
478 if (!urlTextBox.hasFocus()) {
479 urlTextBox.setText(formattedUrlString);
482 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
483 sslCertificate = mainWebView.getCertificate();
486 // Handle SSL Certificate errors.
488 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
489 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
490 sslErrorHandler = handler;
492 // Display the SSL error `AlertDialog`.
493 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
494 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
498 mainWebView.setWebChromeClient(new WebChromeClient() {
499 // Update the progress bar when a page is loading.
501 public void onProgressChanged(WebView view, int progress) {
502 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
503 progressBar.setProgress(progress);
504 if (progress < 100) {
505 progressBar.setVisibility(View.VISIBLE);
507 progressBar.setVisibility(View.GONE);
509 //Stop the `SwipeToRefresh` indicator if it is running
510 swipeRefreshLayout.setRefreshing(false);
514 // Set the favorite icon when it changes.
516 public void onReceivedIcon(WebView view, Bitmap icon) {
517 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
520 // Place the favorite icon in the appBar.
521 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
522 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
525 // Enter full screen video
527 public void onShowCustomView(View view, CustomViewCallback callback) {
528 // Pause the ad if this is the free flavor.
529 if (BuildConfig.FLAVOR.contentEquals("free")) {
530 BannerAd.pauseAd(adView);
533 // Remove the translucent overlays.
534 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
536 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
537 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
539 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
540 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
541 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
543 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
545 // Set `rootCoordinatorLayout` to fill the entire screen.
546 rootCoordinatorLayout.setFitsSystemWindows(false);
548 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
549 fullScreenVideoFrameLayout.addView(view);
550 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
553 // Exit full screen video
554 public void onHideCustomView() {
555 // Hide `fullScreenVideoFrameLayout`.
556 fullScreenVideoFrameLayout.removeAllViews();
557 fullScreenVideoFrameLayout.setVisibility(View.GONE);
559 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
560 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
562 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
563 rootCoordinatorLayout.setFitsSystemWindows(true);
565 // Show the ad if this is the free flavor.
566 if (BuildConfig.FLAVOR.contentEquals("free")) {
567 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
568 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
570 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
571 adView = findViewById(R.id.adView);
576 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
577 registerForContextMenu(mainWebView);
579 // Allow the downloading of files.
580 mainWebView.setDownloadListener(new DownloadListener() {
582 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
583 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
584 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
585 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
589 // Allow pinch to zoom.
590 mainWebView.getSettings().setBuiltInZoomControls(true);
592 // Hide zoom controls.
593 mainWebView.getSettings().setDisplayZoomControls(false);
595 // Initialize cookieManager.
596 cookieManager = CookieManager.getInstance();
598 // 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).
599 customHeaders.put("X-Requested-With", "");
601 // Initialize the default preference values the first time the program is run.
602 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
604 // Apply the settings from the shared preferences.
607 // Get the intent information that started the app.
608 final Intent intent = getIntent();
610 if (intent.getData() != null) {
611 // Get the intent data and convert it to a string.
612 final Uri intentUriData = intent.getData();
613 formattedUrlString = intentUriData.toString();
616 // If formattedUrlString is null assign the homepage to it.
617 if (formattedUrlString == null) {
618 formattedUrlString = homepage;
621 // Load the initial website.
622 mainWebView.loadUrl(formattedUrlString, customHeaders);
624 // If the favorite icon is null, load the default.
625 if (favoriteIcon == null) {
626 // We have to use `ContextCompat` until API >= 21.
627 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
628 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
629 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
632 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
633 adView = findViewById(R.id.adView);
634 BannerAd.requestAd(adView);
639 protected void onNewIntent(Intent intent) {
640 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
643 if (intent.getData() != null) {
644 // Get the intent data and convert it to a string.
645 final Uri intentUriData = intent.getData();
646 formattedUrlString = intentUriData.toString();
649 // Close the navigation drawer if it is open.
650 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
651 drawerLayout.closeDrawer(GravityCompat.START);
655 mainWebView.loadUrl(formattedUrlString, customHeaders);
657 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
658 mainWebView.requestFocus();
662 public boolean onCreateOptionsMenu(Menu menu) {
663 // Inflate the menu; this adds items to the action bar if it is present.
664 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
666 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
669 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
670 updatePrivacyIcons(false);
672 // Get handles for the menu items.
673 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
674 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
675 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
676 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
678 // Only display third-Party Cookies if SDK >= 21
679 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
681 // Get the shared preference values. `this` references the current context.
682 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
684 // Set the status of the additional app bar icons. The default is `false`.
685 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
686 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
687 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
688 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
689 } else { //Do not display the additional icons.
690 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
691 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
692 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
699 public boolean onPrepareOptionsMenu(Menu menu) {
700 // Get handles for the menu items.
701 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
702 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
703 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
704 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
705 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
706 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
707 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
709 // Set the status of the menu item checkboxes.
710 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
711 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
712 toggleDomStorage.setChecked(domStorageEnabled);
713 toggleSaveFormData.setChecked(saveFormDataEnabled);
715 // Enable third-party cookies if first-party cookies are enabled.
716 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
718 // Enable DOM Storage if JavaScript is enabled.
719 toggleDomStorage.setEnabled(javaScriptEnabled);
721 // Enable Clear Cookies if there are any.
722 clearCookies.setEnabled(cookieManager.hasCookies());
724 // Enable Clear Form Data is there is any.
725 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
726 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
728 // Only show `Refresh` if `swipeToRefresh` is disabled.
729 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
731 // Initialize font size variables.
732 int fontSize = mainWebView.getSettings().getTextZoom();
733 String fontSizeTitle;
734 MenuItem selectedFontSizeMenuItem;
736 // Prepare the font size title and current size menu item.
739 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
740 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
744 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
745 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
749 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
750 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
754 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
755 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
759 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
760 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
764 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
765 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
769 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
770 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
774 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
775 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
779 // Set the font size title and select the current size menu item.
780 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
781 fontSizeMenuItem.setTitle(fontSizeTitle);
782 selectedFontSizeMenuItem.setChecked(true);
784 // Run all the other default commands.
785 super.onPrepareOptionsMenu(menu);
787 // `return true` displays the menu.
792 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
793 @SuppressLint("SetJavaScriptEnabled")
794 // removeAllCookies is deprecated, but it is required for API < 21.
795 @SuppressWarnings("deprecation")
796 public boolean onOptionsItemSelected(MenuItem menuItem) {
797 int menuItemId = menuItem.getItemId();
799 // Set the commands that relate to the menu entries.
800 switch (menuItemId) {
801 case R.id.toggleJavaScript:
802 // Switch the status of javaScriptEnabled.
803 javaScriptEnabled = !javaScriptEnabled;
805 // Apply the new JavaScript status.
806 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
808 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
809 updatePrivacyIcons(true);
811 // Display a `Snackbar`.
812 if (javaScriptEnabled) { // JavaScrip is enabled.
813 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
814 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
815 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
816 } else { // Privacy mode.
817 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
820 // Reload the WebView.
821 mainWebView.reload();
824 case R.id.toggleFirstPartyCookies:
825 // Switch the status of firstPartyCookiesEnabled.
826 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
828 // Update the menu checkbox.
829 menuItem.setChecked(firstPartyCookiesEnabled);
831 // Apply the new cookie status.
832 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
834 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
835 updatePrivacyIcons(true);
837 // Display a `Snackbar`.
838 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
839 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
840 } else if (javaScriptEnabled){ // JavaScript is still enabled.
841 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
842 } else { // Privacy mode.
843 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
846 // Reload the WebView.
847 mainWebView.reload();
850 case R.id.toggleThirdPartyCookies:
851 if (Build.VERSION.SDK_INT >= 21) {
852 // Switch the status of thirdPartyCookiesEnabled.
853 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
855 // Update the menu checkbox.
856 menuItem.setChecked(thirdPartyCookiesEnabled);
858 // Apply the new cookie status.
859 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
861 // Display a `Snackbar`.
862 if (thirdPartyCookiesEnabled) {
863 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
865 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
868 // Reload the WebView.
869 mainWebView.reload();
870 } // Else do nothing because SDK < 21.
873 case R.id.toggleDomStorage:
874 // Switch the status of domStorageEnabled.
875 domStorageEnabled = !domStorageEnabled;
877 // Update the menu checkbox.
878 menuItem.setChecked(domStorageEnabled);
880 // Apply the new DOM Storage status.
881 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
883 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
884 updatePrivacyIcons(true);
886 // Display a `Snackbar`.
887 if (domStorageEnabled) {
888 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
890 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
893 // Reload the WebView.
894 mainWebView.reload();
897 case R.id.toggleSaveFormData:
898 // Switch the status of saveFormDataEnabled.
899 saveFormDataEnabled = !saveFormDataEnabled;
901 // Update the menu checkbox.
902 menuItem.setChecked(saveFormDataEnabled);
904 // Apply the new form data status.
905 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
907 // Display a `Snackbar`.
908 if (saveFormDataEnabled) {
909 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
911 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
914 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
915 updatePrivacyIcons(true);
917 // Reload the WebView.
918 mainWebView.reload();
921 case R.id.clearCookies:
922 if (Build.VERSION.SDK_INT < 21) {
923 cookieManager.removeAllCookie();
925 cookieManager.removeAllCookies(null);
927 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
930 case R.id.clearDomStorage:
931 WebStorage webStorage = WebStorage.getInstance();
932 webStorage.deleteAllData();
933 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
936 case R.id.clearFormData:
937 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
938 mainWebViewDatabase.clearFormData();
939 mainWebView.reload();
942 case R.id.fontSizeFiftyPercent:
943 mainWebView.getSettings().setTextZoom(50);
946 case R.id.fontSizeSeventyFivePercent:
947 mainWebView.getSettings().setTextZoom(75);
950 case R.id.fontSizeOneHundredPercent:
951 mainWebView.getSettings().setTextZoom(100);
954 case R.id.fontSizeOneHundredTwentyFivePercent:
955 mainWebView.getSettings().setTextZoom(125);
958 case R.id.fontSizeOneHundredFiftyPercent:
959 mainWebView.getSettings().setTextZoom(150);
962 case R.id.fontSizeOneHundredSeventyFivePercent:
963 mainWebView.getSettings().setTextZoom(175);
966 case R.id.fontSizeTwoHundredPercent:
967 mainWebView.getSettings().setTextZoom(200);
970 case R.id.find_on_page:
971 // Hide the URL app bar.
972 Toolbar appBarToolbar = (Toolbar) findViewById(R.id.app_bar);
973 appBarToolbar.setVisibility(View.GONE);
975 // Show the Find on Page `RelativeLayout`.
976 LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
977 findOnPageLinearLayout.setVisibility(View.VISIBLE);
979 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
980 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
981 findOnPageEditText.postDelayed(new Runnable()
986 // Set the focus on `findOnPageEditText`.
987 findOnPageEditText.requestFocus();
989 // Display the keyboard.
990 inputMethodManager.showSoftInput(findOnPageEditText, 0);
996 Intent shareIntent = new Intent();
997 shareIntent.setAction(Intent.ACTION_SEND);
998 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
999 shareIntent.setType("text/plain");
1000 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1003 case R.id.addToHomescreen:
1004 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1005 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1006 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1008 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1012 // Get a `PrintManager` instance.
1013 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1015 // Convert `mainWebView` to `printDocumentAdapter`.
1016 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1018 // Print the document. The print attributes are `null`.
1019 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1023 mainWebView.reload();
1027 // Don't consume the event.
1028 return super.onOptionsItemSelected(menuItem);
1032 // removeAllCookies is deprecated, but it is required for API < 21.
1033 @SuppressWarnings("deprecation")
1035 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1036 int menuItemId = menuItem.getItemId();
1038 switch (menuItemId) {
1040 mainWebView.loadUrl(homepage, customHeaders);
1044 if (mainWebView.canGoBack()) {
1045 mainWebView.goBack();
1050 if (mainWebView.canGoForward()) {
1051 mainWebView.goForward();
1056 // Gte the `WebBackForwardList`.
1057 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1059 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1060 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1061 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1064 case R.id.bookmarks:
1065 // Launch Bookmarks.
1066 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1067 startActivity(bookmarksIntent);
1070 case R.id.downloads:
1071 // Launch the system Download Manager.
1072 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1074 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1075 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1077 startActivity(downloadManagerIntent);
1081 // Launch `Settings`.
1082 Intent settingsIntent = new Intent(this, Settings.class);
1083 startActivity(settingsIntent);
1088 Intent guideIntent = new Intent(this, Guide.class);
1089 startActivity(guideIntent);
1094 Intent aboutIntent = new Intent(this, About.class);
1095 startActivity(aboutIntent);
1098 case R.id.clearAndExit:
1099 // Clear cookies. The commands changed slightly in API 21.
1100 if (Build.VERSION.SDK_INT >= 21) {
1101 cookieManager.removeAllCookies(null);
1103 cookieManager.removeAllCookie();
1106 // Clear DOM storage.
1107 WebStorage domStorage = WebStorage.getInstance();
1108 domStorage.deleteAllData();
1111 WebViewDatabase formData = WebViewDatabase.getInstance(this);
1112 formData.clearFormData();
1114 // Clear cache. The argument of "true" includes disk files.
1115 mainWebView.clearCache(true);
1117 // Clear the back/forward history.
1118 mainWebView.clearHistory();
1120 // Clear any SSL certificate preferences.
1121 mainWebView.clearSslPreferences();
1123 // Clear `formattedUrlString`.
1124 formattedUrlString = null;
1126 // Clear `customHeaders`.
1127 customHeaders.clear();
1129 // Detach all views from `mainWebViewRelativeLayout`.
1130 RelativeLayout mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.mainWebViewRelativeLayout);
1131 mainWebViewRelativeLayout.removeAllViews();
1133 // Destroy the internal state of `mainWebView`.
1134 mainWebView.destroy();
1136 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1137 if (Build.VERSION.SDK_INT >= 21) {
1138 finishAndRemoveTask();
1143 // Remove the terminated program from RAM. The status code is `0`.
1151 // Close the navigation drawer.
1152 drawerLayout.closeDrawer(GravityCompat.START);
1157 public void onPostCreate(Bundle savedInstanceState) {
1158 super.onPostCreate(savedInstanceState);
1160 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1161 drawerToggle.syncState();
1165 public void onConfigurationChanged(Configuration newConfig) {
1166 super.onConfigurationChanged(newConfig);
1168 // Reload the ad for the free flavor if we are not in full screen mode.
1169 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1171 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1173 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1174 adView = findViewById(R.id.adView);
1177 // `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
1178 // ActivityCompat.invalidateOptionsMenu(this);
1182 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1183 // Store the `HitTestResult`.
1184 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1187 final String imageUrl;
1188 final String linkUrl;
1190 switch (hitTestResult.getType()) {
1191 // `SRC_ANCHOR_TYPE` is a link.
1192 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1193 // Get the target URL.
1194 linkUrl = hitTestResult.getExtra();
1196 // Set the target URL as the title of the `ContextMenu`.
1197 menu.setHeaderTitle(linkUrl);
1199 // Add a `Load URL` button.
1200 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1202 public boolean onMenuItemClick(MenuItem item) {
1203 mainWebView.loadUrl(linkUrl, customHeaders);
1208 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1209 menu.add(R.string.cancel);
1212 case WebView.HitTestResult.EMAIL_TYPE:
1213 // Get the target URL.
1214 linkUrl = hitTestResult.getExtra();
1216 // Set the target URL as the title of the `ContextMenu`.
1217 menu.setHeaderTitle(linkUrl);
1219 // Add a `Write Email` button.
1220 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1222 public boolean onMenuItemClick(MenuItem item) {
1223 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1224 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1226 // Parse the url and set it as the data for the `Intent`.
1227 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1229 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1230 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1233 startActivity(emailIntent);
1238 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1239 menu.add(R.string.cancel);
1242 // `IMAGE_TYPE` is an image.
1243 case WebView.HitTestResult.IMAGE_TYPE:
1244 // Get the image URL.
1245 imageUrl = hitTestResult.getExtra();
1247 // Set the image URL as the title of the `ContextMenu`.
1248 menu.setHeaderTitle(imageUrl);
1250 // Add a `View Image` button.
1251 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1253 public boolean onMenuItemClick(MenuItem item) {
1254 mainWebView.loadUrl(imageUrl, customHeaders);
1259 // Add a `Download Image` button.
1260 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1262 public boolean onMenuItemClick(MenuItem item) {
1263 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1264 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1265 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1270 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1271 menu.add(R.string.cancel);
1275 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1276 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1277 // Get the image URL.
1278 imageUrl = hitTestResult.getExtra();
1280 // Set the image URL as the title of the `ContextMenu`.
1281 menu.setHeaderTitle(imageUrl);
1283 // Add a `View Image` button.
1284 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1286 public boolean onMenuItemClick(MenuItem item) {
1287 mainWebView.loadUrl(imageUrl, customHeaders);
1292 // Add a `Download Image` button.
1293 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1295 public boolean onMenuItemClick(MenuItem item) {
1296 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1297 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1298 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1303 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1304 menu.add(R.string.cancel);
1310 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1311 // Get shortcutNameEditText from the alert dialog.
1312 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1314 // Create the bookmark shortcut based on formattedUrlString.
1315 Intent bookmarkShortcut = new Intent();
1316 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1317 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1319 // Place the bookmark shortcut on the home screen.
1320 Intent placeBookmarkShortcut = new Intent();
1321 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1322 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1323 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1324 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1325 sendBroadcast(placeBookmarkShortcut);
1329 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1330 // Get a handle for the system `DOWNLOAD_SERVICE`.
1331 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1333 // Parse `imageUrl`.
1334 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1336 // Get the file name from `dialogFragment`.
1337 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1338 String imageName = downloadImageNameEditText.getText().toString();
1340 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1341 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1342 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1343 } else { // Only set the title using `imageName`.
1344 downloadRequest.setTitle(imageName);
1347 // Allow `MediaScanner` to index the download if it is a media file.
1348 downloadRequest.allowScanningByMediaScanner();
1350 // Add the URL as the description for the download.
1351 downloadRequest.setDescription(imageUrl);
1353 // Show the download notification after the download is completed.
1354 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1356 // Initiate the download.
1357 downloadManager.enqueue(downloadRequest);
1361 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1362 // Get a handle for the system `DOWNLOAD_SERVICE`.
1363 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1365 // Parse `downloadUrl`.
1366 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1368 // Get the file name from `dialogFragment`.
1369 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1370 String fileName = downloadFileNameEditText.getText().toString();
1372 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1373 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `fileName`.
1374 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1375 } else { // Only set the title using `fileName`.
1376 downloadRequest.setTitle(fileName);
1379 // Allow `MediaScanner` to index the download if it is a media file.
1380 downloadRequest.allowScanningByMediaScanner();
1382 // Add the URL as the description for the download.
1383 downloadRequest.setDescription(downloadUrl);
1385 // Show the download notification after the download is completed.
1386 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1388 // Initiate the download.
1389 downloadManager.enqueue(downloadRequest);
1392 public void viewSslCertificate(View view) {
1393 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1394 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1395 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1399 public void onSslErrorCancel() {
1400 sslErrorHandler.cancel();
1404 public void onSslErrorProceed() {
1405 sslErrorHandler.proceed();
1409 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1410 // Load the history entry.
1411 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1415 public void onClearHistory() {
1416 // Clear the history.
1417 mainWebView.clearHistory();
1420 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1422 public void onBackPressed() {
1423 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1424 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1425 drawerLayout.closeDrawer(GravityCompat.START);
1427 // Load the previous URL if available.
1428 if (mainWebView.canGoBack()) {
1429 mainWebView.goBack();
1431 // Pass `onBackPressed()` to the system.
1432 super.onBackPressed();
1438 public void onPause() {
1439 // Pause `mainWebView`.
1440 mainWebView.onPause();
1442 // Stop all JavaScript.
1443 mainWebView.pauseTimers();
1445 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1446 if (BuildConfig.FLAVOR.contentEquals("free")) {
1447 BannerAd.pauseAd(adView);
1454 public void onResume() {
1457 // Resume JavaScript (if enabled).
1458 mainWebView.resumeTimers();
1460 // Resume `mainWebView`.
1461 mainWebView.onResume();
1463 // Resume the adView for the free flavor.
1464 if (BuildConfig.FLAVOR.contentEquals("free")) {
1465 BannerAd.resumeAd(adView);
1470 public void onRestart() {
1473 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1476 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1477 updatePrivacyIcons(true);
1481 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1482 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1483 String unformattedUrlString = urlTextBox.getText().toString().trim();
1485 URL unformattedUrl = null;
1486 Uri.Builder formattedUri = new Uri.Builder();
1488 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1489 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1490 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1491 if (!unformattedUrlString.startsWith("http")) {
1492 unformattedUrlString = "http://" + unformattedUrlString;
1495 // 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.
1497 unformattedUrl = new URL(unformattedUrlString);
1498 } catch (MalformedURLException e) {
1499 e.printStackTrace();
1502 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1503 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1504 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1505 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1506 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1507 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1509 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1510 formattedUrlString = formattedUri.build().toString();
1512 // Sanitize the search input and convert it to a DuckDuckGo search.
1513 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1515 // Use the correct search URL.
1516 if (javaScriptEnabled) { // JavaScript is enabled.
1517 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1518 } else { // JavaScript is disabled.
1519 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1523 mainWebView.loadUrl(formattedUrlString, customHeaders);
1525 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1526 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1529 public void findPreviousOnPage(View view) {
1530 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1531 mainWebView.findNext(false);
1534 public void findNextOnPage(View view) {
1535 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1536 mainWebView.findNext(true);
1539 public void closeFindOnPage(View view) {
1540 // Delete the contents of `find_on_page_edittext`.
1541 findOnPageEditText.setText(null);
1543 // Clear the highlighted phrases.
1544 mainWebView.clearMatches();
1546 // Hide the Find on Page `RelativeLayout`.
1547 LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
1548 findOnPageLinearLayout.setVisibility(View.GONE);
1550 // Show the URL app bar.
1551 Toolbar appBarToolbar = (Toolbar) findViewById(R.id.app_bar);
1552 appBarToolbar.setVisibility(View.VISIBLE);
1554 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1555 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1558 private void applySettings() {
1559 // Get the shared preference values. `this` references the current context.
1560 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1562 // Store the values from `sharedPreferences` in variables.
1563 String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
1564 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1565 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1566 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1567 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1568 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1569 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1570 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1571 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1572 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1573 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1574 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1575 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1577 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1578 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1579 // Get the values from `sharedPreferences`.
1580 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1581 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1582 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1583 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1584 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1586 // Apply the default settings.
1587 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1588 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1589 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1590 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1591 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1593 // Set third-party cookies status if API >= 21.
1594 if (Build.VERSION.SDK_INT >= 21) {
1595 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1599 // Apply the other settings from `sharedPreferences`.
1600 homepage = homepageString;
1601 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1603 // Set the user agent initial status.
1604 switch (userAgentString) {
1605 case "Default user agent":
1606 // Set the user agent to `""`, which uses the default value.
1607 mainWebView.getSettings().setUserAgentString("");
1610 case "Custom user agent":
1611 // Set the custom user agent.
1612 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1616 // Use the selected user agent.
1617 mainWebView.getSettings().setUserAgentString(userAgentString);
1621 // Set JavaScript disabled search.
1622 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1623 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1624 } else { // Use the string from the pre-built list.
1625 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1628 // Set JavaScript enabled search.
1629 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1630 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1631 } else { // Use the string from the pre-built list.
1632 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1635 // Set Do Not Track status.
1636 if (doNotTrackEnabled) {
1637 customHeaders.put("DNT", "1");
1639 customHeaders.remove("DNT");
1642 // Set Orbot proxy status.
1643 if (proxyThroughOrbot) {
1644 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1645 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1646 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1647 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1650 // If we are in full screen mode update the `SYSTEM_UI` flags.
1651 if (!appBar.isShowing()) {
1652 if (hideSystemBarsOnFullscreen) { // Hide everything.
1653 // Remove the translucent navigation setting if it is currently flagged.
1654 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1656 // Remove the translucent status bar overlay.
1657 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1659 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1660 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1662 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1663 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1664 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1666 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1667 } else { // Hide everything except the status and navigation bars.
1668 // Add the translucent status flag if it is unset.
1669 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1671 if (translucentNavigationBarOnFullscreen) {
1672 // Set the navigation bar to be translucent.
1673 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1675 // Set the navigation bar to be black.
1676 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1682 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1683 // Get handles for the icons.
1684 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1685 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1686 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1687 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1689 // Update `privacyIcon`.
1690 if (javaScriptEnabled) { // JavaScript is enabled.
1691 privacyIcon.setIcon(R.drawable.javascript_enabled);
1692 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1693 privacyIcon.setIcon(R.drawable.warning);
1694 } else { // All the dangerous features are disabled.
1695 privacyIcon.setIcon(R.drawable.privacy_mode);
1698 // Update `firstPartyCookiesIcon`.
1699 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1700 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1701 } else { // First-party cookies are disabled.
1702 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1705 // Update `domStorageIcon`.
1706 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1707 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1708 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1709 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1710 } else { // JavaScript is disabled, so DOM storage is ghosted.
1711 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1714 // Update `formDataIcon`.
1715 if (saveFormDataEnabled) { // Form data is enabled.
1716 formDataIcon.setIcon(R.drawable.form_data_enabled);
1717 } else { // Form data is disabled.
1718 formDataIcon.setIcon(R.drawable.form_data_disabled);
1721 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1722 if (runInvalidateOptionsMenu) {
1723 ActivityCompat.invalidateOptionsMenu(this);