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