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