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