]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebView.java
e6e5304ab9290bcb5793fa41c815395357f82d93
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebView.java
1 /*
2  * Copyright 2015-2017 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.graphics.Bitmap;
36 import android.graphics.drawable.BitmapDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.net.Uri;
39 import android.net.http.SslCertificate;
40 import android.net.http.SslError;
41 import android.os.Build;
42 import android.os.Bundle;
43 import android.preference.PreferenceManager;
44 import android.print.PrintDocumentAdapter;
45 import android.print.PrintManager;
46 import android.support.annotation.NonNull;
47 import android.support.design.widget.CoordinatorLayout;
48 import android.support.design.widget.NavigationView;
49 import android.support.design.widget.Snackbar;
50 import android.support.v4.app.ActivityCompat;
51 import android.support.v4.content.ContextCompat;
52 import android.support.v4.view.GravityCompat;
53 import android.support.v4.widget.DrawerLayout;
54 import android.support.v4.widget.SwipeRefreshLayout;
55 import android.support.v7.app.ActionBar;
56 import android.support.v7.app.ActionBarDrawerToggle;
57 import android.support.v7.app.AppCompatActivity;
58 import android.support.v7.app.AppCompatDialogFragment;
59 import android.support.v7.widget.Toolbar;
60 import android.text.Editable;
61 import android.text.TextWatcher;
62 import android.util.Patterns;
63 import android.view.ContextMenu;
64 import android.view.GestureDetector;
65 import android.view.KeyEvent;
66 import android.view.Menu;
67 import android.view.MenuItem;
68 import android.view.MotionEvent;
69 import android.view.View;
70 import android.view.WindowManager;
71 import android.view.inputmethod.InputMethodManager;
72 import android.webkit.CookieManager;
73 import android.webkit.DownloadListener;
74 import android.webkit.SslErrorHandler;
75 import android.webkit.WebBackForwardList;
76 import android.webkit.WebChromeClient;
77 import android.webkit.WebResourceResponse;
78 import android.webkit.WebStorage;
79 import android.webkit.WebView;
80 import android.webkit.WebViewClient;
81 import android.webkit.WebViewDatabase;
82 import android.widget.EditText;
83 import android.widget.FrameLayout;
84 import android.widget.ImageView;
85 import android.widget.LinearLayout;
86 import android.widget.ProgressBar;
87 import android.widget.RelativeLayout;
88 import android.widget.TextView;
89
90 import com.stoutner.privacybrowser.BannerAd;
91 import com.stoutner.privacybrowser.BuildConfig;
92 import com.stoutner.privacybrowser.R;
93 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
95 import com.stoutner.privacybrowser.dialogs.DownloadFile;
96 import com.stoutner.privacybrowser.dialogs.DownloadImage;
97 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
98 import com.stoutner.privacybrowser.dialogs.UrlHistory;
99 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
100
101 import java.io.BufferedReader;
102 import java.io.ByteArrayInputStream;
103 import java.io.IOException;
104 import java.io.InputStreamReader;
105 import java.io.UnsupportedEncodingException;
106 import java.net.MalformedURLException;
107 import java.net.URL;
108 import java.net.URLEncoder;
109 import java.util.HashMap;
110 import java.util.HashSet;
111 import java.util.Map;
112 import java.util.Set;
113
114 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
115 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
116         SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
117
118     // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
119     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
120     public static ActionBar appBar;
121
122     // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
123     // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
124     public static Bitmap favoriteIcon;
125
126     // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
127     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
128     public static String formattedUrlString;
129
130     // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`.  It is also used in `onCreate()`.
131     public static SslCertificate sslCertificate;
132
133     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`.
134     public static String orbotStatus;
135
136
137     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
138     private DrawerLayout drawerLayout;
139
140     // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
141     private CoordinatorLayout rootCoordinatorLayout;
142
143     // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
144     private WebView mainWebView;
145
146     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
147     private FrameLayout fullScreenVideoFrameLayout;
148
149     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
150     private SwipeRefreshLayout swipeRefreshLayout;
151
152     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
153     private CookieManager cookieManager;
154
155     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
156     private final Map<String, String> customHeaders = new HashMap<>();
157
158     // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
159     // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
160     private Boolean javaScriptEnabled;
161
162     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applySettings()`.
163     private boolean firstPartyCookiesEnabled;
164
165     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
166     private boolean thirdPartyCookiesEnabled;
167
168     // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
169     private boolean domStorageEnabled;
170
171     // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
172     private boolean saveFormDataEnabled;
173
174     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
175     private boolean swipeToRefreshEnabled;
176
177     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
178     private String homepage;
179
180     // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
181     private String javaScriptDisabledSearchURL;
182
183     // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
184     private String javaScriptEnabledSearchURL;
185
186     // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
187     private boolean adBlockerEnabled;
188
189     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
190     private boolean fullScreenBrowsingModeEnabled;
191
192     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applySettings()`.
193     private boolean inFullScreenBrowsingMode;
194
195     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
196     private boolean hideSystemBarsOnFullscreen;
197
198     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
199     private boolean translucentNavigationBarOnFullscreen;
200
201     // `proxyThroughOrbot` is used in `onCreate()` and `applySettings()`
202     private boolean proxyThroughOrbot;
203
204     // `pendingUrl` is used in `onCreate()` and `applySettings()`
205     private static String pendingUrl;
206
207     // `waitingForOrbotData` is used in `onCreate()` and `applySettings()`.
208     private String waitingForOrbotHTMLString;
209
210     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
211     private LinearLayout findOnPageLinearLayout;
212
213     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
214     private EditText findOnPageEditText;
215
216     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
217     private Menu mainMenu;
218
219     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
220     private ActionBarDrawerToggle drawerToggle;
221
222     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
223     private Toolbar supportAppBar;
224
225     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
226     private EditText urlTextBox;
227
228     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
229     private View adView;
230
231     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
232     private SslErrorHandler sslErrorHandler;
233
234     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
235     private InputMethodManager inputMethodManager;
236
237     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
238     private RelativeLayout mainWebViewRelativeLayout;
239
240     @Override
241     // 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.
242     @SuppressLint("SetJavaScriptEnabled")
243     protected void onCreate(Bundle savedInstanceState) {
244         super.onCreate(savedInstanceState);
245         setContentView(R.layout.drawerlayout);
246
247         // Get a handle for `inputMethodManager`.
248         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
249
250         // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
251         supportAppBar = (Toolbar) findViewById(R.id.app_bar);
252         setSupportActionBar(supportAppBar);
253         appBar = getSupportActionBar();
254
255         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
256         assert appBar != null;
257
258         // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
259         appBar.setCustomView(R.layout.url_app_bar);
260         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
261
262         // Set the "go" button on the keyboard to load the URL in urlTextBox.
263         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
264         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
265             @Override
266             public boolean onKey(View v, int keyCode, KeyEvent event) {
267                 // If the event is a key-down event on the `enter` button, load the URL.
268                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
269                     // Load the URL into the mainWebView and consume the event.
270                     try {
271                         loadUrlFromTextBox();
272                     } catch (UnsupportedEncodingException e) {
273                         e.printStackTrace();
274                     }
275                     // If the enter key was pressed, consume the event.
276                     return true;
277                 } else {
278                     // If any other key was pressed, do not consume the event.
279                     return false;
280                 }
281             }
282         });
283
284         // Set `waitingForOrbotHTMLString`.
285         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
286
287         // Initialize `pendingUrl`.
288         pendingUrl = "";
289
290         // Set the initial Orbot status.
291         orbotStatus = "unknown";
292
293         // Create an Orbot status `BroadcastReceiver`.
294         BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
295             @Override
296             public void onReceive(Context context, Intent intent) {
297                 // Store the content of the status message in `orbotStatus`.
298                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
299
300                 // If we are waiting on `pendingUrl`, load it now that Orbot is connected.
301                 if (orbotStatus.equals("ON") && !pendingUrl.isEmpty()) {
302
303                     // Wait 500 milliseconds, because Orbot isn't really ready yet.
304                     try {
305                         Thread.sleep(500);
306                     } catch (InterruptedException exception) {
307                         // Do nothing.
308                     }
309
310                     // Copy `pendingUrl` to `formattedUrlString` and reset `pendingUrl` to be empty.
311                     formattedUrlString = pendingUrl;
312                     pendingUrl = "";
313
314                     // Load `formattedUrlString
315                     mainWebView.loadUrl(formattedUrlString, customHeaders);
316                 }
317             }
318         };
319
320         // Register `orbotStatusBroadcastReceiver` on `this` context.
321         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
322
323         // Get handles for views that need to be accessed.
324         drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
325         rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
326         mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
327         mainWebView = (WebView) findViewById(R.id.mainWebView);
328         findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
329         findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
330         fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
331
332         // Create a double-tap listener to toggle full-screen mode.
333         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
334             // Override `onDoubleTap()`.  All other events are handled using the default settings.
335             @Override
336             public boolean onDoubleTap(MotionEvent event) {
337                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
338                     // Toggle `inFullScreenBrowsingMode`.
339                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
340
341                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
342                         // Hide the `appBar`.
343                         appBar.hide();
344
345                         // Hide the `BannerAd` in the free flavor.
346                         if (BuildConfig.FLAVOR.contentEquals("free")) {
347                             BannerAd.hideAd(adView);
348                         }
349
350                         // Modify the system bars.
351                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
352                             // Remove the translucent overlays.
353                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
354
355                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
356                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
357
358                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
359                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
360                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
361                              */
362                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
363
364                             // Set `rootCoordinatorLayout` to fill the whole screen.
365                             rootCoordinatorLayout.setFitsSystemWindows(false);
366                         } else {  // Hide everything except the status and navigation bars.
367                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
368                             rootCoordinatorLayout.setFitsSystemWindows(false);
369
370                             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.
371                                 // Set the navigation bar to be translucent.
372                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
373                             }
374                         }
375                     } else {  // Switch to normal viewing mode.
376                         // Show the `appBar`.
377                         appBar.show();
378
379                         // Show the `BannerAd` in the free flavor.
380                         if (BuildConfig.FLAVOR.contentEquals("free")) {
381                             // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
382                             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
383
384                             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
385                             adView = findViewById(R.id.adView);
386                         }
387
388                         // Remove the translucent navigation bar flag if it is set.
389                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
390
391                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
392                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
393
394                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
395                         rootCoordinatorLayout.setSystemUiVisibility(0);
396
397                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
398                         rootCoordinatorLayout.setFitsSystemWindows(true);
399                     }
400
401                     // Consume the double-tap.
402                     return true;
403                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
404                     return false;
405                 }
406             }
407         });
408
409         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
410         mainWebView.setOnTouchListener(new View.OnTouchListener() {
411             @Override
412             public boolean onTouch(View v, MotionEvent event) {
413                 // Send the `event` to `gestureDetector`.
414                 return gestureDetector.onTouchEvent(event);
415             }
416         });
417
418         // Update `findOnPageCountTextView`.
419         mainWebView.setFindListener(new WebView.FindListener() {
420             // Get a handle for `findOnPageCountTextView`.
421             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
422
423             @Override
424             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
425                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
426                     // Set `findOnPageCountTextView` to `0/0`.
427                     findOnPageCountTextView.setText(R.string.zero_of_zero);
428                 } else if (isDoneCounting) {  // There are matches.
429                     // `activeMatchOrdinal` is zero-based.
430                     int activeMatch = activeMatchOrdinal + 1;
431
432                     // Set `findOnPageCountTextView`.
433                     findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
434                 }
435             }
436         });
437
438         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
439         findOnPageEditText.addTextChangedListener(new TextWatcher() {
440             @Override
441             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
442                 // Do nothing.
443             }
444
445             @Override
446             public void onTextChanged(CharSequence s, int start, int before, int count) {
447                 // Do nothing.
448             }
449
450             @Override
451             public void afterTextChanged(Editable s) {
452                 // Search for the text in `mainWebView`.
453                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
454             }
455         });
456
457         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
458         findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
459             @Override
460             public boolean onKey(View v, int keyCode, KeyEvent event) {
461                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
462                     // Hide the soft keyboard.  `0` indicates no additional flags.
463                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
464
465                     // Consume the event.
466                     return true;
467                 } else {  // A different key was pressed.
468                     // Do not consume the event.
469                     return false;
470                 }
471             }
472         });
473
474         // Implement swipe to refresh
475         swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
476         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
477         swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
478             @Override
479             public void onRefresh() {
480                 mainWebView.reload();
481             }
482         });
483
484         // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
485         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
486
487         // Listen for touches on the navigation menu.
488         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
489         navigationView.setNavigationItemSelectedListener(this);
490
491         // 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.
492         final Menu navigationMenu = navigationView.getMenu();
493         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
494         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
495         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
496
497         // The `DrawerListener` allows us to update the Navigation Menu.
498         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
499             @Override
500             public void onDrawerSlide(View drawerView, float slideOffset) {
501             }
502
503             @Override
504             public void onDrawerOpened(View drawerView) {
505             }
506
507             @Override
508             public void onDrawerClosed(View drawerView) {
509             }
510
511             @Override
512             public void onDrawerStateChanged(int newState) {
513                 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
514                 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
515                 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
516                 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
517
518                 // Hide the keyboard so we can see the navigation menu.  `0` indicates no additional flags.
519                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
520             }
521         });
522
523         // drawerToggle creates the hamburger icon at the start of the AppBar.
524         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
525
526         // Initialize `adServerSet`.
527         final Set<String> adServersSet = new HashSet<>();
528
529         // Load the list of ad servers into memory.
530         try {
531             // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
532             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
533
534             // Create a string for storing each ad server.
535             String adServer;
536
537             // Populate `adServersSet`.
538             while ((adServer = bufferedReader.readLine()) != null) {
539                 adServersSet.add(adServer);
540             }
541
542             // Close `bufferedReader`.
543             bufferedReader.close();
544         } catch (IOException ioException) {
545             // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
546         }
547
548         mainWebView.setWebViewClient(new WebViewClient() {
549             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
550             // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
551             @SuppressWarnings("deprecation")
552             @Override
553             public boolean shouldOverrideUrlLoading(WebView view, String url) {
554                 // Use an external email program if the link begins with `mailto:`.
555                 if (url.startsWith("mailto:")) {
556                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
557                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
558
559                     // Parse the url and set it as the data for the `Intent`.
560                     emailIntent.setData(Uri.parse(url));
561
562                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
563                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
564
565                     // Make it so.
566                     startActivity(emailIntent);
567                     return true;
568                 } else {  // Load the URL in Privacy Browser.
569                     mainWebView.loadUrl(url, customHeaders);
570                     return true;
571                 }
572             }
573
574             // Block ads.  We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
575             @SuppressWarnings("deprecation")
576             @Override
577             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
578                 if (adBlockerEnabled) {  // Block ads.
579                     // Extract the host from `url`.
580                     Uri requestUri = Uri.parse(url);
581                     String requestHost = requestUri.getHost();
582
583                     // Create a variable to track if this is an ad server.
584                     boolean requestHostIsAdServer = false;
585
586                     // Check all the subdomains of `requestHost` if it is not `null`.
587                     if (requestHost != null) {
588                         while (requestHost.contains(".")) {
589                             if (adServersSet.contains(requestHost)) {
590                                 requestHostIsAdServer = true;
591                             }
592
593                             // Strip out the lowest subdomain of `requestHost`.
594                             requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
595                         }
596                     }
597
598                     if (requestHostIsAdServer) {  // It is an ad server.
599                         // Return an empty `WebResourceResponse`.
600                         return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
601                     } else {  // It is not an ad server.
602                         // `return null` loads the requested resource.
603                         return null;
604                     }
605                 } else {  // Ad blocking is disabled.
606                     // `return null` loads the requested resource.
607                     return null;
608                 }
609             }
610
611             // Update the URL in urlTextBox when the page starts to load.
612             @Override
613             public void onPageStarted(WebView view, String url, Bitmap favicon) {
614                 // Check to see if we are waiting on Orbot.
615                 if (pendingUrl.isEmpty()) {  // We are not waiting on Orbot, so we need to process the URL.
616                     // 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.
617                     formattedUrlString = url;
618
619                     // Display the loading URL is the URL text box.
620                     urlTextBox.setText(url);
621                 }
622             }
623
624             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
625             @Override
626             public void onPageFinished(WebView view, String url) {
627                 // Check to see if we are waiting on Orbot.
628                 if (pendingUrl.isEmpty()) {  // we are not waiting on Orbot, so we need to process the URL.
629                     formattedUrlString = url;
630
631                     // Only update urlTextBox if the user is not typing in it.
632                     if (!urlTextBox.hasFocus()) {
633                         urlTextBox.setText(formattedUrlString);
634                     }
635
636                     // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
637                     sslCertificate = mainWebView.getCertificate();
638                 }
639             }
640
641             // Handle SSL Certificate errors.
642             @Override
643             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
644                 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
645                 sslErrorHandler = handler;
646
647                 // Display the SSL error `AlertDialog`.
648                 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
649                 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
650             }
651         });
652
653         mainWebView.setWebChromeClient(new WebChromeClient() {
654             // Update the progress bar when a page is loading.
655             @Override
656             public void onProgressChanged(WebView view, int progress) {
657                 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
658                 progressBar.setProgress(progress);
659                 if (progress < 100) {
660                     progressBar.setVisibility(View.VISIBLE);
661                 } else {
662                     progressBar.setVisibility(View.GONE);
663
664                     //Stop the `SwipeToRefresh` indicator if it is running
665                     swipeRefreshLayout.setRefreshing(false);
666                 }
667             }
668
669             // Set the favorite icon when it changes.
670             @Override
671             public void onReceivedIcon(WebView view, Bitmap icon) {
672                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
673                 favoriteIcon = icon;
674
675                 // Place the favorite icon in the appBar.
676                 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
677                 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
678             }
679
680             // Enter full screen video
681             @Override
682             public void onShowCustomView(View view, CustomViewCallback callback) {
683                 // Pause the ad if this is the free flavor.
684                 if (BuildConfig.FLAVOR.contentEquals("free")) {
685                     BannerAd.pauseAd(adView);
686                 }
687
688                 // Remove the translucent overlays.
689                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
690
691                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
692                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
693
694                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
695                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
696                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
697                  */
698                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
699
700                 // Set `rootCoordinatorLayout` to fill the entire screen.
701                 rootCoordinatorLayout.setFitsSystemWindows(false);
702
703                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
704                 fullScreenVideoFrameLayout.addView(view);
705                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
706             }
707
708             // Exit full screen video
709             public void onHideCustomView() {
710                 // Hide `fullScreenVideoFrameLayout`.
711                 fullScreenVideoFrameLayout.removeAllViews();
712                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
713
714                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
715                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
716
717                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
718                 rootCoordinatorLayout.setFitsSystemWindows(true);
719
720                 // Show the ad if this is the free flavor.
721                 if (BuildConfig.FLAVOR.contentEquals("free")) {
722                     // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
723                     BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
724
725                     // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
726                     adView = findViewById(R.id.adView);
727                 }
728             }
729         });
730
731         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
732         registerForContextMenu(mainWebView);
733
734         // Allow the downloading of files.
735         mainWebView.setDownloadListener(new DownloadListener() {
736             @Override
737             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
738                 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
739                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
740                 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
741             }
742         });
743
744         // Allow pinch to zoom.
745         mainWebView.getSettings().setBuiltInZoomControls(true);
746
747         // Hide zoom controls.
748         mainWebView.getSettings().setDisplayZoomControls(false);
749
750         // Initialize cookieManager.
751         cookieManager = CookieManager.getInstance();
752
753         // 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).
754         customHeaders.put("X-Requested-With", "");
755
756         // Initialize the default preference values the first time the program is run.  `this` is the context.  `false` keeps this command from resetting any current preferences back to default.
757         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
758
759         // Get the intent information that started the app.
760         final Intent intent = getIntent();
761
762         if (intent.getData() != null) {
763             // Get the intent data and convert it to a string.
764             final Uri intentUriData = intent.getData();
765             formattedUrlString = intentUriData.toString();
766         }
767
768         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
769         inFullScreenBrowsingMode = false;
770
771         // Initialize AdView for the free flavor.
772         adView = findViewById(R.id.adView);
773
774         // Apply the settings from the shared preferences.
775         applySettings();
776
777         // Load `formattedUrlString` if we are not proxying through Orbot and waiting for Orbot to connect.
778         if (!(proxyThroughOrbot && !orbotStatus.equals("ON"))) {
779             mainWebView.loadUrl(formattedUrlString, customHeaders);
780         }
781
782         // If the favorite icon is null, load the default.
783         if (favoriteIcon == null) {
784             // We have to use `ContextCompat` until API >= 21.
785             Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
786             BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
787             favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
788         }
789     }
790
791
792     @Override
793     protected void onNewIntent(Intent intent) {
794         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
795         setIntent(intent);
796
797         if (intent.getData() != null) {
798             // Get the intent data and convert it to a string.
799             final Uri intentUriData = intent.getData();
800             formattedUrlString = intentUriData.toString();
801         }
802
803         // Close the navigation drawer if it is open.
804         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
805             drawerLayout.closeDrawer(GravityCompat.START);
806         }
807
808         // Load the website.
809         mainWebView.loadUrl(formattedUrlString, customHeaders);
810
811         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
812         mainWebView.requestFocus();
813     }
814
815     @Override
816     public boolean onCreateOptionsMenu(Menu menu) {
817         // Inflate the menu; this adds items to the action bar if it is present.
818         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
819
820         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
821         mainMenu = menu;
822
823         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
824         updatePrivacyIcons(false);
825
826         // Get handles for the menu items.
827         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
828         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
829         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
830         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
831
832         // Only display third-Party Cookies if SDK >= 21
833         toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
834
835         // Get the shared preference values.  `this` references the current context.
836         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
837
838         // Set the status of the additional app bar icons.  The default is `false`.
839         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
840             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
841             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
842             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
843         } else { //Do not display the additional icons.
844             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
845             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
846             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
847         }
848
849         return true;
850     }
851
852     @Override
853     public boolean onPrepareOptionsMenu(Menu menu) {
854         // Get handles for the menu items.
855         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
856         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
857         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
858         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
859         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
860         MenuItem clearFormData = menu.findItem(R.id.clearFormData);
861         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
862
863         // Set the status of the menu item checkboxes.
864         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
865         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
866         toggleDomStorage.setChecked(domStorageEnabled);
867         toggleSaveFormData.setChecked(saveFormDataEnabled);
868
869         // Enable third-party cookies if first-party cookies are enabled.
870         toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
871
872         // Enable DOM Storage if JavaScript is enabled.
873         toggleDomStorage.setEnabled(javaScriptEnabled);
874
875         // Enable Clear Cookies if there are any.
876         clearCookies.setEnabled(cookieManager.hasCookies());
877
878         // Enable Clear Form Data is there is any.
879         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
880         clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
881
882         // Only show `Refresh` if `swipeToRefresh` is disabled.
883         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
884
885         // Initialize font size variables.
886         int fontSize = mainWebView.getSettings().getTextZoom();
887         String fontSizeTitle;
888         MenuItem selectedFontSizeMenuItem;
889
890         // Prepare the font size title and current size menu item.
891         switch (fontSize) {
892             case 50:
893                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
894                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
895                 break;
896
897             case 75:
898                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
899                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
900                 break;
901
902             case 100:
903                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
904                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
905                 break;
906
907             case 125:
908                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
909                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
910                 break;
911
912             case 150:
913                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
914                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
915                 break;
916
917             case 175:
918                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
919                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
920                 break;
921
922             case 200:
923                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
924                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
925                 break;
926
927             default:
928                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
929                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
930                 break;
931         }
932
933         // Set the font size title and select the current size menu item.
934         MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
935         fontSizeMenuItem.setTitle(fontSizeTitle);
936         selectedFontSizeMenuItem.setChecked(true);
937
938         // Run all the other default commands.
939         super.onPrepareOptionsMenu(menu);
940
941         // `return true` displays the menu.
942         return true;
943     }
944
945     @Override
946     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
947     @SuppressLint("SetJavaScriptEnabled")
948     // removeAllCookies is deprecated, but it is required for API < 21.
949     @SuppressWarnings("deprecation")
950     public boolean onOptionsItemSelected(MenuItem menuItem) {
951         int menuItemId = menuItem.getItemId();
952
953         // Set the commands that relate to the menu entries.
954         switch (menuItemId) {
955             case R.id.toggleJavaScript:
956                 // Switch the status of javaScriptEnabled.
957                 javaScriptEnabled = !javaScriptEnabled;
958
959                 // Apply the new JavaScript status.
960                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
961
962                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
963                 updatePrivacyIcons(true);
964
965                 // Display a `Snackbar`.
966                 if (javaScriptEnabled) {  // JavaScrip is enabled.
967                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
968                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
969                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
970                 } else {  // Privacy mode.
971                     Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
972                 }
973
974                 // Reload the WebView.
975                 mainWebView.reload();
976                 return true;
977
978             case R.id.toggleFirstPartyCookies:
979                 // Switch the status of firstPartyCookiesEnabled.
980                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
981
982                 // Update the menu checkbox.
983                 menuItem.setChecked(firstPartyCookiesEnabled);
984
985                 // Apply the new cookie status.
986                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
987
988                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
989                 updatePrivacyIcons(true);
990
991                 // Display a `Snackbar`.
992                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
993                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
994                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
995                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
996                 } else {  // Privacy mode.
997                     Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
998                 }
999
1000                 // Reload the WebView.
1001                 mainWebView.reload();
1002                 return true;
1003
1004             case R.id.toggleThirdPartyCookies:
1005                 if (Build.VERSION.SDK_INT >= 21) {
1006                     // Switch the status of thirdPartyCookiesEnabled.
1007                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1008
1009                     // Update the menu checkbox.
1010                     menuItem.setChecked(thirdPartyCookiesEnabled);
1011
1012                     // Apply the new cookie status.
1013                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1014
1015                     // Display a `Snackbar`.
1016                     if (thirdPartyCookiesEnabled) {
1017                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1018                     } else {
1019                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1020                     }
1021
1022                     // Reload the WebView.
1023                     mainWebView.reload();
1024                 } // Else do nothing because SDK < 21.
1025                 return true;
1026
1027             case R.id.toggleDomStorage:
1028                 // Switch the status of domStorageEnabled.
1029                 domStorageEnabled = !domStorageEnabled;
1030
1031                 // Update the menu checkbox.
1032                 menuItem.setChecked(domStorageEnabled);
1033
1034                 // Apply the new DOM Storage status.
1035                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1036
1037                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1038                 updatePrivacyIcons(true);
1039
1040                 // Display a `Snackbar`.
1041                 if (domStorageEnabled) {
1042                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1043                 } else {
1044                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1045                 }
1046
1047                 // Reload the WebView.
1048                 mainWebView.reload();
1049                 return true;
1050
1051             case R.id.toggleSaveFormData:
1052                 // Switch the status of saveFormDataEnabled.
1053                 saveFormDataEnabled = !saveFormDataEnabled;
1054
1055                 // Update the menu checkbox.
1056                 menuItem.setChecked(saveFormDataEnabled);
1057
1058                 // Apply the new form data status.
1059                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1060
1061                 // Display a `Snackbar`.
1062                 if (saveFormDataEnabled) {
1063                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1064                 } else {
1065                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1066                 }
1067
1068                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1069                 updatePrivacyIcons(true);
1070
1071                 // Reload the WebView.
1072                 mainWebView.reload();
1073                 return true;
1074
1075             case R.id.clearCookies:
1076                 if (Build.VERSION.SDK_INT < 21) {
1077                     cookieManager.removeAllCookie();
1078                 } else {
1079                     cookieManager.removeAllCookies(null);
1080                 }
1081                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1082                 return true;
1083
1084             case R.id.clearDomStorage:
1085                 WebStorage webStorage = WebStorage.getInstance();
1086                 webStorage.deleteAllData();
1087                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1088                 return true;
1089
1090             case R.id.clearFormData:
1091                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1092                 mainWebViewDatabase.clearFormData();
1093                 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1094                 return true;
1095
1096             case R.id.fontSizeFiftyPercent:
1097                 mainWebView.getSettings().setTextZoom(50);
1098                 return true;
1099
1100             case R.id.fontSizeSeventyFivePercent:
1101                 mainWebView.getSettings().setTextZoom(75);
1102                 return true;
1103
1104             case R.id.fontSizeOneHundredPercent:
1105                 mainWebView.getSettings().setTextZoom(100);
1106                 return true;
1107
1108             case R.id.fontSizeOneHundredTwentyFivePercent:
1109                 mainWebView.getSettings().setTextZoom(125);
1110                 return true;
1111
1112             case R.id.fontSizeOneHundredFiftyPercent:
1113                 mainWebView.getSettings().setTextZoom(150);
1114                 return true;
1115
1116             case R.id.fontSizeOneHundredSeventyFivePercent:
1117                 mainWebView.getSettings().setTextZoom(175);
1118                 return true;
1119
1120             case R.id.fontSizeTwoHundredPercent:
1121                 mainWebView.getSettings().setTextZoom(200);
1122                 return true;
1123
1124             case R.id.find_on_page:
1125                 // Hide the URL app bar.
1126                 supportAppBar.setVisibility(View.GONE);
1127
1128                 // Show the Find on Page `RelativeLayout`.
1129                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1130
1131                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
1132                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1133                 findOnPageEditText.postDelayed(new Runnable()
1134                 {
1135                     @Override
1136                     public void run()
1137                     {
1138                         // Set the focus on `findOnPageEditText`.
1139                         findOnPageEditText.requestFocus();
1140
1141                         // Display the keyboard.
1142                         inputMethodManager.showSoftInput(findOnPageEditText, 0);
1143                     }
1144                 }, 200);
1145                 return true;
1146
1147             case R.id.share:
1148                 Intent shareIntent = new Intent();
1149                 shareIntent.setAction(Intent.ACTION_SEND);
1150                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1151                 shareIntent.setType("text/plain");
1152                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1153                 return true;
1154
1155             case R.id.addToHomescreen:
1156                 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1157                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1158                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1159
1160                 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1161                 return true;
1162
1163             case R.id.print:
1164                 // Get a `PrintManager` instance.
1165                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1166
1167                 // Convert `mainWebView` to `printDocumentAdapter`.
1168                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1169
1170                 // Print the document.  The print attributes are `null`.
1171                 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1172                 return true;
1173
1174             case R.id.refresh:
1175                 mainWebView.reload();
1176                 return true;
1177
1178             default:
1179                 // Don't consume the event.
1180                 return super.onOptionsItemSelected(menuItem);
1181         }
1182     }
1183
1184     // removeAllCookies is deprecated, but it is required for API < 21.
1185     @SuppressWarnings("deprecation")
1186     @Override
1187     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1188         int menuItemId = menuItem.getItemId();
1189
1190         switch (menuItemId) {
1191             case R.id.home:
1192                 mainWebView.loadUrl(homepage, customHeaders);
1193                 break;
1194
1195             case R.id.back:
1196                 if (mainWebView.canGoBack()) {
1197                     mainWebView.goBack();
1198                 }
1199                 break;
1200
1201             case R.id.forward:
1202                 if (mainWebView.canGoForward()) {
1203                     mainWebView.goForward();
1204                 }
1205                 break;
1206
1207             case R.id.history:
1208                 // Gte the `WebBackForwardList`.
1209                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1210
1211                 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
1212                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1213                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1214                 break;
1215
1216             case R.id.bookmarks:
1217                 // Launch Bookmarks.
1218                 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1219                 startActivity(bookmarksIntent);
1220                 break;
1221
1222             case R.id.downloads:
1223                 // Launch the system Download Manager.
1224                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1225
1226                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1227                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1228
1229                 startActivity(downloadManagerIntent);
1230                 break;
1231
1232             case R.id.settings:
1233                 // Launch `Settings`.
1234                 Intent settingsIntent = new Intent(this, Settings.class);
1235                 startActivity(settingsIntent);
1236                 break;
1237
1238             case R.id.domains:
1239                 // Launch `DomainsList`.
1240                 Intent domainsIntent = new Intent(this, DomainsList.class);
1241                 startActivity(domainsIntent);
1242                 break;
1243
1244             case R.id.guide:
1245                 // Launch `Guide`.
1246                 Intent guideIntent = new Intent(this, Guide.class);
1247                 startActivity(guideIntent);
1248                 break;
1249
1250             case R.id.about:
1251                 // Launch `About`.
1252                 Intent aboutIntent = new Intent(this, About.class);
1253                 startActivity(aboutIntent);
1254                 break;
1255
1256             case R.id.clearAndExit:
1257                 // Clear cookies.  The commands changed slightly in API 21.
1258                 if (Build.VERSION.SDK_INT >= 21) {
1259                     cookieManager.removeAllCookies(null);
1260                 } else {
1261                     cookieManager.removeAllCookie();
1262                 }
1263
1264                 // Clear DOM storage.
1265                 WebStorage domStorage = WebStorage.getInstance();
1266                 domStorage.deleteAllData();
1267
1268                 // Clear form data.
1269                 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1270                 webViewDatabase.clearFormData();
1271
1272                 // Clear cache.  The argument of "true" includes disk files.
1273                 mainWebView.clearCache(true);
1274
1275                 // Clear the back/forward history.
1276                 mainWebView.clearHistory();
1277
1278                 // Clear any SSL certificate preferences.
1279                 mainWebView.clearSslPreferences();
1280
1281                 // Clear `formattedUrlString`.
1282                 formattedUrlString = null;
1283
1284                 // Clear `customHeaders`.
1285                 customHeaders.clear();
1286
1287                 // Detach all views from `mainWebViewRelativeLayout`.
1288                 mainWebViewRelativeLayout.removeAllViews();
1289
1290                 // Destroy the internal state of `mainWebView`.
1291                 mainWebView.destroy();
1292
1293                 // Manually delete the `app_webview` folder, which contains an additional `WebView` cache.  See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1294                 Runtime runtime = Runtime.getRuntime();
1295                 String dataDirString = getApplicationInfo().dataDir;  // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1296                 try {
1297                     runtime.exec("rm -rf " + dataDirString + "/app_webview");
1298                 } catch (IOException e) {
1299                     // Do nothing if the files do not exist.
1300                 }
1301
1302                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1303                 if (Build.VERSION.SDK_INT >= 21) {
1304                     finishAndRemoveTask();
1305                 } else {
1306                     finish();
1307                 }
1308
1309                 // Remove the terminated program from RAM.  The status code is `0`.
1310                 System.exit(0);
1311                 break;
1312
1313             default:
1314                 break;
1315         }
1316
1317         // Close the navigation drawer.
1318         drawerLayout.closeDrawer(GravityCompat.START);
1319         return true;
1320     }
1321
1322     @Override
1323     public void onPostCreate(Bundle savedInstanceState) {
1324         super.onPostCreate(savedInstanceState);
1325
1326         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1327         drawerToggle.syncState();
1328     }
1329
1330     @Override
1331     public void onConfigurationChanged(Configuration newConfig) {
1332         super.onConfigurationChanged(newConfig);
1333
1334         // Reload the ad for the free flavor if we are not in full screen mode.
1335         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1336             // Reload the ad.
1337             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1338
1339             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1340             adView = findViewById(R.id.adView);
1341         }
1342
1343         // `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
1344         // ActivityCompat.invalidateOptionsMenu(this);
1345     }
1346
1347     @Override
1348     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1349         // Store the `HitTestResult`.
1350         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1351
1352         // Create strings.
1353         final String imageUrl;
1354         final String linkUrl;
1355
1356         // Get a handle for the `ClipboardManager`.
1357         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1358
1359         switch (hitTestResult.getType()) {
1360             // `SRC_ANCHOR_TYPE` is a link.
1361             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1362                 // Get the target URL.
1363                 linkUrl = hitTestResult.getExtra();
1364
1365                 // Set the target URL as the title of the `ContextMenu`.
1366                 menu.setHeaderTitle(linkUrl);
1367
1368                 // Add a `Load URL` entry.
1369                 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1370                     @Override
1371                     public boolean onMenuItemClick(MenuItem item) {
1372                         mainWebView.loadUrl(linkUrl, customHeaders);
1373                         return false;
1374                     }
1375                 });
1376
1377                 // Add a `Copy URL` entry.
1378                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1379                     @Override
1380                     public boolean onMenuItemClick(MenuItem item) {
1381                         // Save the link URL in a `ClipData`.
1382                         ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1383
1384                         // Set the `ClipData` as the clipboard's primary clip.
1385                         clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1386                         return false;
1387                     }
1388                 });
1389
1390                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1391                 menu.add(R.string.cancel);
1392                 break;
1393
1394             case WebView.HitTestResult.EMAIL_TYPE:
1395                 // Get the target URL.
1396                 linkUrl = hitTestResult.getExtra();
1397
1398                 // Set the target URL as the title of the `ContextMenu`.
1399                 menu.setHeaderTitle(linkUrl);
1400
1401                 // Add a `Write Email` entry.
1402                 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1403                     @Override
1404                     public boolean onMenuItemClick(MenuItem item) {
1405                         // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1406                         Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1407
1408                         // Parse the url and set it as the data for the `Intent`.
1409                         emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1410
1411                         // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1412                         emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1413
1414                         // Make it so.
1415                         startActivity(emailIntent);
1416                         return false;
1417                     }
1418                 });
1419
1420                 // Add a `Copy Email Address` entry.
1421                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1422                     @Override
1423                     public boolean onMenuItemClick(MenuItem item) {
1424                         // Save the email address in a `ClipData`.
1425                         ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1426
1427                         // Set the `ClipData` as the clipboard's primary clip.
1428                         clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1429                         return false;
1430                     }
1431                 });
1432
1433                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1434                 menu.add(R.string.cancel);
1435                 break;
1436
1437             // `IMAGE_TYPE` is an image.
1438             case WebView.HitTestResult.IMAGE_TYPE:
1439                 // Get the image URL.
1440                 imageUrl = hitTestResult.getExtra();
1441
1442                 // Set the image URL as the title of the `ContextMenu`.
1443                 menu.setHeaderTitle(imageUrl);
1444
1445                 // Add a `View Image` entry.
1446                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1447                     @Override
1448                     public boolean onMenuItemClick(MenuItem item) {
1449                         mainWebView.loadUrl(imageUrl, customHeaders);
1450                         return false;
1451                     }
1452                 });
1453
1454                 // Add a `Download Image` entry.
1455                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1456                     @Override
1457                     public boolean onMenuItemClick(MenuItem item) {
1458                         // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1459                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1460                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1461                         return false;
1462                     }
1463                 });
1464
1465                 // Add a `Copy URL` entry.
1466                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1467                     @Override
1468                     public boolean onMenuItemClick(MenuItem item) {
1469                         // Save the image URL in a `ClipData`.
1470                         ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1471
1472                         // Set the `ClipData` as the clipboard's primary clip.
1473                         clipboardManager.setPrimaryClip(srcImageTypeClipData);
1474                         return false;
1475                     }
1476                 });
1477
1478                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1479                 menu.add(R.string.cancel);
1480                 break;
1481
1482
1483             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1484             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1485                 // Get the image URL.
1486                 imageUrl = hitTestResult.getExtra();
1487
1488                 // Set the image URL as the title of the `ContextMenu`.
1489                 menu.setHeaderTitle(imageUrl);
1490
1491                 // Add a `View Image` entry.
1492                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1493                     @Override
1494                     public boolean onMenuItemClick(MenuItem item) {
1495                         mainWebView.loadUrl(imageUrl, customHeaders);
1496                         return false;
1497                     }
1498                 });
1499
1500                 // Add a `Download Image` entry.
1501                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1502                     @Override
1503                     public boolean onMenuItemClick(MenuItem item) {
1504                         // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1505                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1506                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1507                         return false;
1508                     }
1509                 });
1510
1511                 // Add a `Copy URL` entry.
1512                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1513                     @Override
1514                     public boolean onMenuItemClick(MenuItem item) {
1515                         // Save the image URL in a `ClipData`.
1516                         ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1517
1518                         // Set the `ClipData` as the clipboard's primary clip.
1519                         clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1520                         return false;
1521                     }
1522                 });
1523
1524                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1525                 menu.add(R.string.cancel);
1526                 break;
1527         }
1528     }
1529
1530     @Override
1531     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1532         // Get shortcutNameEditText from the alert dialog.
1533         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1534
1535         // Create the bookmark shortcut based on formattedUrlString.
1536         Intent bookmarkShortcut = new Intent();
1537         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1538         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1539
1540         // Place the bookmark shortcut on the home screen.
1541         Intent placeBookmarkShortcut = new Intent();
1542         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1543         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1544         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1545         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1546         sendBroadcast(placeBookmarkShortcut);
1547     }
1548
1549     @Override
1550     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1551         // Download the image if it has an HTTP or HTTPS URI.
1552         if (imageUrl.startsWith("http")) {
1553             // Get a handle for the system `DOWNLOAD_SERVICE`.
1554             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1555
1556             // Parse `imageUrl`.
1557             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1558
1559             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
1560             if (firstPartyCookiesEnabled) {
1561                 // Get the cookies for `imageUrl`.
1562                 String cookies = cookieManager.getCookie(imageUrl);
1563
1564                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1565                 downloadRequest.addRequestHeader("Cookie", cookies);
1566             }
1567
1568             // Get the file name from `dialogFragment`.
1569             EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1570             String imageName = downloadImageNameEditText.getText().toString();
1571
1572             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1573             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1574                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1575             } else { // Only set the title using `imageName`.
1576                 downloadRequest.setTitle(imageName);
1577             }
1578
1579             // Allow `MediaScanner` to index the download if it is a media file.
1580             downloadRequest.allowScanningByMediaScanner();
1581
1582             // Add the URL as the description for the download.
1583             downloadRequest.setDescription(imageUrl);
1584
1585             // Show the download notification after the download is completed.
1586             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1587
1588             // Initiate the download.
1589             downloadManager.enqueue(downloadRequest);
1590         } else {  // The image is not an HTTP or HTTPS URI.
1591             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1592         }
1593     }
1594
1595     @Override
1596     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1597         // Download the file if it has an HTTP or HTTPS URI.
1598         if (downloadUrl.startsWith("http")) {
1599
1600             // Get a handle for the system `DOWNLOAD_SERVICE`.
1601             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1602
1603             // Parse `downloadUrl`.
1604             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1605
1606             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
1607             if (firstPartyCookiesEnabled) {
1608                 // Get the cookies for `downloadUrl`.
1609                 String cookies = cookieManager.getCookie(downloadUrl);
1610
1611                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1612                 downloadRequest.addRequestHeader("Cookie", cookies);
1613             }
1614
1615             // Get the file name from `dialogFragment`.
1616             EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1617             String fileName = downloadFileNameEditText.getText().toString();
1618
1619             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1620             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1621                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1622             } else { // Only set the title using `fileName`.
1623                 downloadRequest.setTitle(fileName);
1624             }
1625
1626             // Allow `MediaScanner` to index the download if it is a media file.
1627             downloadRequest.allowScanningByMediaScanner();
1628
1629             // Add the URL as the description for the download.
1630             downloadRequest.setDescription(downloadUrl);
1631
1632             // Show the download notification after the download is completed.
1633             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1634
1635             // Initiate the download.
1636             downloadManager.enqueue(downloadRequest);
1637         } else {  // The download is not an HTTP or HTTPS URI.
1638             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1639         }
1640     }
1641
1642     public void viewSslCertificate(View view) {
1643         // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1644         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1645         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1646     }
1647
1648     @Override
1649     public void onSslErrorCancel() {
1650         sslErrorHandler.cancel();
1651     }
1652
1653     @Override
1654     public void onSslErrorProceed() {
1655         sslErrorHandler.proceed();
1656     }
1657
1658     @Override
1659     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1660         // Load the history entry.
1661         mainWebView.goBackOrForward(moveBackOrForwardSteps);
1662     }
1663
1664     @Override
1665     public void onClearHistory() {
1666         // Clear the history.
1667         mainWebView.clearHistory();
1668     }
1669
1670     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1671     @Override
1672     public void onBackPressed() {
1673         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1674         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1675             drawerLayout.closeDrawer(GravityCompat.START);
1676         } else {
1677             // Load the previous URL if available.
1678             if (mainWebView.canGoBack()) {
1679                 mainWebView.goBack();
1680             } else {
1681                 // Pass `onBackPressed()` to the system.
1682                 super.onBackPressed();
1683             }
1684         }
1685     }
1686
1687     @Override
1688     public void onPause() {
1689         // Pause `mainWebView`.
1690         mainWebView.onPause();
1691
1692         // Stop all JavaScript.
1693         mainWebView.pauseTimers();
1694
1695         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1696         if (BuildConfig.FLAVOR.contentEquals("free")) {
1697             BannerAd.pauseAd(adView);
1698         }
1699
1700         super.onPause();
1701     }
1702
1703     @Override
1704     public void onResume() {
1705         super.onResume();
1706
1707         // Resume JavaScript (if enabled).
1708         mainWebView.resumeTimers();
1709
1710         // Resume `mainWebView`.
1711         mainWebView.onResume();
1712
1713         // Resume the adView for the free flavor.
1714         if (BuildConfig.FLAVOR.contentEquals("free")) {
1715             BannerAd.resumeAd(adView);
1716         }
1717     }
1718
1719     @Override
1720     public void onRestart() {
1721         super.onRestart();
1722
1723         // Apply the settings from shared preferences, which might have been changed in `Settings`.
1724         applySettings();
1725
1726         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1727         updatePrivacyIcons(true);
1728
1729     }
1730
1731     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1732         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
1733         String unformattedUrlString = urlTextBox.getText().toString().trim();
1734
1735         URL unformattedUrl = null;
1736         Uri.Builder formattedUri = new Uri.Builder();
1737
1738         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
1739         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1740             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
1741             if (!unformattedUrlString.startsWith("http")) {
1742                 unformattedUrlString = "http://" + unformattedUrlString;
1743             }
1744
1745             // 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.
1746             try {
1747                 unformattedUrl = new URL(unformattedUrlString);
1748             } catch (MalformedURLException e) {
1749                 e.printStackTrace();
1750             }
1751
1752             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1753             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1754             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1755             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1756             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1757             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1758
1759             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1760             formattedUrlString = formattedUri.build().toString();
1761         } else {
1762             // Sanitize the search input and convert it to a DuckDuckGo search.
1763             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1764
1765             // Use the correct search URL.
1766             if (javaScriptEnabled) {  // JavaScript is enabled.
1767                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1768             } else { // JavaScript is disabled.
1769                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1770             }
1771         }
1772
1773         mainWebView.loadUrl(formattedUrlString, customHeaders);
1774
1775         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
1776         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1777     }
1778
1779     public void findPreviousOnPage(View view) {
1780         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
1781         mainWebView.findNext(false);
1782     }
1783
1784     public void findNextOnPage(View view) {
1785         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1786         mainWebView.findNext(true);
1787     }
1788
1789     public void closeFindOnPage(View view) {
1790         // Delete the contents of `find_on_page_edittext`.
1791         findOnPageEditText.setText(null);
1792
1793         // Clear the highlighted phrases.
1794         mainWebView.clearMatches();
1795
1796         // Hide the Find on Page `RelativeLayout`.
1797         findOnPageLinearLayout.setVisibility(View.GONE);
1798
1799         // Show the URL app bar.
1800         supportAppBar.setVisibility(View.VISIBLE);
1801
1802         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
1803         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1804     }
1805
1806     private void applySettings() {
1807         // Get the shared preference values.  `this` references the current context.
1808         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1809
1810         // Store the values from `sharedPreferences` in variables.
1811         String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1812         String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1813         String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1814         String javaScriptDisabledSearchCustomURLString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1815         String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1816         String javaScriptEnabledSearchCustomURLString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1817         String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1818         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
1819         String torJavaScriptDisabledSearchString = sharedPreferences.getString("tor_javascript_disabled_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
1820         String torJavaScriptDisabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_disabled_search_custom_url", "");
1821         String torJavaScriptEnabledSearchString = sharedPreferences.getString("tor_javascript_enabled_search", "https://3g2upl4pq6kufc4m.onion/?q=");
1822         String torJavaScriptEnabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_enabled_search_custom_url", "");
1823         String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1824         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1825         adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
1826         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
1827         proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1828         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1829         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1830         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1831
1832         // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1833         if (javaScriptEnabled == null) {  // If `javaScriptEnabled` is null the program is just starting.
1834             // Get the values from `sharedPreferences`.
1835             javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1836             firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1837             thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1838             domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1839             saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1840
1841             // Apply the default settings.
1842             mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1843             cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1844             mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1845             mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1846             mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1847
1848             // Set third-party cookies status if API >= 21.
1849             if (Build.VERSION.SDK_INT >= 21) {
1850                 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1851             }
1852         }
1853
1854         // Set the homepage, search, and proxy options.
1855         if (proxyThroughOrbot) {  // Set the Tor options.
1856             // Set `torHomepageString` as `homepage`.
1857             homepage = torHomepageString;
1858
1859             // If formattedUrlString is null assign the homepage to it.
1860             if (formattedUrlString == null) {
1861                 formattedUrlString = homepage;
1862             }
1863
1864             // Set JavaScript disabled search.
1865             if (torJavaScriptDisabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1866                 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchCustomURLString;
1867             } else {  // Use the string from the pre-built list.
1868                 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchString;
1869             }
1870
1871             // Set JavaScript enabled search.
1872             if (torJavaScriptEnabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1873                 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchCustomURLString;
1874             } else {  // Use the string from the pre-built list.
1875                 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchString;
1876             }
1877
1878             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
1879             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1880
1881             // Display a message to the user if we are waiting on Orbot.
1882             if (!orbotStatus.equals("ON")) {
1883                 // Save `formattedUrlString` in `pendingUrl`.
1884                 pendingUrl = formattedUrlString;
1885
1886                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1887                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1888             }
1889         } else {  // Set the non-Tor options.
1890             // Set `homepageString` as `homepage`.
1891             homepage = homepageString;
1892
1893             // If formattedUrlString is null assign the homepage to it.
1894             if (formattedUrlString == null) {
1895                 formattedUrlString = homepage;
1896             }
1897
1898             // Set JavaScript disabled search.
1899             if (javaScriptDisabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1900                 javaScriptDisabledSearchURL = javaScriptDisabledSearchCustomURLString;
1901             } else {  // Use the string from the pre-built list.
1902                 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1903             }
1904
1905             // Set JavaScript enabled search.
1906             if (javaScriptEnabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1907                 javaScriptEnabledSearchURL = javaScriptEnabledSearchCustomURLString;
1908             } else {  // Use the string from the pre-built list.
1909                 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1910             }
1911
1912             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
1913             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1914
1915             // Reset `pendingUrl` if we are currently waiting for Orbot to connect.
1916             if (!pendingUrl.isEmpty()) {
1917                 formattedUrlString = pendingUrl;
1918                 pendingUrl = "";
1919             }
1920         }
1921
1922         // Set swipe to refresh.
1923         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1924
1925         // Set the user agent initial status.
1926         switch (userAgentString) {
1927             case "Default user agent":
1928                 // Set the user agent to `""`, which uses the default value.
1929                 mainWebView.getSettings().setUserAgentString("");
1930                 break;
1931
1932             case "Custom user agent":
1933                 // Set the custom user agent.
1934                 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1935                 break;
1936
1937             default:
1938                 // Use the selected user agent.
1939                 mainWebView.getSettings().setUserAgentString(userAgentString);
1940                 break;
1941         }
1942
1943         // Set Do Not Track status.
1944         if (doNotTrackEnabled) {
1945             customHeaders.put("DNT", "1");
1946         } else {
1947             customHeaders.remove("DNT");
1948         }
1949
1950         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1951         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
1952             if (hideSystemBarsOnFullscreen) {  // Hide everything.
1953                 // Remove the translucent navigation setting if it is currently flagged.
1954                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1955
1956                 // Remove the translucent status bar overlay.
1957                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1958
1959                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1960                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1961
1962                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1963                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1964                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1965                  */
1966                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1967             } else {  // Hide everything except the status and navigation bars.
1968                 // Add the translucent status flag if it is unset.
1969                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1970
1971                 if (translucentNavigationBarOnFullscreen) {
1972                     // Set the navigation bar to be translucent.
1973                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1974                 } else {
1975                     // Set the navigation bar to be black.
1976                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1977                 }
1978             }
1979         } else {  // Switch to normal viewing mode.
1980             // Reset `inFullScreenBrowsingMode` to `false`.
1981             inFullScreenBrowsingMode = false;
1982
1983             // Show the `appBar`.
1984             appBar.show();
1985
1986             // Show the `BannerAd` in the free flavor.
1987             if (BuildConfig.FLAVOR.contentEquals("free")) {
1988                 // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
1989                 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1990
1991                 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1992                 adView = findViewById(R.id.adView);
1993             }
1994
1995             // Remove the translucent navigation bar flag if it is set.
1996             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1997
1998             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1999             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2000
2001             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2002             rootCoordinatorLayout.setSystemUiVisibility(0);
2003
2004             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2005             rootCoordinatorLayout.setFitsSystemWindows(true);
2006         }
2007     }
2008
2009     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2010         // Get handles for the icons.
2011         MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
2012         MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
2013         MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
2014         MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
2015
2016         // Update `privacyIcon`.
2017         if (javaScriptEnabled) {  // JavaScript is enabled.
2018             privacyIcon.setIcon(R.drawable.javascript_enabled);
2019         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
2020             privacyIcon.setIcon(R.drawable.warning);
2021         } else {  // All the dangerous features are disabled.
2022             privacyIcon.setIcon(R.drawable.privacy_mode);
2023         }
2024
2025         // Update `firstPartyCookiesIcon`.
2026         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2027             firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
2028         } else {  // First-party cookies are disabled.
2029             firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
2030         }
2031
2032         // Update `domStorageIcon`.
2033         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
2034             domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
2035         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
2036             domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2037         } else {  // JavaScript is disabled, so DOM storage is ghosted.
2038             domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2039         }
2040
2041         // Update `formDataIcon`.
2042         if (saveFormDataEnabled) {  // Form data is enabled.
2043             formDataIcon.setIcon(R.drawable.form_data_enabled);
2044         } else {  // Form data is disabled.
2045             formDataIcon.setIcon(R.drawable.form_data_disabled);
2046         }
2047
2048         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.  `this` references the current activity.
2049         if (runInvalidateOptionsMenu) {
2050             ActivityCompat.invalidateOptionsMenu(this);
2051         }
2052     }
2053 }