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