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