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