]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Add controls for `Clear and Exit`. Implements https://redmine.stoutner.com/issues...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.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.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.TextWatcher;
63 import android.util.Patterns;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.WindowManager;
72 import android.view.inputmethod.InputMethodManager;
73 import android.webkit.CookieManager;
74 import android.webkit.DownloadListener;
75 import android.webkit.SslErrorHandler;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ProgressBar;
88 import android.widget.RelativeLayout;
89 import android.widget.TextView;
90
91 import com.stoutner.privacybrowser.BannerAd;
92 import com.stoutner.privacybrowser.BuildConfig;
93 import com.stoutner.privacybrowser.R;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
95 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
96 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
98 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
99 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
100 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
101 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
102
103 import java.io.BufferedReader;
104 import java.io.ByteArrayInputStream;
105 import java.io.IOException;
106 import java.io.InputStreamReader;
107 import java.io.UnsupportedEncodingException;
108 import java.net.MalformedURLException;
109 import java.net.URL;
110 import java.net.URLDecoder;
111 import java.net.URLEncoder;
112 import java.util.HashMap;
113 import java.util.HashSet;
114 import java.util.Map;
115 import java.util.Set;
116
117 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
118 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
119         SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
120
121     // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
122     public static ActionBar appBar;
123
124     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
125     // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
126     public static Bitmap favoriteIconBitmap;
127
128     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
129     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
130     public static String formattedUrlString;
131
132     // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
133     public static SslCertificate sslCertificate;
134
135     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`.
136     public static String orbotStatus;
137
138     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
139     public static String webViewTitle;
140
141     // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`.  It is also used in `applyAppSettings` and `applyDomainSettings()`.
142     public static boolean displayWebpageImagesBoolean;
143
144
145     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
146     private boolean navigatingHistory;
147
148     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
149     private Bitmap favoriteIconDefaultBitmap;
150
151     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
152     private DrawerLayout drawerLayout;
153
154     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
155     private CoordinatorLayout rootCoordinatorLayout;
156
157     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
158     // and `setDisplayWebpageImages()`.
159     private WebView mainWebView;
160
161     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
162     private FrameLayout fullScreenVideoFrameLayout;
163
164     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
165     private SwipeRefreshLayout swipeRefreshLayout;
166
167     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
168     private RelativeLayout urlAppBarRelativeLayout;
169
170     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
171     private ImageView favoriteIconImageView;
172
173     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
174     private CookieManager cookieManager;
175
176     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
177     private final Map<String, String> customHeaders = new HashMap<>();
178
179     // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
180     // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
181     private Boolean javaScriptEnabled;
182
183     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
184     private boolean firstPartyCookiesEnabled;
185
186     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
187     private boolean thirdPartyCookiesEnabled;
188
189     // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
190     private boolean domStorageEnabled;
191
192     // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
193     private boolean saveFormDataEnabled;
194
195     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
196     private boolean swipeToRefreshEnabled;
197
198     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
199     private String homepage;
200
201     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
202     private String searchURL;
203
204     // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
205     private boolean adBlockerEnabled;
206
207     // `privacyBrowserRuntime` is used in `onCreate()` and `applyAppSettings()`.
208     private Runtime privacyBrowserRuntime;
209
210     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
211     private boolean incognitoModeEnabled;
212
213     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
214     private boolean fullScreenBrowsingModeEnabled;
215
216     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
217     private boolean inFullScreenBrowsingMode;
218
219     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
220     private boolean hideSystemBarsOnFullscreen;
221
222     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
223     private boolean translucentNavigationBarOnFullscreen;
224
225     // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
226     private String currentDomainName;
227
228     // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
229     private boolean waitingForOrbot;
230
231     // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
232     private boolean domainSettingsApplied;
233
234     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
235     private int displayWebpageImagesInt;
236
237     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
238     private boolean onTheFlyDisplayImagesSet;
239
240     // `loadingNewIntentBoolean` is used in `onNewIntent()` and `onRestart()`.
241     private boolean loadingNewIntentBoolean;
242
243     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
244     private String waitingForOrbotHTMLString;
245
246     // `privateDataDirectoryString` is used in `onCreate()` and `onNavigationItemSelected()`.
247     private String privateDataDirectoryString;
248
249     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
250     private LinearLayout findOnPageLinearLayout;
251
252     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
253     private EditText findOnPageEditText;
254
255     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
256     private Menu mainMenu;
257
258     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
259     private ActionBarDrawerToggle drawerToggle;
260
261     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
262     private Toolbar supportAppBar;
263
264     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `loadUrl()`.
265     private EditText urlTextBox;
266
267     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
268     private View adView;
269
270     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
271     private SslErrorHandler sslErrorHandler;
272
273     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
274     private InputMethodManager inputMethodManager;
275
276     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
277     private RelativeLayout mainWebViewRelativeLayout;
278
279     @Override
280     // 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.
281     @SuppressLint("SetJavaScriptEnabled")
282     protected void onCreate(Bundle savedInstanceState) {
283         super.onCreate(savedInstanceState);
284         setContentView(R.layout.main_drawerlayout);
285
286         // Get a handle for `inputMethodManager`.
287         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
288
289         // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
290         supportAppBar = (Toolbar) findViewById(R.id.app_bar);
291         setSupportActionBar(supportAppBar);
292         appBar = getSupportActionBar();
293
294         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
295         assert appBar != null;
296
297         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
298         appBar.setCustomView(R.layout.url_app_bar);
299         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
300
301         // Set the "go" button on the keyboard to load the URL in urlTextBox.
302         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
303         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
304             @Override
305             public boolean onKey(View v, int keyCode, KeyEvent event) {
306                 // If the event is a key-down event on the `enter` button, load the URL.
307                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
308                     // Load the URL into the mainWebView and consume the event.
309                     try {
310                         loadUrlFromTextBox();
311                     } catch (UnsupportedEncodingException e) {
312                         e.printStackTrace();
313                     }
314                     // If the enter key was pressed, consume the event.
315                     return true;
316                 } else {
317                     // If any other key was pressed, do not consume the event.
318                     return false;
319                 }
320             }
321         });
322
323         // Set `waitingForOrbotHTMLString`.
324         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
325
326         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
327         currentDomainName = "";
328         orbotStatus = "unknown";
329         waitingForOrbot = false;
330
331         // Create an Orbot status `BroadcastReceiver`.
332         BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
333             @Override
334             public void onReceive(Context context, Intent intent) {
335                 // Store the content of the status message in `orbotStatus`.
336                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
337
338                 // If we are waiting on Orbot, load the website now that Orbot is connected.
339                 if (orbotStatus.equals("ON") && waitingForOrbot) {
340                     // Reset `waitingForOrbot`.
341                     waitingForOrbot = false;
342
343                     // Load `formattedUrlString
344                     loadUrl(formattedUrlString);
345                 }
346             }
347         };
348
349         // Register `orbotStatusBroadcastReceiver` on `this` context.
350         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
351
352         // Get handles for views that need to be accessed.
353         drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
354         rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
355         mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
356         mainWebView = (WebView) findViewById(R.id.main_webview);
357         findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
358         findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
359         fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
360         urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
361         favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
362
363         // Create a double-tap listener to toggle full-screen mode.
364         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
365             // Override `onDoubleTap()`.  All other events are handled using the default settings.
366             @Override
367             public boolean onDoubleTap(MotionEvent event) {
368                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
369                     // Toggle `inFullScreenBrowsingMode`.
370                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
371
372                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
373                         // Hide the `appBar`.
374                         appBar.hide();
375
376                         // Hide the `BannerAd` in the free flavor.
377                         if (BuildConfig.FLAVOR.contentEquals("free")) {
378                             BannerAd.hideAd(adView);
379                         }
380
381                         // Modify the system bars.
382                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
383                             // Remove the translucent overlays.
384                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
385
386                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
387                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
388
389                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
390                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
391                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
392                              */
393                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
394
395                             // Set `rootCoordinatorLayout` to fill the whole screen.
396                             rootCoordinatorLayout.setFitsSystemWindows(false);
397                         } else {  // Hide everything except the status and navigation bars.
398                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
399                             rootCoordinatorLayout.setFitsSystemWindows(false);
400
401                             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.
402                                 // Set the navigation bar to be translucent.
403                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
404                             }
405                         }
406                     } else {  // Switch to normal viewing mode.
407                         // Show the `appBar`.
408                         appBar.show();
409
410                         // Show the `BannerAd` in the free flavor.
411                         if (BuildConfig.FLAVOR.contentEquals("free")) {
412                             // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
413                             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
414
415                             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
416                             adView = findViewById(R.id.adview);
417                         }
418
419                         // Remove the translucent navigation bar flag if it is set.
420                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
421
422                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
423                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
424
425                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
426                         rootCoordinatorLayout.setSystemUiVisibility(0);
427
428                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
429                         rootCoordinatorLayout.setFitsSystemWindows(true);
430                     }
431
432                     // Consume the double-tap.
433                     return true;
434                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
435                     return false;
436                 }
437             }
438         });
439
440         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
441         mainWebView.setOnTouchListener(new View.OnTouchListener() {
442             @Override
443             public boolean onTouch(View v, MotionEvent event) {
444                 // Send the `event` to `gestureDetector`.
445                 return gestureDetector.onTouchEvent(event);
446             }
447         });
448
449         // Update `findOnPageCountTextView`.
450         mainWebView.setFindListener(new WebView.FindListener() {
451             // Get a handle for `findOnPageCountTextView`.
452             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
453
454             @Override
455             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
456                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
457                     // Set `findOnPageCountTextView` to `0/0`.
458                     findOnPageCountTextView.setText(R.string.zero_of_zero);
459                 } else if (isDoneCounting) {  // There are matches.
460                     // `activeMatchOrdinal` is zero-based.
461                     int activeMatch = activeMatchOrdinal + 1;
462
463                     // Set `findOnPageCountTextView`.
464                     findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
465                 }
466             }
467         });
468
469         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
470         findOnPageEditText.addTextChangedListener(new TextWatcher() {
471             @Override
472             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
473                 // Do nothing.
474             }
475
476             @Override
477             public void onTextChanged(CharSequence s, int start, int before, int count) {
478                 // Do nothing.
479             }
480
481             @Override
482             public void afterTextChanged(Editable s) {
483                 // Search for the text in `mainWebView`.
484                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
485             }
486         });
487
488         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
489         findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
490             @Override
491             public boolean onKey(View v, int keyCode, KeyEvent event) {
492                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
493                     // Hide the soft keyboard.  `0` indicates no additional flags.
494                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
495
496                     // Consume the event.
497                     return true;
498                 } else {  // A different key was pressed.
499                     // Do not consume the event.
500                     return false;
501                 }
502             }
503         });
504
505         // Implement swipe to refresh
506         swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
507         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
508         swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
509             @Override
510             public void onRefresh() {
511                 mainWebView.reload();
512             }
513         });
514
515         // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
516         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
517
518         // Listen for touches on the navigation menu.
519         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
520         navigationView.setNavigationItemSelectedListener(this);
521
522         // 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.
523         final Menu navigationMenu = navigationView.getMenu();
524         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
525         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
526         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
527
528         // The `DrawerListener` allows us to update the Navigation Menu.
529         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
530             @Override
531             public void onDrawerSlide(View drawerView, float slideOffset) {
532             }
533
534             @Override
535             public void onDrawerOpened(View drawerView) {
536             }
537
538             @Override
539             public void onDrawerClosed(View drawerView) {
540             }
541
542             @Override
543             public void onDrawerStateChanged(int newState) {
544                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // The drawer is opening or closing.
545                     // Update the `Back`, `Forward`, and `History` menu items.
546                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
547                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
548                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
549
550                     // Hide the keyboard so we can see the navigation menu.  `0` indicates no additional flags.
551                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
552                 }
553             }
554         });
555
556         // drawerToggle creates the hamburger icon at the start of the AppBar.
557         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
558
559         // Initialize `adServerSet`.
560         final Set<String> adServersSet = new HashSet<>();
561
562         // Load the list of ad servers into memory.
563         try {
564             // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
565             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
566
567             // Create a string for storing each ad server.
568             String adServer;
569
570             // Populate `adServersSet`.
571             while ((adServer = bufferedReader.readLine()) != null) {
572                 adServersSet.add(adServer);
573             }
574
575             // Close `bufferedReader`.
576             bufferedReader.close();
577         } catch (IOException ioException) {
578             // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
579         }
580
581         mainWebView.setWebViewClient(new WebViewClient() {
582             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
583             // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
584             @SuppressWarnings("deprecation")
585             @Override
586             public boolean shouldOverrideUrlLoading(WebView view, String url) {
587                 if (url.startsWith("mailto:")) {  // Load the URL in an external email program because it begins with `mailto:`.
588                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
589                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
590
591                     // Parse the url and set it as the data for the `Intent`.
592                     emailIntent.setData(Uri.parse(url));
593
594                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
595                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
596
597                     // Make it so.
598                     startActivity(emailIntent);
599
600                     // Returning `true` indicates the application is handling the URL.
601                     return true;
602                 } else {  // Load the URL in Privacy Browser.
603                     // Apply the domain settings for the new URL.
604                     applyDomainSettings(url);
605
606                     // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
607                     return false;
608                 }
609             }
610
611             // Block ads.  We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
612             @SuppressWarnings("deprecation")
613             @Override
614             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
615                 if (adBlockerEnabled) {  // Block ads.
616                     // Extract the host from `url`.
617                     Uri requestUri = Uri.parse(url);
618                     String requestHost = requestUri.getHost();
619
620                     // Initialize a variable to track if this is an ad server.
621                     boolean requestHostIsAdServer = false;
622
623                     // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
624                     if (requestHost != null) {
625                         while (requestHost.contains(".") && !requestHostIsAdServer) {  // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
626                             if (adServersSet.contains(requestHost)) {
627                                 requestHostIsAdServer = true;
628                             }
629
630                             // Strip out the lowest subdomain of `requestHost`.
631                             requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
632                         }
633                     }
634
635                     if (requestHostIsAdServer) {  // It is an ad server.
636                         // Return an empty `WebResourceResponse`.
637                         return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
638                     } else {  // It is not an ad server.
639                         // `return null` loads the requested resource.
640                         return null;
641                     }
642                 } else {  // Ad blocking is disabled.
643                     // `return null` loads the requested resource.
644                     return null;
645                 }
646             }
647
648             // Update the URL in urlTextBox when the page starts to load.
649             @Override
650             public void onPageStarted(WebView view, String url, Bitmap favicon) {
651                 // Reset `webViewTitle`
652                 webViewTitle = getString(R.string.no_title);
653
654                 // Check to see if we are waiting on Orbot.
655                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
656                     // 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.
657                     formattedUrlString = url;
658
659                     // Display the loading URL is the URL text box.
660                     urlTextBox.setText(url);
661
662                     // Apply any custom domain settings if the URL was loaded by navigating history.
663                     if (navigatingHistory) {
664                         applyDomainSettings(url);
665                     }
666                 }
667             }
668
669             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
670             @Override
671             public void onPageFinished(WebView view, String url) {
672                 // Clear the cache and history if Incognito Mode is enabled.
673                 if (incognitoModeEnabled) {
674                     // Clear the cache.  `true` includes disk files.
675                     mainWebView.clearCache(true);
676
677                     // Clear the back/forward history.
678                     mainWebView.clearHistory();
679
680                     // Manually delete cache folders.
681                     try {
682                         // Delete the main `cache` folder.
683                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
684
685                         // 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`.
686                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
687                     } catch (IOException e) {
688                         // Do nothing if an error is thrown.
689                     }
690                 }
691
692                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
693                 if (!waitingForOrbot) {
694                     // Check to see if `WebView` has set `url` to be `about:blank`.
695                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
696                         // Set `formattedUrlString` to `""`.
697                         formattedUrlString = "";
698
699                         // Update `urlTextBox`.
700                         urlTextBox.setText(formattedUrlString);
701
702                         // Request focus for `urlTextBox`.
703                         urlTextBox.requestFocus();
704
705                         // Display the keyboard.
706                         inputMethodManager.showSoftInput(urlTextBox, 0);
707
708                         // Apply the domain settings.
709                         applyDomainSettings(formattedUrlString);
710                     } else {  // `WebView` has loaded a webpage.
711                         // Set `formattedUrlString`.
712                         formattedUrlString = url;
713
714                         // Only update `urlTextBox` if the user is not typing in it.
715                         if (!urlTextBox.hasFocus()) {
716                             urlTextBox.setText(formattedUrlString);
717                         }
718                     }
719
720                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
721                     sslCertificate = mainWebView.getCertificate();
722                 }
723             }
724
725             // Handle SSL Certificate errors.
726             @Override
727             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
728                 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
729                 sslErrorHandler = handler;
730
731                 // Display the SSL error `AlertDialog`.
732                 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
733                 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
734             }
735         });
736
737         // Get a handle for the progress bar.
738         final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
739
740         mainWebView.setWebChromeClient(new WebChromeClient() {
741             // Update the progress bar when a page is loading.
742             @Override
743             public void onProgressChanged(WebView view, int progress) {
744                 progressBar.setProgress(progress);
745                 if (progress < 100) {
746                     progressBar.setVisibility(View.VISIBLE);
747                 } else {
748                     progressBar.setVisibility(View.GONE);
749
750                     //Stop the `SwipeToRefresh` indicator if it is running
751                     swipeRefreshLayout.setRefreshing(false);
752                 }
753             }
754
755             // Set the favorite icon when it changes.
756             @Override
757             public void onReceivedIcon(WebView view, Bitmap icon) {
758                 // Only update the favorite icon if the website has finished loading.
759                 if (progressBar.getVisibility() == View.GONE) {
760                     // Save a copy of the favorite icon.
761                     favoriteIconBitmap = icon;
762
763                     // Place the favorite icon in the appBar.
764                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
765                 }
766             }
767
768             // Save a copy of the title when it changes.
769             @Override
770             public void onReceivedTitle(WebView view, String title) {
771                 // Save a copy of the title.
772                 webViewTitle = title;
773             }
774
775             // Enter full screen video
776             @Override
777             public void onShowCustomView(View view, CustomViewCallback callback) {
778                 // Pause the ad if this is the free flavor.
779                 if (BuildConfig.FLAVOR.contentEquals("free")) {
780                     BannerAd.pauseAd(adView);
781                 }
782
783                 // Remove the translucent overlays.
784                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
785
786                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
787                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
788
789                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
790                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
791                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
792                  */
793                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
794
795                 // Set `rootCoordinatorLayout` to fill the entire screen.
796                 rootCoordinatorLayout.setFitsSystemWindows(false);
797
798                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
799                 fullScreenVideoFrameLayout.addView(view);
800                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
801             }
802
803             // Exit full screen video
804             public void onHideCustomView() {
805                 // Hide `fullScreenVideoFrameLayout`.
806                 fullScreenVideoFrameLayout.removeAllViews();
807                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
808
809                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
810                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
811
812                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
813                 rootCoordinatorLayout.setFitsSystemWindows(true);
814
815                 // Show the ad if this is the free flavor.
816                 if (BuildConfig.FLAVOR.contentEquals("free")) {
817                     // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
818                     BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
819
820                     // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
821                     adView = findViewById(R.id.adview);
822                 }
823             }
824         });
825
826         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
827         registerForContextMenu(mainWebView);
828
829         // Allow the downloading of files.
830         mainWebView.setDownloadListener(new DownloadListener() {
831             @Override
832             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
833                 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
834                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
835                 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
836             }
837         });
838
839         // Allow pinch to zoom.
840         mainWebView.getSettings().setBuiltInZoomControls(true);
841
842         // Hide zoom controls.
843         mainWebView.getSettings().setDisplayZoomControls(false);
844
845         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
846         mainWebView.getSettings().setUseWideViewPort(true);
847
848         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
849         mainWebView.getSettings().setLoadWithOverviewMode(true);
850
851         // Initialize cookieManager.
852         cookieManager = CookieManager.getInstance();
853
854         // 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).
855         customHeaders.put("X-Requested-With", "");
856
857         // 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.
858         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
859
860         // Get the intent that started the app.
861         final Intent launchingIntent = getIntent();
862
863         // Extract the launching intent data as `launchingIntentUriData`.
864         final Uri launchingIntentUriData = launchingIntent.getData();
865
866         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
867         if (launchingIntentUriData != null) {
868             formattedUrlString = launchingIntentUriData.toString();
869         }
870
871         // Get a handle for the `Runtime`.
872         privacyBrowserRuntime = Runtime.getRuntime();
873
874         // Store the application's private data directory.
875         privateDataDirectoryString = 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`.
876
877         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
878         inFullScreenBrowsingMode = false;
879
880         // Initialize AdView for the free flavor.
881         adView = findViewById(R.id.adview);
882
883         // Initialize the privacy settings variables.
884         javaScriptEnabled = false;
885         firstPartyCookiesEnabled = false;
886         thirdPartyCookiesEnabled = false;
887         domStorageEnabled = false;
888         saveFormDataEnabled = false;
889
890         // Initialize `webViewTitle`.
891         webViewTitle = getString(R.string.no_title);
892
893         // Initialize `favoriteIconBitmap`.  We have to use `ContextCompat` until API >= 21.
894         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
895         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
896         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
897
898         // If the favorite icon is null, load the default.
899         if (favoriteIconBitmap == null) {
900             favoriteIconBitmap = favoriteIconDefaultBitmap;
901         }
902
903         // Apply the app settings from the shared preferences.
904         applyAppSettings();
905
906         // Load `formattedUrlString` if we are not waiting for Orbot to connect.
907         if (!waitingForOrbot) {
908             loadUrl(formattedUrlString);
909         }
910     }
911
912     @Override
913     protected void onNewIntent(Intent intent) {
914         // Set `loadingNewIntentBoolean`.
915         loadingNewIntentBoolean = true;
916
917         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
918         setIntent(intent);
919
920         if (intent.getData() != null) {
921             // Get the intent data and convert it to a string.
922             final Uri intentUriData = intent.getData();
923             formattedUrlString = intentUriData.toString();
924         }
925
926         // Close the navigation drawer if it is open.
927         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
928             drawerLayout.closeDrawer(GravityCompat.START);
929         }
930
931         // Load the website.
932         loadUrl(formattedUrlString);
933
934         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
935         mainWebView.requestFocus();
936     }
937
938     @Override
939     public void onRestart() {
940         super.onRestart();
941
942         // Apply the app settings, which may have been changed in `SettingsActivity`.
943         applyAppSettings();
944
945         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
946         updatePrivacyIcons(true);
947
948         // Set the display webpage images mode.
949         setDisplayWebpageImages();
950
951         // Only reload `mainWebView` if not loading a new intent and not waiting for Orbot.
952         if (!loadingNewIntentBoolean && !waitingForOrbot) {
953             // Reload the webpage to remove images if `setDisplayWebpageImages` has turned them off.
954             mainWebView.reload();
955         } else if (loadingNewIntentBoolean) {  // Reset `loadingNewIntentBoolean` if this run comes from a new intent.
956             loadingNewIntentBoolean = false;
957         }
958     }
959
960     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
961     @Override
962     public void onResume() {
963         super.onResume();
964
965         // Resume JavaScript (if enabled).
966         mainWebView.resumeTimers();
967
968         // Resume `mainWebView`.
969         mainWebView.onResume();
970
971         // Resume the adView for the free flavor.
972         if (BuildConfig.FLAVOR.contentEquals("free")) {
973             BannerAd.resumeAd(adView);
974         }
975     }
976
977     @Override
978     public void onPause() {
979         // Pause `mainWebView`.
980         mainWebView.onPause();
981
982         // Stop all JavaScript.
983         mainWebView.pauseTimers();
984
985         // Pause the adView or it will continue to consume resources in the background on the free flavor.
986         if (BuildConfig.FLAVOR.contentEquals("free")) {
987             BannerAd.pauseAd(adView);
988         }
989
990         super.onPause();
991     }
992
993     @Override
994     public boolean onCreateOptionsMenu(Menu menu) {
995         // Inflate the menu; this adds items to the action bar if it is present.
996         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
997
998         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
999         mainMenu = menu;
1000
1001         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1002         updatePrivacyIcons(false);
1003
1004         // Get handles for the menu items.
1005         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1006         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1007         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1008         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1009
1010         // Only display third-party cookies if SDK >= 21
1011         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1012
1013         // Get the shared preference values.  `this` references the current context.
1014         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1015
1016         // Set the status of the additional app bar icons.  The default is `false`.
1017         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1018             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1019             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1020             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1021         } else { //Do not display the additional icons.
1022             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1023             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1024             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1025         }
1026
1027         return true;
1028     }
1029
1030     @Override
1031     public boolean onPrepareOptionsMenu(Menu menu) {
1032         // Get handles for the menu items.
1033         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1034         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1035         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1036         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1037         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1038         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1039         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1040         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1041         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1042
1043         // Set the status of the menu item checkboxes.
1044         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1045         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1046         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1047         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1048         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1049
1050         // Enable third-party cookies if first-party cookies are enabled.
1051         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1052
1053         // Enable DOM Storage if JavaScript is enabled.
1054         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1055
1056         // Enable Clear Cookies if there are any.
1057         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1058
1059         // Enable Clear Form Data is there is any.
1060         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1061         clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1062
1063         // Initialize font size variables.
1064         int fontSize = mainWebView.getSettings().getTextZoom();
1065         String fontSizeTitle;
1066         MenuItem selectedFontSizeMenuItem;
1067
1068         // Prepare the font size title and current size menu item.
1069         switch (fontSize) {
1070             case 25:
1071                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1072                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1073                 break;
1074
1075             case 50:
1076                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1077                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1078                 break;
1079
1080             case 75:
1081                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1082                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1083                 break;
1084
1085             case 100:
1086                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1087                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1088                 break;
1089
1090             case 125:
1091                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1092                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1093                 break;
1094
1095             case 150:
1096                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1097                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1098                 break;
1099
1100             case 175:
1101                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1102                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1103                 break;
1104
1105             case 200:
1106                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1107                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1108                 break;
1109
1110             default:
1111                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1112                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1113                 break;
1114         }
1115
1116         // Set the font size title and select the current size menu item.
1117         fontSizeMenuItem.setTitle(fontSizeTitle);
1118         selectedFontSizeMenuItem.setChecked(true);
1119
1120         // Only show `Refresh` if `swipeToRefresh` is disabled.
1121         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1122
1123         // Run all the other default commands.
1124         super.onPrepareOptionsMenu(menu);
1125
1126         // `return true` displays the menu.
1127         return true;
1128     }
1129
1130     @Override
1131     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1132     @SuppressLint("SetJavaScriptEnabled")
1133     // removeAllCookies is deprecated, but it is required for API < 21.
1134     @SuppressWarnings("deprecation")
1135     public boolean onOptionsItemSelected(MenuItem menuItem) {
1136         int menuItemId = menuItem.getItemId();
1137
1138         // Set the commands that relate to the menu entries.
1139         switch (menuItemId) {
1140             case R.id.toggle_javascript:
1141                 // Switch the status of javaScriptEnabled.
1142                 javaScriptEnabled = !javaScriptEnabled;
1143
1144                 // Apply the new JavaScript status.
1145                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1146
1147                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1148                 updatePrivacyIcons(true);
1149
1150                 // Display a `Snackbar`.
1151                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1152                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1153                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1154                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1155                 } else {  // Privacy mode.
1156                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1157                 }
1158
1159                 // Reload the WebView.
1160                 mainWebView.reload();
1161                 return true;
1162
1163             case R.id.toggle_first_party_cookies:
1164                 // Switch the status of firstPartyCookiesEnabled.
1165                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1166
1167                 // Update the menu checkbox.
1168                 menuItem.setChecked(firstPartyCookiesEnabled);
1169
1170                 // Apply the new cookie status.
1171                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1172
1173                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1174                 updatePrivacyIcons(true);
1175
1176                 // Display a `Snackbar`.
1177                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1178                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1179                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
1180                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1181                 } else {  // Privacy mode.
1182                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1183                 }
1184
1185                 // Reload the WebView.
1186                 mainWebView.reload();
1187                 return true;
1188
1189             case R.id.toggle_third_party_cookies:
1190                 if (Build.VERSION.SDK_INT >= 21) {
1191                     // Switch the status of thirdPartyCookiesEnabled.
1192                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1193
1194                     // Update the menu checkbox.
1195                     menuItem.setChecked(thirdPartyCookiesEnabled);
1196
1197                     // Apply the new cookie status.
1198                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1199
1200                     // Display a `Snackbar`.
1201                     if (thirdPartyCookiesEnabled) {
1202                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1203                     } else {
1204                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1205                     }
1206
1207                     // Reload the WebView.
1208                     mainWebView.reload();
1209                 } // Else do nothing because SDK < 21.
1210                 return true;
1211
1212             case R.id.toggle_dom_storage:
1213                 // Switch the status of domStorageEnabled.
1214                 domStorageEnabled = !domStorageEnabled;
1215
1216                 // Update the menu checkbox.
1217                 menuItem.setChecked(domStorageEnabled);
1218
1219                 // Apply the new DOM Storage status.
1220                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1221
1222                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1223                 updatePrivacyIcons(true);
1224
1225                 // Display a `Snackbar`.
1226                 if (domStorageEnabled) {
1227                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1228                 } else {
1229                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1230                 }
1231
1232                 // Reload the WebView.
1233                 mainWebView.reload();
1234                 return true;
1235
1236             case R.id.toggle_save_form_data:
1237                 // Switch the status of saveFormDataEnabled.
1238                 saveFormDataEnabled = !saveFormDataEnabled;
1239
1240                 // Update the menu checkbox.
1241                 menuItem.setChecked(saveFormDataEnabled);
1242
1243                 // Apply the new form data status.
1244                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1245
1246                 // Display a `Snackbar`.
1247                 if (saveFormDataEnabled) {
1248                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1249                 } else {
1250                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1251                 }
1252
1253                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1254                 updatePrivacyIcons(true);
1255
1256                 // Reload the WebView.
1257                 mainWebView.reload();
1258                 return true;
1259
1260             case R.id.clear_cookies:
1261                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1262                         .setAction(R.string.undo, new View.OnClickListener() {
1263                             @Override
1264                             public void onClick(View v) {
1265                                 // Do nothing because everything will be handled by `onDismissed()` below.
1266                             }
1267                         })
1268                         .addCallback(new Snackbar.Callback() {
1269                             @Override
1270                             public void onDismissed(Snackbar snackbar, int event) {
1271                                 switch (event) {
1272                                     // The user pushed the `Undo` button.
1273                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1274                                         // Do nothing.
1275                                         break;
1276
1277                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1278                                     default:
1279                                         // `cookieManager.removeAllCookie()` varies by SDK.
1280                                         if (Build.VERSION.SDK_INT < 21) {
1281                                             cookieManager.removeAllCookie();
1282                                         } else {
1283                                             // `null` indicates no callback.
1284                                             cookieManager.removeAllCookies(null);
1285                                         }
1286                                 }
1287                             }
1288                         })
1289                         .show();
1290                 return true;
1291
1292             case R.id.clear_dom_storage:
1293                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1294                         .setAction(R.string.undo, new View.OnClickListener() {
1295                             @Override
1296                             public void onClick(View v) {
1297                                 // Do nothing because everything will be handled by `onDismissed()` below.
1298                             }
1299                         })
1300                         .addCallback(new Snackbar.Callback() {
1301                             @Override
1302                             public void onDismissed(Snackbar snackbar, int event) {
1303                                 switch (event) {
1304                                     // The user pushed the `Undo` button.
1305                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1306                                         // Do nothing.
1307                                         break;
1308
1309                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1310                                     default:
1311                                         // Delete the DOM Storage.
1312                                         WebStorage webStorage = WebStorage.getInstance();
1313                                         webStorage.deleteAllData();
1314                                 }
1315                             }
1316                         })
1317                         .show();
1318                 return true;
1319
1320             case R.id.clear_form_data:
1321                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1322                         .setAction(R.string.undo, new View.OnClickListener() {
1323                             @Override
1324                             public void onClick(View v) {
1325                                 // Do nothing because everything will be handled by `onDismissed()` below.
1326                             }
1327                         })
1328                         .addCallback(new Snackbar.Callback() {
1329                             @Override
1330                             public void onDismissed(Snackbar snackbar, int event) {
1331                                 switch (event) {
1332                                     // The user pushed the `Undo` button.
1333                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1334                                         // Do nothing.
1335                                         break;
1336
1337                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1338                                     default:
1339                                         // Delete the form data.
1340                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1341                                         mainWebViewDatabase.clearFormData();
1342                                 }
1343                             }
1344                         })
1345                         .show();
1346                 return true;
1347
1348             case R.id.font_size_twenty_five_percent:
1349                 mainWebView.getSettings().setTextZoom(25);
1350                 return true;
1351
1352             case R.id.font_size_fifty_percent:
1353                 mainWebView.getSettings().setTextZoom(50);
1354                 return true;
1355
1356             case R.id.font_size_seventy_five_percent:
1357                 mainWebView.getSettings().setTextZoom(75);
1358                 return true;
1359
1360             case R.id.font_size_one_hundred_percent:
1361                 mainWebView.getSettings().setTextZoom(100);
1362                 return true;
1363
1364             case R.id.font_size_one_hundred_twenty_five_percent:
1365                 mainWebView.getSettings().setTextZoom(125);
1366                 return true;
1367
1368             case R.id.font_size_one_hundred_fifty_percent:
1369                 mainWebView.getSettings().setTextZoom(150);
1370                 return true;
1371
1372             case R.id.font_size_one_hundred_seventy_five_percent:
1373                 mainWebView.getSettings().setTextZoom(175);
1374                 return true;
1375
1376             case R.id.font_size_two_hundred_percent:
1377                 mainWebView.getSettings().setTextZoom(200);
1378                 return true;
1379
1380             case R.id.display_images:
1381                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1382                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
1383                     mainWebView.reload();
1384                 } else {  // Images are not currently loaded automatically.
1385                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
1386                 }
1387
1388                 // Set `onTheFlyDisplayImagesSet`.
1389                 onTheFlyDisplayImagesSet = true;
1390                 return true;
1391
1392             case R.id.share:
1393                 // Setup the share string.
1394                 String shareString;
1395                 if (webViewTitle != null) {
1396                     shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1397                 } else {
1398                     shareString = urlTextBox.getText().toString();
1399                 }
1400
1401                 // Create the share intent.
1402                 Intent shareIntent = new Intent();
1403                 shareIntent.setAction(Intent.ACTION_SEND);
1404                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1405                 shareIntent.setType("text/plain");
1406
1407                 // Make it so.
1408                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1409                 return true;
1410
1411             case R.id.find_on_page:
1412                 // Hide the URL app bar.
1413                 supportAppBar.setVisibility(View.GONE);
1414
1415                 // Show the Find on Page `RelativeLayout`.
1416                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1417
1418                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
1419                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1420                 findOnPageEditText.postDelayed(new Runnable()
1421                 {
1422                     @Override
1423                     public void run()
1424                     {
1425                         // Set the focus on `findOnPageEditText`.
1426                         findOnPageEditText.requestFocus();
1427
1428                         // Display the keyboard.
1429                         inputMethodManager.showSoftInput(findOnPageEditText, 0);
1430                     }
1431                 }, 200);
1432                 return true;
1433
1434             case R.id.print:
1435                 // Get a `PrintManager` instance.
1436                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1437
1438                 // Convert `mainWebView` to `printDocumentAdapter`.
1439                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1440
1441                 // Print the document.  The print attributes are `null`.
1442                 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1443                 return true;
1444
1445             case R.id.add_to_homescreen:
1446                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1447                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1448                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1449
1450                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1451                 return true;
1452
1453             case R.id.refresh:
1454                 mainWebView.reload();
1455                 return true;
1456
1457             default:
1458                 // Don't consume the event.
1459                 return super.onOptionsItemSelected(menuItem);
1460         }
1461     }
1462
1463     // removeAllCookies is deprecated, but it is required for API < 21.
1464     @SuppressWarnings("deprecation")
1465     @Override
1466     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1467         int menuItemId = menuItem.getItemId();
1468
1469         switch (menuItemId) {
1470             case R.id.home:
1471                 loadUrl(homepage);
1472                 break;
1473
1474             case R.id.back:
1475                 if (mainWebView.canGoBack()) {
1476                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1477                     navigatingHistory = true;
1478
1479                     // Load the previous website in the history.
1480                     mainWebView.goBack();
1481                 }
1482                 break;
1483
1484             case R.id.forward:
1485                 if (mainWebView.canGoForward()) {
1486                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1487                     navigatingHistory = true;
1488
1489                     // Load the next website in the history.
1490                     mainWebView.goForward();
1491                 }
1492                 break;
1493
1494             case R.id.history:
1495                 // Get the `WebBackForwardList`.
1496                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1497
1498                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
1499                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1500                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1501                 break;
1502
1503             case R.id.bookmarks:
1504                 // Launch BookmarksActivity.
1505                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1506                 startActivity(bookmarksIntent);
1507                 break;
1508
1509             case R.id.downloads:
1510                 // Launch the system Download Manager.
1511                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1512
1513                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1514                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1515
1516                 startActivity(downloadManagerIntent);
1517                 break;
1518
1519             case R.id.settings:
1520                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1521                 currentDomainName = "";
1522
1523                 // Launch `SettingsActivity`.
1524                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1525                 startActivity(settingsIntent);
1526                 break;
1527
1528             case R.id.domains:
1529                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1530                 currentDomainName = "";
1531
1532                 // Launch `DomainsActivity`.
1533                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1534                 startActivity(domainsIntent);
1535                 break;
1536
1537             case R.id.guide:
1538                 // Launch `GuideActivity`.
1539                 Intent guideIntent = new Intent(this, GuideActivity.class);
1540                 startActivity(guideIntent);
1541                 break;
1542
1543             case R.id.about:
1544                 // Launch `AboutActivity`.
1545                 Intent aboutIntent = new Intent(this, AboutActivity.class);
1546                 startActivity(aboutIntent);
1547                 break;
1548
1549             case R.id.clearAndExit:
1550                 // Get a handle for `sharedPreferences`.  `this` references the current context.
1551                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1552
1553                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1554
1555                 // Clear cookies.
1556                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1557                     // The command to remove cookies changed slightly in API 21.
1558                     if (Build.VERSION.SDK_INT >= 21) {
1559                         cookieManager.removeAllCookies(null);
1560                     } else {
1561                         cookieManager.removeAllCookie();
1562                     }
1563
1564                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1565                     try {
1566                         // We have to use two commands because `Runtime.exec()` does not like `*`.
1567                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1568                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1569                     } catch (IOException e) {
1570                         // Do nothing if an error is thrown.
1571                     }
1572                 }
1573
1574                 // Clear DOM storage.
1575                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1576                     // Ask `WebStorage` to clear the DOM storage.
1577                     WebStorage webStorage = WebStorage.getInstance();
1578                     webStorage.deleteAllData();
1579
1580                     // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1581                     try {
1582                         // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1583                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1584                     } catch (IOException e) {
1585                         // Do nothing if an error is thrown.
1586                     }
1587                 }
1588
1589                 // Clear form data.
1590                 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1591                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1592                     webViewDatabase.clearFormData();
1593
1594                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1595                     try {
1596                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1597                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1598                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1599                     } catch (IOException e) {
1600                         // Do nothing if an error is thrown.
1601                     }
1602                 }
1603
1604                 // Clear the cache.
1605                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1606                     // `true` includes disk files.
1607                     mainWebView.clearCache(true);
1608
1609                     // Manually delete the cache directories.
1610                     try {
1611                         // Delete the main cache directory.
1612                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1613
1614                         // Delete the secondary `Service Worker` cache directory.  We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1615                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1616                     } catch (IOException e) {
1617                         // Do nothing if an error is thrown.
1618                     }
1619                 }
1620
1621                 // Clear SSL certificate preferences.
1622                 mainWebView.clearSslPreferences();
1623
1624                 // Clear the back/forward history.
1625                 mainWebView.clearHistory();
1626
1627                 // Clear `formattedUrlString`.
1628                 formattedUrlString = null;
1629
1630                 // Clear `customHeaders`.
1631                 customHeaders.clear();
1632
1633                 // Detach all views from `mainWebViewRelativeLayout`.
1634                 mainWebViewRelativeLayout.removeAllViews();
1635
1636                 // Destroy the internal state of `mainWebView`.
1637                 mainWebView.destroy();
1638
1639                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1640                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1641                 if (clearEverything) {
1642                     try {
1643                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1644                     } catch (IOException e) {
1645                         // Do nothing if an error is thrown.
1646                     }
1647                 }
1648
1649                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1650                 if (Build.VERSION.SDK_INT >= 21) {
1651                     finishAndRemoveTask();
1652                 } else {
1653                     finish();
1654                 }
1655
1656                 // Remove the terminated program from RAM.  The status code is `0`.
1657                 System.exit(0);
1658                 break;
1659         }
1660
1661         // Close the navigation drawer.
1662         drawerLayout.closeDrawer(GravityCompat.START);
1663         return true;
1664     }
1665
1666     @Override
1667     public void onPostCreate(Bundle savedInstanceState) {
1668         super.onPostCreate(savedInstanceState);
1669
1670         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1671         drawerToggle.syncState();
1672     }
1673
1674     @Override
1675     public void onConfigurationChanged(Configuration newConfig) {
1676         super.onConfigurationChanged(newConfig);
1677
1678         // Reload the ad for the free flavor if we are not in full screen mode.
1679         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1680             // Reload the ad.
1681             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1682
1683             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1684             adView = findViewById(R.id.adview);
1685         }
1686
1687         // `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
1688         // ActivityCompat.invalidateOptionsMenu(this);
1689     }
1690
1691     @Override
1692     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1693         // Store the `HitTestResult`.
1694         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1695
1696         // Create strings.
1697         final String imageUrl;
1698         final String linkUrl;
1699
1700         // Get a handle for the `ClipboardManager`.
1701         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1702
1703         switch (hitTestResult.getType()) {
1704             // `SRC_ANCHOR_TYPE` is a link.
1705             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1706                 // Get the target URL.
1707                 linkUrl = hitTestResult.getExtra();
1708
1709                 // Set the target URL as the title of the `ContextMenu`.
1710                 menu.setHeaderTitle(linkUrl);
1711
1712                 // Add a `Load URL` entry.
1713                 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1714                     @Override
1715                     public boolean onMenuItemClick(MenuItem item) {
1716                         loadUrl(linkUrl);
1717                         return false;
1718                     }
1719                 });
1720
1721                 // Add a `Copy URL` entry.
1722                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1723                     @Override
1724                     public boolean onMenuItemClick(MenuItem item) {
1725                         // Save the link URL in a `ClipData`.
1726                         ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1727
1728                         // Set the `ClipData` as the clipboard's primary clip.
1729                         clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1730                         return false;
1731                     }
1732                 });
1733
1734                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1735                 menu.add(R.string.cancel);
1736                 break;
1737
1738             case WebView.HitTestResult.EMAIL_TYPE:
1739                 // Get the target URL.
1740                 linkUrl = hitTestResult.getExtra();
1741
1742                 // Set the target URL as the title of the `ContextMenu`.
1743                 menu.setHeaderTitle(linkUrl);
1744
1745                 // Add a `Write Email` entry.
1746                 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1747                     @Override
1748                     public boolean onMenuItemClick(MenuItem item) {
1749                         // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1750                         Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1751
1752                         // Parse the url and set it as the data for the `Intent`.
1753                         emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1754
1755                         // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1756                         emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1757
1758                         // Make it so.
1759                         startActivity(emailIntent);
1760                         return false;
1761                     }
1762                 });
1763
1764                 // Add a `Copy Email Address` entry.
1765                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1766                     @Override
1767                     public boolean onMenuItemClick(MenuItem item) {
1768                         // Save the email address in a `ClipData`.
1769                         ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1770
1771                         // Set the `ClipData` as the clipboard's primary clip.
1772                         clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1773                         return false;
1774                     }
1775                 });
1776
1777                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1778                 menu.add(R.string.cancel);
1779                 break;
1780
1781             // `IMAGE_TYPE` is an image.
1782             case WebView.HitTestResult.IMAGE_TYPE:
1783                 // Get the image URL.
1784                 imageUrl = hitTestResult.getExtra();
1785
1786                 // Set the image URL as the title of the `ContextMenu`.
1787                 menu.setHeaderTitle(imageUrl);
1788
1789                 // Add a `View Image` entry.
1790                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1791                     @Override
1792                     public boolean onMenuItemClick(MenuItem item) {
1793                         loadUrl(imageUrl);
1794                         return false;
1795                     }
1796                 });
1797
1798                 // Add a `Download Image` entry.
1799                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1800                     @Override
1801                     public boolean onMenuItemClick(MenuItem item) {
1802                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1803                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1804                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1805                         return false;
1806                     }
1807                 });
1808
1809                 // Add a `Copy URL` entry.
1810                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1811                     @Override
1812                     public boolean onMenuItemClick(MenuItem item) {
1813                         // Save the image URL in a `ClipData`.
1814                         ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1815
1816                         // Set the `ClipData` as the clipboard's primary clip.
1817                         clipboardManager.setPrimaryClip(srcImageTypeClipData);
1818                         return false;
1819                     }
1820                 });
1821
1822                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1823                 menu.add(R.string.cancel);
1824                 break;
1825
1826
1827             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1828             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1829                 // Get the image URL.
1830                 imageUrl = hitTestResult.getExtra();
1831
1832                 // Set the image URL as the title of the `ContextMenu`.
1833                 menu.setHeaderTitle(imageUrl);
1834
1835                 // Add a `View Image` entry.
1836                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1837                     @Override
1838                     public boolean onMenuItemClick(MenuItem item) {
1839                         loadUrl(imageUrl);
1840                         return false;
1841                     }
1842                 });
1843
1844                 // Add a `Download Image` entry.
1845                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1846                     @Override
1847                     public boolean onMenuItemClick(MenuItem item) {
1848                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1849                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1850                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1851                         return false;
1852                     }
1853                 });
1854
1855                 // Add a `Copy URL` entry.
1856                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1857                     @Override
1858                     public boolean onMenuItemClick(MenuItem item) {
1859                         // Save the image URL in a `ClipData`.
1860                         ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1861
1862                         // Set the `ClipData` as the clipboard's primary clip.
1863                         clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1864                         return false;
1865                     }
1866                 });
1867
1868                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1869                 menu.add(R.string.cancel);
1870                 break;
1871         }
1872     }
1873
1874     @Override
1875     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1876         // Get shortcutNameEditText from the alert dialog.
1877         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1878
1879         // Create the bookmark shortcut based on formattedUrlString.
1880         Intent bookmarkShortcut = new Intent();
1881         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1882         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1883
1884         // Place the bookmark shortcut on the home screen.
1885         Intent placeBookmarkShortcut = new Intent();
1886         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1887         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1888         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1889         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1890         sendBroadcast(placeBookmarkShortcut);
1891     }
1892
1893     @Override
1894     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1895         // Download the image if it has an HTTP or HTTPS URI.
1896         if (imageUrl.startsWith("http")) {
1897             // Get a handle for the system `DOWNLOAD_SERVICE`.
1898             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1899
1900             // Parse `imageUrl`.
1901             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1902
1903             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
1904             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1905             if (firstPartyCookiesEnabled) {
1906                 // Get the cookies for `imageUrl`.
1907                 String cookies = cookieManager.getCookie(imageUrl);
1908
1909                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1910                 downloadRequest.addRequestHeader("Cookie", cookies);
1911             }
1912
1913             // Get the file name from `dialogFragment`.
1914             EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1915             String imageName = downloadImageNameEditText.getText().toString();
1916
1917             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1918             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1919                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1920             } else { // Only set the title using `imageName`.
1921                 downloadRequest.setTitle(imageName);
1922             }
1923
1924             // Allow `MediaScanner` to index the download if it is a media file.
1925             downloadRequest.allowScanningByMediaScanner();
1926
1927             // Add the URL as the description for the download.
1928             downloadRequest.setDescription(imageUrl);
1929
1930             // Show the download notification after the download is completed.
1931             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1932
1933             // Initiate the download.
1934             downloadManager.enqueue(downloadRequest);
1935         } else {  // The image is not an HTTP or HTTPS URI.
1936             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1937         }
1938     }
1939
1940     @Override
1941     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1942         // Download the file if it has an HTTP or HTTPS URI.
1943         if (downloadUrl.startsWith("http")) {
1944
1945             // Get a handle for the system `DOWNLOAD_SERVICE`.
1946             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1947
1948             // Parse `downloadUrl`.
1949             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1950
1951             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
1952             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1953             if (firstPartyCookiesEnabled) {
1954                 // Get the cookies for `downloadUrl`.
1955                 String cookies = cookieManager.getCookie(downloadUrl);
1956
1957                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1958                 downloadRequest.addRequestHeader("Cookie", cookies);
1959             }
1960
1961             // Get the file name from `dialogFragment`.
1962             EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1963             String fileName = downloadFileNameEditText.getText().toString();
1964
1965             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1966             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1967                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1968             } else { // Only set the title using `fileName`.
1969                 downloadRequest.setTitle(fileName);
1970             }
1971
1972             // Allow `MediaScanner` to index the download if it is a media file.
1973             downloadRequest.allowScanningByMediaScanner();
1974
1975             // Add the URL as the description for the download.
1976             downloadRequest.setDescription(downloadUrl);
1977
1978             // Show the download notification after the download is completed.
1979             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1980
1981             // Initiate the download.
1982             downloadManager.enqueue(downloadRequest);
1983         } else {  // The download is not an HTTP or HTTPS URI.
1984             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1985         }
1986     }
1987
1988     public void viewSslCertificate(View view) {
1989         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1990         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
1991         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1992     }
1993
1994     @Override
1995     public void onSslErrorCancel() {
1996         sslErrorHandler.cancel();
1997     }
1998
1999     @Override
2000     public void onSslErrorProceed() {
2001         sslErrorHandler.proceed();
2002     }
2003
2004     @Override
2005     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2006         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2007         navigatingHistory = true;
2008
2009         // Load the history entry.
2010         mainWebView.goBackOrForward(moveBackOrForwardSteps);
2011     }
2012
2013     @Override
2014     public void onClearHistory() {
2015         // Clear the history.
2016         mainWebView.clearHistory();
2017     }
2018
2019     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2020     @Override
2021     public void onBackPressed() {
2022         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2023         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2024             drawerLayout.closeDrawer(GravityCompat.START);
2025         } else {
2026             // Load the previous URL if available.
2027             if (mainWebView.canGoBack()) {
2028                 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2029                 navigatingHistory = true;
2030
2031                 // Go back.
2032                 mainWebView.goBack();
2033             } else {
2034                 // Pass `onBackPressed()` to the system.
2035                 super.onBackPressed();
2036             }
2037         }
2038     }
2039
2040     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2041         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
2042         String unformattedUrlString = urlTextBox.getText().toString().trim();
2043
2044         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
2045         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2046             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
2047             if (!unformattedUrlString.startsWith("http")) {
2048                 unformattedUrlString = "http://" + unformattedUrlString;
2049             }
2050
2051             // Initialize `unformattedUrl`.
2052             URL unformattedUrl = null;
2053
2054             // 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.
2055             try {
2056                 unformattedUrl = new URL(unformattedUrlString);
2057             } catch (MalformedURLException e) {
2058                 e.printStackTrace();
2059             }
2060
2061             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2062             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2063             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2064             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2065             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2066             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2067
2068             // Build the URI.
2069             Uri.Builder formattedUri = new Uri.Builder();
2070             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2071
2072             // Decode `formattedUri` as a `String` in `UTF-8`.
2073             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2074         } else {
2075             // Sanitize the search input and convert it to a search.
2076             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2077
2078             // Add the base search URL.
2079             formattedUrlString = searchURL + encodedUrlString;
2080         }
2081
2082         loadUrl(formattedUrlString);
2083
2084         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2085         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2086     }
2087
2088
2089     private void loadUrl(String url) {
2090         // Apply any custom domain settings.
2091         applyDomainSettings(url);
2092
2093         // Load the URL.
2094         mainWebView.loadUrl(url, customHeaders);
2095     }
2096
2097     public void findPreviousOnPage(View view) {
2098         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
2099         mainWebView.findNext(false);
2100     }
2101
2102     public void findNextOnPage(View view) {
2103         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2104         mainWebView.findNext(true);
2105     }
2106
2107     public void closeFindOnPage(View view) {
2108         // Delete the contents of `find_on_page_edittext`.
2109         findOnPageEditText.setText(null);
2110
2111         // Clear the highlighted phrases.
2112         mainWebView.clearMatches();
2113
2114         // Hide the Find on Page `RelativeLayout`.
2115         findOnPageLinearLayout.setVisibility(View.GONE);
2116
2117         // Show the URL app bar.
2118         supportAppBar.setVisibility(View.VISIBLE);
2119
2120         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2121         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2122     }
2123
2124     private void applyAppSettings() {
2125         // Get a handle for `sharedPreferences`.  `this` references the current context.
2126         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2127
2128         // Store the values from `sharedPreferences` in variables.
2129         String homepageString = sharedPreferences.getString("homepage", "https://duckduckgo.com");
2130         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2131         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2132         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2133         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2134         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2135         adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2136         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2137         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2138         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2139         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2140         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2141         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2142         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2143         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2144
2145         // Set the homepage, search, and proxy options.
2146         if (proxyThroughOrbot) {  // Set the Tor options.
2147             // Set `torHomepageString` as `homepage`.
2148             homepage = torHomepageString;
2149
2150             // If formattedUrlString is null assign the homepage to it.
2151             if (formattedUrlString == null) {
2152                 formattedUrlString = homepage;
2153             }
2154
2155             // Set the search URL.
2156             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
2157                 searchURL = torSearchCustomURLString;
2158             } else {  // Use the string from the pre-built list.
2159                 searchURL = torSearchString;
2160             }
2161
2162             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
2163             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2164
2165             // Display a message to the user if we are waiting on Orbot.
2166             if (!orbotStatus.equals("ON")) {
2167                 // Set `waitingForOrbot`.
2168                 waitingForOrbot = true;
2169
2170                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
2171                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2172             }
2173         } else {  // Set the non-Tor options.
2174             // Set `homepageString` as `homepage`.
2175             homepage = homepageString;
2176
2177             // If formattedUrlString is null assign the homepage to it.
2178             if (formattedUrlString == null) {
2179                 formattedUrlString = homepage;
2180             }
2181
2182             // Set the search URL.
2183             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
2184                 searchURL = searchCustomURLString;
2185             } else {  // Use the string from the pre-built list.
2186                 searchURL = searchString;
2187             }
2188
2189             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
2190             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2191
2192             // Reset `waitingForOrbot.
2193             waitingForOrbot = false;
2194         }
2195
2196         // Set swipe to refresh.
2197         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2198
2199         // Set Do Not Track status.
2200         if (doNotTrackEnabled) {
2201             customHeaders.put("DNT", "1");
2202         } else {
2203             customHeaders.remove("DNT");
2204         }
2205
2206         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2207         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2208             if (hideSystemBarsOnFullscreen) {  // Hide everything.
2209                 // Remove the translucent navigation setting if it is currently flagged.
2210                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2211
2212                 // Remove the translucent status bar overlay.
2213                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2214
2215                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2216                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2217
2218                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2219                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2220                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2221                  */
2222                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2223             } else {  // Hide everything except the status and navigation bars.
2224                 // Add the translucent status flag if it is unset.
2225                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2226
2227                 if (translucentNavigationBarOnFullscreen) {
2228                     // Set the navigation bar to be translucent.
2229                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2230                 } else {
2231                     // Set the navigation bar to be black.
2232                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2233                 }
2234             }
2235         } else {  // Switch to normal viewing mode.
2236             // Reset `inFullScreenBrowsingMode` to `false`.
2237             inFullScreenBrowsingMode = false;
2238
2239             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2240             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2241                 appBar.show();
2242             }
2243
2244             // Show the `BannerAd` in the free flavor.
2245             if (BuildConfig.FLAVOR.contentEquals("free")) {
2246                 // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
2247                 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2248
2249                 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2250                 adView = findViewById(R.id.adview);
2251             }
2252
2253             // Remove the translucent navigation bar flag if it is set.
2254             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2255
2256             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2257             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2258
2259             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2260             rootCoordinatorLayout.setSystemUiVisibility(0);
2261
2262             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2263             rootCoordinatorLayout.setFitsSystemWindows(true);
2264         }
2265     }
2266
2267     // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2268     @SuppressWarnings("deprecation")
2269     private void applyDomainSettings(String url) {
2270         // Reset `navigatingHistory`.
2271         navigatingHistory = false;
2272
2273         // Parse the URL into a URI.
2274         Uri uri = Uri.parse(url);
2275
2276         // Extract the domain from `uri`.
2277         String hostName = uri.getHost();
2278
2279         // Initialize `loadingNewDomainName`.
2280         boolean loadingNewDomainName;
2281
2282         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2283         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2284         //noinspection SimplifiableIfStatement
2285         if ((hostName == null) || (currentDomainName == null)) {
2286             loadingNewDomainName = true;
2287         } else {  // Determine if `hostName` equals `currentDomainName`.
2288             loadingNewDomainName = !hostName.equals(currentDomainName);
2289         }
2290
2291         // Only apply the domain settings if we are loading a new domain.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
2292         if (loadingNewDomainName) {
2293             // Set the new `hostname` as the `currentDomainName`.
2294             currentDomainName = hostName;
2295
2296             // Reset `favoriteIconBitmap` and display it in the `appbar`.
2297             favoriteIconBitmap = favoriteIconDefaultBitmap;
2298             favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2299
2300             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
2301             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2302             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2303
2304             // Get a full cursor from `domainsDatabaseHelper`.
2305             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2306
2307             // Initialize `domainSettingsSet`.
2308             Set<String> domainSettingsSet = new HashSet<>();
2309
2310             // Get the domain name column index.
2311             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2312
2313             // Populate `domainSettingsSet`.
2314             for (int i = 0; i < domainNameCursor.getCount(); i++) {
2315                 // Move `domainsCursor` to the current row.
2316                 domainNameCursor.moveToPosition(i);
2317
2318                 // Store the domain name in `domainSettingsSet`.
2319                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2320             }
2321
2322             // Close `domainNameCursor.
2323             domainNameCursor.close();
2324
2325             // Initialize variables to track if domain settings will be applied and, if so, under which name.
2326             domainSettingsApplied = false;
2327             String domainNameInDatabase = null;
2328
2329             // Check the hostname.
2330             if (domainSettingsSet.contains(hostName)) {
2331                 domainSettingsApplied = true;
2332                 domainNameInDatabase = hostName;
2333             }
2334
2335             // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2336             if (hostName != null) {
2337                 while (hostName.contains(".") && !domainSettingsApplied) {  // Stop checking if we run out of  `.` or if we already know that `domainSettingsApplied` is `true`.
2338                     if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
2339                         domainSettingsApplied = true;
2340                         domainNameInDatabase = "*." + hostName;
2341                     }
2342
2343                     // Strip out the lowest subdomain of `host`.
2344                     hostName = hostName.substring(hostName.indexOf(".") + 1);
2345                 }
2346             }
2347
2348             // Get a handle for the shared preference.  `this` references the current context.
2349             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2350
2351             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
2352                 // Get a cursor for the current host and move it to the first position.
2353                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2354                 currentHostDomainSettingsCursor.moveToFirst();
2355
2356                 // Get the settings from the cursor.
2357                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2358                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2359                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2360                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2361                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2362                 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2363                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2364                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2365
2366                 // Close `currentHostDomainSettingsCursor`.
2367                 currentHostDomainSettingsCursor.close();
2368
2369                 // Apply the domain settings.
2370                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2371                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2372                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2373                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2374                 mainWebView.getSettings().setTextZoom(fontSize);
2375
2376                 // Set third-party cookies status if API >= 21.
2377                 if (Build.VERSION.SDK_INT >= 21) {
2378                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2379                 }
2380
2381                 // Set the user agent.
2382                 if (userAgentString.equals("WebView default user agent")) {
2383                     // Set the user agent to `""`, which uses the default value.
2384                     mainWebView.getSettings().setUserAgentString("");
2385                 } else {
2386                     // Use the selected user agent.
2387                     mainWebView.getSettings().setUserAgentString(userAgentString);
2388                 }
2389
2390                 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2391                 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2392             } else {  // The URL we are loading does not have custom domain settings.  Load the defaults.
2393                 // Store the values from `sharedPreferences` in variables.
2394                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2395                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2396                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2397                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2398                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2399                 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2400                 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2401                 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2402
2403                 // Apply the default settings.
2404                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2405                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2406                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2407                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2408                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2409
2410                 // Set third-party cookies status if API >= 21.
2411                 if (Build.VERSION.SDK_INT >= 21) {
2412                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2413                 }
2414
2415                 // Set the default user agent.
2416                 switch (userAgentString) {
2417                     case "WebView default user agent":
2418                         // Set the user agent to `""`, which uses the default value.
2419                         mainWebView.getSettings().setUserAgentString("");
2420                         break;
2421
2422                     case "Custom user agent":
2423                         // Set the custom user agent.
2424                         mainWebView.getSettings().setUserAgentString(customUserAgentString);
2425                         break;
2426
2427                     default:
2428                         // Use the selected user agent.
2429                         mainWebView.getSettings().setUserAgentString(userAgentString);
2430                         break;
2431                 }
2432
2433                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2434                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2435             }
2436
2437             // Close `domainsDatabaseHelper`.
2438             domainsDatabaseHelper.close();
2439
2440             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
2441             onTheFlyDisplayImagesSet = false;
2442             setDisplayWebpageImages();
2443
2444             // Update the privacy icons, but only if `mainMenu` has already been populated.
2445             if (mainMenu != null) {
2446                 updatePrivacyIcons(true);
2447             }
2448         }
2449     }
2450
2451     private void setDisplayWebpageImages() {
2452         if (!onTheFlyDisplayImagesSet) {
2453             if (domainSettingsApplied) {  // Custom domain settings are applied.
2454                 switch (displayWebpageImagesInt) {
2455                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2456                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2457                         break;
2458
2459                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2460                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
2461                         break;
2462
2463                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2464                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
2465                         break;
2466                 }
2467             } else {  // Default settings are applied.
2468                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2469             }
2470         }
2471     }
2472
2473     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2474         // Get handles for the icons.
2475         MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2476         MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2477         MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2478         MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2479
2480         // Update `privacyIcon`.
2481         if (javaScriptEnabled) {  // JavaScript is enabled.
2482             privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2483         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
2484             privacyIconMenuItem.setIcon(R.drawable.warning);
2485         } else {  // All the dangerous features are disabled.
2486             privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2487         }
2488
2489         // Update `firstPartyCookiesIcon`.
2490         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2491             firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2492         } else {  // First-party cookies are disabled.
2493             firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2494         }
2495
2496         // Update `domStorageIcon`.
2497         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
2498             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2499         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
2500             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2501         } else {  // JavaScript is disabled, so DOM storage is ghosted.
2502             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2503         }
2504
2505         // Update `formDataIcon`.
2506         if (saveFormDataEnabled) {  // Form data is enabled.
2507             formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2508         } else {  // Form data is disabled.
2509             formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2510         }
2511
2512         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.  `this` references the current activity.
2513         if (runInvalidateOptionsMenu) {
2514             ActivityCompat.invalidateOptionsMenu(this);
2515         }
2516     }
2517 }