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