]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
032aacb07109d24d164e906a9a6b8731448addb9
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 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.BitmapFactory;
38 import android.graphics.Typeface;
39 import android.graphics.drawable.BitmapDrawable;
40 import android.graphics.drawable.Drawable;
41 import android.net.Uri;
42 import android.net.http.SslCertificate;
43 import android.net.http.SslError;
44 import android.os.Build;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.preference.PreferenceManager;
48 import android.print.PrintDocumentAdapter;
49 import android.print.PrintManager;
50 import android.support.annotation.NonNull;
51 import android.support.design.widget.CoordinatorLayout;
52 import android.support.design.widget.FloatingActionButton;
53 import android.support.design.widget.NavigationView;
54 import android.support.design.widget.Snackbar;
55 import android.support.v4.content.ContextCompat;
56 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
57 import android.support.v4.content.pm.ShortcutInfoCompat;
58 import android.support.v4.content.pm.ShortcutManagerCompat;
59 import android.support.v4.graphics.drawable.IconCompat;
60 import android.support.v4.view.GravityCompat;
61 import android.support.v4.widget.DrawerLayout;
62 import android.support.v4.widget.SwipeRefreshLayout;
63 import android.support.v7.app.ActionBar;
64 import android.support.v7.app.ActionBarDrawerToggle;
65 import android.support.v7.app.AppCompatActivity;
66 import android.support.v7.app.AppCompatDialogFragment;
67 import android.support.v7.widget.Toolbar;
68 import android.text.Editable;
69 import android.text.Spanned;
70 import android.text.TextWatcher;
71 import android.text.style.ForegroundColorSpan;
72 import android.util.Patterns;
73 import android.view.ContextMenu;
74 import android.view.GestureDetector;
75 import android.view.KeyEvent;
76 import android.view.Menu;
77 import android.view.MenuItem;
78 import android.view.MotionEvent;
79 import android.view.View;
80 import android.view.ViewGroup;
81 import android.view.WindowManager;
82 import android.view.inputmethod.InputMethodManager;
83 import android.webkit.CookieManager;
84 import android.webkit.HttpAuthHandler;
85 import android.webkit.SslErrorHandler;
86 import android.webkit.WebBackForwardList;
87 import android.webkit.WebChromeClient;
88 import android.webkit.WebResourceResponse;
89 import android.webkit.WebStorage;
90 import android.webkit.WebView;
91 import android.webkit.WebViewClient;
92 import android.webkit.WebViewDatabase;
93 import android.widget.CursorAdapter;
94 import android.widget.EditText;
95 import android.widget.FrameLayout;
96 import android.widget.ImageView;
97 import android.widget.LinearLayout;
98 import android.widget.ListView;
99 import android.widget.ProgressBar;
100 import android.widget.RadioButton;
101 import android.widget.RelativeLayout;
102 import android.widget.TextView;
103
104 import com.stoutner.privacybrowser.BannerAd;
105 import com.stoutner.privacybrowser.BuildConfig;
106 import com.stoutner.privacybrowser.R;
107 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
108 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
109 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
110 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
111 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
112 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
113 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
114 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
115 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
116 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
117 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
118 import com.stoutner.privacybrowser.helpers.BlockListHelper;
119 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
120 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
121 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
124
125 import java.io.ByteArrayInputStream;
126 import java.io.ByteArrayOutputStream;
127 import java.io.File;
128 import java.io.IOException;
129 import java.io.UnsupportedEncodingException;
130 import java.net.MalformedURLException;
131 import java.net.URL;
132 import java.net.URLDecoder;
133 import java.net.URLEncoder;
134 import java.util.ArrayList;
135 import java.util.Date;
136 import java.util.HashMap;
137 import java.util.HashSet;
138 import java.util.List;
139 import java.util.Map;
140 import java.util.Set;
141
142 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
143 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener,
144         CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener,
145         DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
146         NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener,
147         UrlHistoryDialog.UrlHistoryListener {
148
149     // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
150     // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
151     // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
152     //  and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
153     public static boolean darkTheme;
154
155     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
156     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
157     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
158     public static Bitmap favoriteIconBitmap;
159
160     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
161     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
162     public static String formattedUrlString;
163
164     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
165     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
166     public static SslCertificate sslCertificate;
167
168     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`.
169     public static String orbotStatus;
170
171     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
172     public static String webViewTitle;
173
174     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
175     public static String appliedUserAgentString;
176
177     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
178     public static boolean reloadOnRestart;
179
180     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`.
181     public static boolean loadUrlOnRestart;
182
183     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
184     public static boolean restartFromBookmarksActivity;
185
186     // The block list versions are public static so they can be accessed from `AboutTabFragment`.  They are also used in `onCreate()`.
187     public static String easyListVersion;
188     public static String easyPrivacyVersion;
189     public static String fanboyAnnoyanceVersion;
190     public static String fanboySocialVersion;
191
192     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
193     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
194     public static String currentBookmarksFolder;
195
196     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
197     public static int domainSettingsDatabaseId;
198
199     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
200     public static String pinnedDomainSslIssuedToCNameString;
201     public static String pinnedDomainSslIssuedToONameString;
202     public static String pinnedDomainSslIssuedToUNameString;
203     public static String pinnedDomainSslIssuedByCNameString;
204     public static String pinnedDomainSslIssuedByONameString;
205     public static String pinnedDomainSslIssuedByUNameString;
206     public static Date pinnedDomainSslStartDate;
207     public static Date pinnedDomainSslEndDate;
208
209
210     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
211     private ActionBar appBar;
212
213     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
214     private boolean navigatingHistory;
215
216     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
217     private Bitmap favoriteIconDefaultBitmap;
218
219     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
220     private DrawerLayout drawerLayout;
221
222     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
223     private CoordinatorLayout rootCoordinatorLayout;
224
225     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
226     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
227     private WebView mainWebView;
228
229     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
230     private FrameLayout fullScreenVideoFrameLayout;
231
232     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
233     private SwipeRefreshLayout swipeRefreshLayout;
234
235     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
236     private RelativeLayout urlAppBarRelativeLayout;
237
238     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
239     private ImageView favoriteIconImageView;
240
241     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
242     private CookieManager cookieManager;
243
244     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
245     private final Map<String, String> customHeaders = new HashMap<>();
246
247     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
248     private boolean javaScriptEnabled;
249
250     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
251     private boolean firstPartyCookiesEnabled;
252
253     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
254     private boolean thirdPartyCookiesEnabled;
255
256     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
257     private boolean domStorageEnabled;
258
259     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
260     private boolean saveFormDataEnabled;
261
262     // `nightMode` is used in `onCreate()` and  `applyDomainSettings()`.
263     private boolean nightMode;
264
265     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
266     private boolean swipeToRefreshEnabled;
267
268     // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
269     private boolean displayWebpageImagesBoolean;
270
271     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
272     private String homepage;
273
274     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
275     private String searchURL;
276
277     // The block list variables are used in `onCreate()` and `applyAppSettings()`.
278     private boolean easyListEnabled;
279     private boolean easyPrivacyEnabled;
280     private boolean fanboyAnnoyanceListEnabled;
281     private boolean fanboySocialBlockingListEnabled;
282
283     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
284     private Runtime privacyBrowserRuntime;
285
286     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
287     private boolean incognitoModeEnabled;
288
289     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
290     private boolean fullScreenBrowsingModeEnabled;
291
292     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
293     private boolean inFullScreenBrowsingMode;
294
295     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
296     private boolean hideSystemBarsOnFullscreen;
297
298     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
299     private boolean translucentNavigationBarOnFullscreen;
300
301     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
302     private boolean reapplyDomainSettingsOnRestart;
303
304     // `returnFromSettings` is used in `onNavigationItemSelected()` and `onRestart()`.
305     private boolean returnFromSettings;
306
307     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
308     private String currentDomainName;
309
310     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
311     private boolean ignorePinnedSslCertificate;
312
313     // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
314     private boolean waitingForOrbot;
315
316     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
317     private boolean domainSettingsApplied;
318
319     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
320     private int displayWebpageImagesInt;
321
322     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
323     private boolean onTheFlyDisplayImagesSet;
324
325     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
326     private String waitingForOrbotHTMLString;
327
328     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
329     private String privateDataDirectoryString;
330
331     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
332     private LinearLayout findOnPageLinearLayout;
333
334     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
335     private EditText findOnPageEditText;
336
337     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
338     private Menu mainMenu;
339
340     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
341     private ActionBarDrawerToggle drawerToggle;
342
343     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
344     private Toolbar supportAppBar;
345
346     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
347     private EditText urlTextBox;
348
349     // The color spans are used in `onCreate()` and `highlightUrlText()`.
350     private ForegroundColorSpan redColorSpan;
351     private ForegroundColorSpan initialGrayColorSpan;
352     private ForegroundColorSpan finalGrayColorSpan;
353
354     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
355     private View adView;
356
357     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
358     private SslErrorHandler sslErrorHandler;
359
360     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
361     private static HttpAuthHandler httpAuthHandler;
362
363     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
364     private InputMethodManager inputMethodManager;
365
366     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
367     private RelativeLayout mainWebViewRelativeLayout;
368
369     // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
370     private boolean urlIsLoading;
371
372     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
373     private boolean pinnedDomainSslCertificate;
374
375     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
376     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
377
378     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
379     private ListView bookmarksListView;
380
381     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
382     private TextView bookmarksTitleTextView;
383
384     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
385     private Cursor bookmarksCursor;
386
387     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
388     private CursorAdapter bookmarksCursorAdapter;
389
390     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
391     private String oldFolderNameString;
392
393     @Override
394     // 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.
395     @SuppressLint({"SetJavaScriptEnabled"})
396     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
397     @SuppressWarnings("deprecation")
398     protected void onCreate(Bundle savedInstanceState) {
399         // Get a handle for `sharedPreferences`.  `this` references the current context.
400         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
401
402         // Get the theme preference.
403         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
404
405         // Set the activity theme.
406         if (darkTheme) {
407             setTheme(R.style.PrivacyBrowserDark);
408         } else {
409             setTheme(R.style.PrivacyBrowserLight);
410         }
411
412         // Run the default commands.
413         super.onCreate(savedInstanceState);
414
415         // Set the content view.
416         setContentView(R.layout.main_drawerlayout);
417
418         // Get a handle for `inputMethodManager`.
419         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
420
421         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
422         supportAppBar = findViewById(R.id.app_bar);
423         setSupportActionBar(supportAppBar);
424         appBar = getSupportActionBar();
425
426         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
427         assert appBar != null;
428
429         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
430         appBar.setCustomView(R.layout.url_app_bar);
431         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
432
433         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
434         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
435         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
436         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
437
438         // Get a handle for `urlTextBox`.
439         urlTextBox = findViewById(R.id.url_edittext);
440
441         // Remove the formatting from `urlTextBar` when the user is editing the text.
442         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
443             if (hasFocus) {  // The user is editing `urlTextBox`.
444                 // Remove the highlighting.
445                 urlTextBox.getText().removeSpan(redColorSpan);
446                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
447                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
448             } else {  // The user has stopped editing `urlTextBox`.
449                 // Reapply the highlighting.
450                 highlightUrlText();
451             }
452         });
453
454         // Set the go button on the keyboard to load the URL in `urlTextBox`.
455         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
456             // If the event is a key-down event on the `enter` button, load the URL.
457             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
458                 // Load the URL into the mainWebView and consume the event.
459                 try {
460                     loadUrlFromTextBox();
461                 } catch (UnsupportedEncodingException e) {
462                     e.printStackTrace();
463                 }
464                 // If the enter key was pressed, consume the event.
465                 return true;
466             } else {
467                 // If any other key was pressed, do not consume the event.
468                 return false;
469             }
470         });
471
472         // Set `waitingForOrbotHTMLString`.
473         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
474
475         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
476         currentDomainName = "";
477         orbotStatus = "unknown";
478         waitingForOrbot = false;
479
480         // Create an Orbot status `BroadcastReceiver`.
481         BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
482             @Override
483             public void onReceive(Context context, Intent intent) {
484                 // Store the content of the status message in `orbotStatus`.
485                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
486
487                 // If we are waiting on Orbot, load the website now that Orbot is connected.
488                 if (orbotStatus.equals("ON") && waitingForOrbot) {
489                     // Reset `waitingForOrbot`.
490                     waitingForOrbot = false;
491
492                     // Load `formattedUrlString
493                     loadUrl(formattedUrlString);
494                 }
495             }
496         };
497
498         // Register `orbotStatusBroadcastReceiver` on `this` context.
499         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
500
501         // Get handles for views that need to be accessed.
502         drawerLayout = findViewById(R.id.drawerlayout);
503         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
504         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
505         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
506         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
507         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
508         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
509         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
510         mainWebView = findViewById(R.id.main_webview);
511         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
512         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
513         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
514         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
515         favoriteIconImageView = findViewById(R.id.favorite_icon);
516
517         // Set the bookmarks drawer resources according to the theme.  This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
518         if (darkTheme) {
519             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
520             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
521             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
522             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
523         } else {
524             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
525             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
526             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
527             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
528         }
529
530         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
531         launchBookmarksActivityFab.setOnClickListener(v -> {
532             // Create an intent to launch the bookmarks activity.
533             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
534
535             // Include the current folder with the `Intent`.
536             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
537
538             // Make it so.
539             startActivity(bookmarksIntent);
540         });
541
542         // Set the create new bookmark folder FAB to display the `AlertDialog`.
543         createBookmarkFolderFab.setOnClickListener(v -> {
544             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
545             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
546             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
547         });
548
549         // Set the create new bookmark FAB to display the `AlertDialog`.
550         createBookmarkFab.setOnClickListener(view -> {
551             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
552             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
553             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
554         });
555
556         // Create a double-tap listener to toggle full-screen mode.
557         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
558             // Override `onDoubleTap()`.  All other events are handled using the default settings.
559             @Override
560             public boolean onDoubleTap(MotionEvent event) {
561                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
562                     // Toggle `inFullScreenBrowsingMode`.
563                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
564
565                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
566                         // Hide the `appBar`.
567                         appBar.hide();
568
569                         // Hide the `BannerAd` in the free flavor.
570                         if (BuildConfig.FLAVOR.contentEquals("free")) {
571                             BannerAd.hideAd(adView);
572                         }
573
574                         // Modify the system bars.
575                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
576                             // Remove the translucent overlays.
577                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
578
579                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
580                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
581
582                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
583                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
584                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
585                              */
586                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
587
588                             // Set `rootCoordinatorLayout` to fill the whole screen.
589                             rootCoordinatorLayout.setFitsSystemWindows(false);
590                         } else {  // Hide everything except the status and navigation bars.
591                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
592                             rootCoordinatorLayout.setFitsSystemWindows(false);
593
594                             // 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.
595                             if (translucentNavigationBarOnFullscreen) {
596                                 // Set the navigation bar to be translucent.
597                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
598                             }
599                         }
600                     } else {  // Switch to normal viewing mode.
601                         // Show the `appBar`.
602                         appBar.show();
603
604                         // Show the `BannerAd` in the free flavor.
605                         if (BuildConfig.FLAVOR.contentEquals("free")) {
606                             // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
607                             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
608
609                             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
610                             adView = findViewById(R.id.adview);
611                         }
612
613                         // Remove the translucent navigation bar flag if it is set.
614                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
615
616                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
617                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
618
619                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
620                         rootCoordinatorLayout.setSystemUiVisibility(0);
621
622                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
623                         rootCoordinatorLayout.setFitsSystemWindows(true);
624                     }
625
626                     // Consume the double-tap.
627                     return true;
628                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
629                     return false;
630                 }
631             }
632         });
633
634         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
635         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
636             // Call `performClick()` on the view, which is required for accessibility.
637             v.performClick();
638
639             // Send the `event` to `gestureDetector`.
640             return gestureDetector.onTouchEvent(event);
641         });
642
643         // Update `findOnPageCountTextView`.
644         mainWebView.setFindListener(new WebView.FindListener() {
645             // Get a handle for `findOnPageCountTextView`.
646             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
647
648             @Override
649             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
650                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
651                     // Set `findOnPageCountTextView` to `0/0`.
652                     findOnPageCountTextView.setText(R.string.zero_of_zero);
653                 } else if (isDoneCounting) {  // There are matches.
654                     // `activeMatchOrdinal` is zero-based.
655                     int activeMatch = activeMatchOrdinal + 1;
656
657                     // Build the match string.
658                     String matchString = activeMatch + "/" + numberOfMatches;
659
660                     // Set `findOnPageCountTextView`.
661                     findOnPageCountTextView.setText(matchString);
662                 }
663             }
664         });
665
666         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
667         findOnPageEditText.addTextChangedListener(new TextWatcher() {
668             @Override
669             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
670                 // Do nothing.
671             }
672
673             @Override
674             public void onTextChanged(CharSequence s, int start, int before, int count) {
675                 // Do nothing.
676             }
677
678             @Override
679             public void afterTextChanged(Editable s) {
680                 // Search for the text in `mainWebView`.
681                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
682             }
683         });
684
685         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
686         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
687             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
688                 // Hide the soft keyboard.  `0` indicates no additional flags.
689                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
690
691                 // Consume the event.
692                 return true;
693             } else {  // A different key was pressed.
694                 // Do not consume the event.
695                 return false;
696             }
697         });
698
699         // Implement swipe to refresh
700         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
701         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
702         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
703
704         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
705         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
706         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
707
708         // Listen for touches on the navigation menu.
709         final NavigationView navigationView = findViewById(R.id.navigationview);
710         navigationView.setNavigationItemSelectedListener(this);
711
712         // 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.
713         final Menu navigationMenu = navigationView.getMenu();
714         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
715         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
716         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
717
718         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
719         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
720         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
721
722         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
723         currentBookmarksFolder = "";
724
725         // Load the home folder, which is `""` in the database.
726         loadBookmarksFolder();
727
728         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
729             // Convert the id from long to int to match the format of the bookmarks database.
730             int databaseID = (int) id;
731
732             // Get the bookmark `Cursor` for this ID and move it to the first row.
733             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
734             bookmarkCursor.moveToFirst();
735
736             // Act upon the bookmark according to the type.
737             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
738                 // Store the new folder name in `currentBookmarksFolder`.
739                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
740
741                 // Load the new folder.
742                 loadBookmarksFolder();
743             } else {  // The selected bookmark is not a folder.
744                 // Load the bookmark URL.
745                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
746
747                 // Close the bookmarks drawer.
748                 drawerLayout.closeDrawer(GravityCompat.END);
749             }
750
751             // Close the `Cursor`.
752             bookmarkCursor.close();
753         });
754
755         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
756             // Convert the database ID from `long` to `int`.
757             int databaseId = (int) id;
758
759             // Find out if the selected bookmark is a folder.
760             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
761
762             if (isFolder) {
763                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
764                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
765
766                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
767                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
768                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
769             } else {
770                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
771                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
772                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
773             }
774
775             // Consume the event.
776             return true;
777         });
778
779         // The `DrawerListener` allows us to update the Navigation Menu.
780         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
781             @Override
782             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
783             }
784
785             @Override
786             public void onDrawerOpened(@NonNull View drawerView) {
787             }
788
789             @Override
790             public void onDrawerClosed(@NonNull View drawerView) {
791             }
792
793             @Override
794             public void onDrawerStateChanged(int newState) {
795                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // The drawer is opening or closing.
796                     // Update the `Back`, `Forward`, and `History` menu items.
797                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
798                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
799                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
800
801                     // Hide the keyboard (if displayed) so we can see the navigation menu.  `0` indicates no additional flags.
802                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
803
804                     // Clear the focus from `urlTextBox` if it has it.
805                     urlTextBox.clearFocus();
806                 }
807             }
808         });
809
810         // drawerToggle creates the hamburger icon at the start of the AppBar.
811         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
812
813         // Get a handle for the progress bar.
814         final ProgressBar progressBar = findViewById(R.id.progress_bar);
815
816         mainWebView.setWebChromeClient(new WebChromeClient() {
817             // Update the progress bar when a page is loading.
818             @Override
819             public void onProgressChanged(WebView view, int progress) {
820                 // Inject the night mode CSS if night mode is enabled.
821                 if (nightMode) {
822                     // `background-color: #212121` sets the background to be dark gray.  `color: #BDBDBD` sets the text color to be light gray.  `box-shadow: none` removes a lower underline on links
823                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
824                     // `border: none` removes all borders, which can also be used to underline text.
825                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
826                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
827                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
828                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
829                                 // Initialize a `Handler` to display `mainWebView`.
830                                 Handler displayWebViewHandler = new Handler();
831
832                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
833                                 Runnable displayWebViewRunnable = () -> {
834                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
835                                     if (progressBar.getVisibility() == View.GONE) {
836                                         mainWebView.setVisibility(View.VISIBLE);
837                                     }
838                                 };
839
840                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
841                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
842                             });
843                 }
844
845                 // Update the progress bar.
846                 progressBar.setProgress(progress);
847
848                 // Set the visibility of the progress bar.
849                 if (progress < 100) {
850                     // Show the progress bar.
851                     progressBar.setVisibility(View.VISIBLE);
852                 } else {
853                     // Hide the progress bar.
854                     progressBar.setVisibility(View.GONE);
855
856                     // Display `mainWebView` if night mode is disabled.
857                     // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not
858                     // currently enabled.
859                     if (!nightMode) {
860                         mainWebView.setVisibility(View.VISIBLE);
861                     }
862
863                     //Stop the `SwipeToRefresh` indicator if it is running
864                     swipeRefreshLayout.setRefreshing(false);
865                 }
866             }
867
868             // Set the favorite icon when it changes.
869             @Override
870             public void onReceivedIcon(WebView view, Bitmap icon) {
871                 // Only update the favorite icon if the website has finished loading.
872                 if (progressBar.getVisibility() == View.GONE) {
873                     // Save a copy of the favorite icon.
874                     favoriteIconBitmap = icon;
875
876                     // Place the favorite icon in the appBar.
877                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
878                 }
879             }
880
881             // Save a copy of the title when it changes.
882             @Override
883             public void onReceivedTitle(WebView view, String title) {
884                 // Save a copy of the title.
885                 webViewTitle = title;
886             }
887
888             // Enter full screen video
889             @Override
890             public void onShowCustomView(View view, CustomViewCallback callback) {
891                 // Pause the ad if this is the free flavor.
892                 if (BuildConfig.FLAVOR.contentEquals("free")) {
893                     BannerAd.pauseAd(adView);
894                 }
895
896                 // Remove the translucent overlays.
897                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
898
899                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
900                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
901
902                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
903                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
904                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
905                  */
906                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
907
908                 // Set `rootCoordinatorLayout` to fill the entire screen.
909                 rootCoordinatorLayout.setFitsSystemWindows(false);
910
911                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
912                 fullScreenVideoFrameLayout.addView(view);
913                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
914             }
915
916             // Exit full screen video
917             public void onHideCustomView() {
918                 // Hide `fullScreenVideoFrameLayout`.
919                 fullScreenVideoFrameLayout.removeAllViews();
920                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
921
922                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
923                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
924
925                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
926                 rootCoordinatorLayout.setFitsSystemWindows(true);
927
928                 // Show the ad if this is the free flavor.
929                 if (BuildConfig.FLAVOR.contentEquals("free")) {
930                     // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
931                     BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
932
933                     // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
934                     adView = findViewById(R.id.adview);
935                 }
936             }
937         });
938
939         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
940         registerForContextMenu(mainWebView);
941
942         // Allow the downloading of files.
943         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
944             // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
945             AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
946             downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
947         });
948
949         // Allow pinch to zoom.
950         mainWebView.getSettings().setBuiltInZoomControls(true);
951
952         // Hide zoom controls.
953         mainWebView.getSettings().setDisplayZoomControls(false);
954
955         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
956         mainWebView.getSettings().setUseWideViewPort(true);
957
958         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
959         mainWebView.getSettings().setLoadWithOverviewMode(true);
960
961         // Explicitly disable geolocation.
962         mainWebView.getSettings().setGeolocationEnabled(false);
963
964         // Initialize cookieManager.
965         cookieManager = CookieManager.getInstance();
966
967         // 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).
968         customHeaders.put("X-Requested-With", "");
969
970         // 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.
971         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
972
973         // Get the intent that started the app.
974         final Intent launchingIntent = getIntent();
975
976         // Extract the launching intent data as `launchingIntentUriData`.
977         final Uri launchingIntentUriData = launchingIntent.getData();
978
979         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
980         if (launchingIntentUriData != null) {
981             formattedUrlString = launchingIntentUriData.toString();
982         }
983
984         // Get a handle for the `Runtime`.
985         privacyBrowserRuntime = Runtime.getRuntime();
986
987         // Store the application's private data directory.
988         privateDataDirectoryString = getApplicationInfo().dataDir;
989         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
990
991         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
992         inFullScreenBrowsingMode = false;
993
994         // Initialize AdView for the free flavor.
995         adView = findViewById(R.id.adview);
996
997         // Initialize the privacy settings variables.
998         javaScriptEnabled = false;
999         firstPartyCookiesEnabled = false;
1000         thirdPartyCookiesEnabled = false;
1001         domStorageEnabled = false;
1002         saveFormDataEnabled = false;
1003         nightMode = false;
1004
1005         // Initialize `webViewTitle`.
1006         webViewTitle = getString(R.string.no_title);
1007
1008         // Initialize `favoriteIconBitmap`.  `ContextCompat` must be used until API >= 21.
1009         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1010         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1011         assert favoriteIconBitmapDrawable != null;
1012         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1013
1014         // If the favorite icon is null, load the default.
1015         if (favoriteIconBitmap == null) {
1016             favoriteIconBitmap = favoriteIconDefaultBitmap;
1017         }
1018
1019         // Apply the app settings from the shared preferences.
1020         applyAppSettings();
1021
1022         // Instantiate the block list helper.
1023         BlockListHelper blockListHelper = new BlockListHelper();
1024
1025         // Parse the block lists.
1026         final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1027         final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1028         final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1029         final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1030
1031         // Store the list versions.
1032         easyListVersion = easyList.get(0).get(0)[0];
1033         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1034         fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1035         fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1036
1037         mainWebView.setWebViewClient(new WebViewClient() {
1038             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1039             // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
1040             @SuppressWarnings("deprecation")
1041             @Override
1042             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1043                 if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1044                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1045                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1046
1047                     // Parse the url and set it as the data for the `Intent`.
1048                     emailIntent.setData(Uri.parse(url));
1049
1050                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1051                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1052
1053                     // Make it so.
1054                     startActivity(emailIntent);
1055
1056                     // Returning `true` indicates the application is handling the URL.
1057                     return true;
1058                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1059                     // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
1060                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1061
1062                     // Add the phone number to the intent.
1063                     dialIntent.setData(Uri.parse(url));
1064
1065                     // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
1066                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1067
1068                     // Make it so.
1069                     startActivity(dialIntent);
1070
1071                     // Returning `true` indicates the application is handling the URL.
1072                     return true;
1073                 } else {  // Load the URL in Privacy Browser.
1074                     // Apply the domain settings for the new URL.
1075                     applyDomainSettings(url);
1076
1077                     // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1078                     return false;
1079                 }
1080             }
1081
1082             // Check requests against the block lists.  The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1083             @SuppressWarnings("deprecation")
1084             @Override
1085             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1086                 // Create an empty web resource response to be used if the resource request is blocked.
1087                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1088
1089                 // Check EasyList if it is enabled.
1090                 if (easyListEnabled) {
1091                     if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1092                         // The resource request was blocked.  Return an empty web resource response.
1093                         return emptyWebResourceResponse;
1094                     }
1095                 }
1096
1097                 // Check EasyPrivacy if it is enabled.
1098                 if (easyPrivacyEnabled) {
1099                     if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1100                         // The resource request was blocked.  Return an empty web resource response.
1101                         return emptyWebResourceResponse;
1102                     }
1103                 }
1104
1105                 // Check Fanboy’s Annoyance List if it is enabled.
1106                 if (fanboyAnnoyanceListEnabled) {
1107                     if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1108                         // The resource request was blocked.  Return an empty web resource response.
1109                         return emptyWebResourceResponse;
1110                     }
1111                 } else if (fanboySocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1112                     if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1113                         // The resource request was blocked.  Return an empty web resource response.
1114                         return emptyWebResourceResponse;
1115                     }
1116                 }
1117
1118                 // The resource request has not been blocked.  `return null` loads the requested resource.
1119                 return null;
1120             }
1121
1122             // Handle HTTP authentication requests.
1123             @Override
1124             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1125                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1126                 httpAuthHandler = handler;
1127
1128                 // Display the HTTP authentication dialog.
1129                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1130                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1131             }
1132
1133             // Update the URL in urlTextBox when the page starts to load.
1134             @Override
1135             public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1136                 if (nightMode) {
1137                     mainWebView.setVisibility(View.INVISIBLE);
1138                 }
1139
1140                 // Hide the keyboard.  `0` indicates no additional flags.
1141                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1142
1143                 // Check to see if we are waiting on Orbot.
1144                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1145                     // 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.
1146                     formattedUrlString = url;
1147
1148                     // Display the formatted URL text.
1149                     urlTextBox.setText(formattedUrlString);
1150
1151                     // Apply text highlighting to `urlTextBox`.
1152                     highlightUrlText();
1153
1154                     // Apply any custom domain settings if the URL was loaded by navigating history.
1155                     if (navigatingHistory) {
1156                         applyDomainSettings(url);
1157                     }
1158
1159                     // Set `urlIsLoading` to `true`, so that redirects while loading do not trigger changes in the user agent, which forces another reload of the existing page.
1160                     urlIsLoading = true;
1161                 }
1162             }
1163
1164             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1165             @Override
1166             public void onPageFinished(WebView view, String url) {
1167                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1168                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1169                     cookieManager.flush();
1170                 }
1171
1172                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1173                 urlIsLoading = false;
1174
1175                 // Clear the cache and history if Incognito Mode is enabled.
1176                 if (incognitoModeEnabled) {
1177                     // Clear the cache.  `true` includes disk files.
1178                     mainWebView.clearCache(true);
1179
1180                     // Clear the back/forward history.
1181                     mainWebView.clearHistory();
1182
1183                     // Manually delete cache folders.
1184                     try {
1185                         // Delete the main `cache` folder.
1186                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1187
1188                         // 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`.
1189                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1190                     } catch (IOException e) {
1191                         // Do nothing if an error is thrown.
1192                     }
1193                 }
1194
1195                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1196                 if (!waitingForOrbot) {
1197                     // Check to see if `WebView` has set `url` to be `about:blank`.
1198                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1199                         // Set `formattedUrlString` to `""`.
1200                         formattedUrlString = "";
1201
1202                         urlTextBox.setText(formattedUrlString);
1203
1204                         // Request focus for `urlTextBox`.
1205                         urlTextBox.requestFocus();
1206
1207                         // Display the keyboard.
1208                         inputMethodManager.showSoftInput(urlTextBox, 0);
1209
1210                         // Apply the domain settings.  This clears any settings from the previous domain.
1211                         applyDomainSettings(formattedUrlString);
1212                     } else {  // `WebView` has loaded a webpage.
1213                         // Set `formattedUrlString`.
1214                         formattedUrlString = url;
1215
1216                         // Only update `urlTextBox` if the user is not typing in it.
1217                         if (!urlTextBox.hasFocus()) {
1218                             // Display the formatted URL text.
1219                             urlTextBox.setText(formattedUrlString);
1220
1221                             // Apply text highlighting to `urlTextBox`.
1222                             highlightUrlText();
1223                         }
1224                     }
1225
1226                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1227                     sslCertificate = mainWebView.getCertificate();
1228
1229                     // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
1230                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1231                         // Initialize the current SSL certificate variables.
1232                         String currentWebsiteIssuedToCName = "";
1233                         String currentWebsiteIssuedToOName = "";
1234                         String currentWebsiteIssuedToUName = "";
1235                         String currentWebsiteIssuedByCName = "";
1236                         String currentWebsiteIssuedByOName = "";
1237                         String currentWebsiteIssuedByUName = "";
1238                         Date currentWebsiteSslStartDate = null;
1239                         Date currentWebsiteSslEndDate = null;
1240
1241
1242                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1243                         if (sslCertificate != null) {
1244                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1245                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1246                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1247                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1248                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1249                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1250                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1251                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1252                         }
1253
1254                         // Initialize `String` variables to store the SSL certificate dates.  `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
1255                         String currentWebsiteSslStartDateString = "";
1256                         String currentWebsiteSslEndDateString = "";
1257                         String pinnedDomainSslStartDateString = "";
1258                         String pinnedDomainSslEndDateString = "";
1259
1260                         // Convert the `Dates` to `Strings` if they are not `null`.
1261                         if (currentWebsiteSslStartDate != null) {
1262                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1263                         }
1264
1265                         if (currentWebsiteSslEndDate != null) {
1266                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1267                         }
1268
1269                         if (pinnedDomainSslStartDate != null) {
1270                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1271                         }
1272
1273                         if (pinnedDomainSslEndDate != null) {
1274                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1275                         }
1276
1277                         // Check to see if the pinned SSL certificate matches the current website certificate.
1278                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1279                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1280                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1281                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1282                             // The pinned SSL certificate doesn't match the current domain certificate.
1283                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1284                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1285                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1286                         }
1287                     }
1288                 }
1289             }
1290
1291             // Handle SSL Certificate errors.
1292             @Override
1293             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1294                 // Get the current website SSL certificate.
1295                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1296
1297                 // Extract the individual pieces of information from the current website SSL certificate.
1298                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1299                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1300                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1301                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1302                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1303                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1304                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1305                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1306
1307                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1308                 if (pinnedDomainSslCertificate &&
1309                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1310                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1311                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1312                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1313                     // An SSL certificate is pinned and matches the current domain certificate.
1314                     // Proceed to the website without displaying an error.
1315                     handler.proceed();
1316                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1317                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1318                     sslErrorHandler = handler;
1319
1320                     // Display the SSL error `AlertDialog`.
1321                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1322                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1323                 }
1324             }
1325         });
1326
1327         // Load the website if not waiting for Orbot to connect.
1328         if (!waitingForOrbot) {
1329             loadUrl(formattedUrlString);
1330         }
1331     }
1332
1333     @Override
1334     protected void onNewIntent(Intent intent) {
1335         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1336         setIntent(intent);
1337
1338         // Check to see if the intent contains a new URL.
1339         if (intent.getData() != null) {
1340             // Get the intent data and convert it to a string.
1341             final Uri intentUriData = intent.getData();
1342             formattedUrlString = intentUriData.toString();
1343
1344             // Load the website.
1345             loadUrl(formattedUrlString);
1346
1347             // Close the navigation drawer if it is open.
1348             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1349                 drawerLayout.closeDrawer(GravityCompat.START);
1350             }
1351
1352             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1353             mainWebView.requestFocus();
1354         }
1355     }
1356
1357     @Override
1358     public void onRestart() {
1359         // Run the default commands.
1360         super.onRestart();
1361
1362         // Apply the app settings if returning from the Settings activity..
1363         if (returnFromSettings) {
1364             // Reset the return from settings flag.
1365             returnFromSettings = false;
1366
1367             // Apply the app settings.
1368             applyAppSettings();
1369
1370             // Set the display webpage images mode.
1371             setDisplayWebpageImages();
1372         }
1373
1374         // Reload the webpage if displaying of images has been disabled in the Settings activity.
1375         if (reloadOnRestart) {
1376             // Reload `mainWebView`.
1377             mainWebView.reload();
1378
1379             // Reset `reloadOnRestartBoolean`.
1380             reloadOnRestart = false;
1381         }
1382
1383         // Apply the domain settings if returning from the Domains activity.
1384         if (reapplyDomainSettingsOnRestart) {
1385             // Reset `reapplyDomainSettingsOnRestart`.
1386             reapplyDomainSettingsOnRestart = false;
1387
1388             // Reapply the domain settings.
1389             applyDomainSettings(formattedUrlString);
1390         }
1391
1392         // Load the URL on restart to apply changes to night mode.
1393         if (loadUrlOnRestart) {
1394             // Load the current `formattedUrlString`.
1395             loadUrl(formattedUrlString);
1396
1397             // Reset `loadUrlOnRestart.
1398             loadUrlOnRestart = false;
1399         }
1400
1401         // Update the bookmarks drawer if returning from the Bookmarks activity.
1402         if (restartFromBookmarksActivity) {
1403             // Close the bookmarks drawer.
1404             drawerLayout.closeDrawer(GravityCompat.END);
1405
1406             // Reload the bookmarks drawer.
1407             loadBookmarksFolder();
1408
1409             // Reset `restartFromBookmarksActivity`.
1410             restartFromBookmarksActivity = false;
1411         }
1412
1413         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1414         updatePrivacyIcons(true);
1415     }
1416
1417     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1418     @Override
1419     public void onResume() {
1420         // Run the default commands.
1421         super.onResume();
1422
1423         // Resume JavaScript (if enabled).
1424         mainWebView.resumeTimers();
1425
1426         // Resume `mainWebView`.
1427         mainWebView.onResume();
1428
1429         // Resume the adView for the free flavor.
1430         if (BuildConfig.FLAVOR.contentEquals("free")) {
1431             BannerAd.resumeAd(adView);
1432         }
1433     }
1434
1435     @Override
1436     public void onPause() {
1437         // Pause `mainWebView`.
1438         mainWebView.onPause();
1439
1440         // Stop all JavaScript.
1441         mainWebView.pauseTimers();
1442
1443         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1444         if (BuildConfig.FLAVOR.contentEquals("free")) {
1445             BannerAd.pauseAd(adView);
1446         }
1447
1448         super.onPause();
1449     }
1450
1451     @Override
1452     public boolean onCreateOptionsMenu(Menu menu) {
1453         // Inflate the menu; this adds items to the action bar if it is present.
1454         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1455
1456         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1457         mainMenu = menu;
1458
1459         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1460         updatePrivacyIcons(false);
1461
1462         // Get handles for the menu items.
1463         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1464         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1465         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1466         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1467
1468         // Only display third-party cookies if SDK >= 21
1469         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1470
1471         // Get the shared preference values.  `this` references the current context.
1472         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1473
1474         // Set the status of the additional app bar icons.  The default is `false`.
1475         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1476             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1477             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1478             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1479         } else { //Do not display the additional icons.
1480             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1481             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1482             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1483         }
1484
1485         return true;
1486     }
1487
1488     @Override
1489     public boolean onPrepareOptionsMenu(Menu menu) {
1490         // Get handles for the menu items.
1491         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1492         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1493         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1494         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1495         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1496         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1497         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1498         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1499         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1500         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1501         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1502         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1503
1504         // Set the text for the domain menu item.
1505         if (domainSettingsApplied) {
1506             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1507         } else {
1508             addOrEditDomain.setTitle(R.string.add_domain_settings);
1509         }
1510
1511         // Set the status of the menu item checkboxes.
1512         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1513         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1514         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1515         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1516         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1517
1518         // Enable third-party cookies if first-party cookies are enabled.
1519         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1520
1521         // Enable `DOM Storage` if JavaScript is enabled.
1522         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1523
1524         // Enable `Clear Cookies` if there are any.
1525         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1526
1527         // Get a count of the number of files in the `Local Storage` directory.
1528         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1529         int localStorageDirectoryNumberOfFiles = 0;
1530         if (localStorageDirectory.exists()) {
1531             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1532         }
1533
1534         // Get a count of the number of files in the `IndexedDB` directory.
1535         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1536         int indexedDBDirectoryNumberOfFiles = 0;
1537         if (indexedDBDirectory.exists()) {
1538             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1539         }
1540
1541         // Enable `Clear DOM Storage` if there is any.
1542         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1543
1544         // Enable `Clear Form Data` is there is any.
1545         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1546         clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1547
1548         // Enable `Clear Data` if any of the submenu items are enabled.
1549         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1550
1551         // Initialize font size variables.
1552         int fontSize = mainWebView.getSettings().getTextZoom();
1553         String fontSizeTitle;
1554         MenuItem selectedFontSizeMenuItem;
1555
1556         // Prepare the font size title and current size menu item.
1557         switch (fontSize) {
1558             case 25:
1559                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1560                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1561                 break;
1562
1563             case 50:
1564                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1565                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1566                 break;
1567
1568             case 75:
1569                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1570                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1571                 break;
1572
1573             case 100:
1574                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1575                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1576                 break;
1577
1578             case 125:
1579                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1580                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1581                 break;
1582
1583             case 150:
1584                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1585                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1586                 break;
1587
1588             case 175:
1589                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1590                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1591                 break;
1592
1593             case 200:
1594                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1595                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1596                 break;
1597
1598             default:
1599                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1600                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1601                 break;
1602         }
1603
1604         // Set the font size title and select the current size menu item.
1605         fontSizeMenuItem.setTitle(fontSizeTitle);
1606         selectedFontSizeMenuItem.setChecked(true);
1607
1608         // Only show `Refresh` if `swipeToRefresh` is disabled.
1609         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1610
1611         // Run all the other default commands.
1612         super.onPrepareOptionsMenu(menu);
1613
1614         // Display the menu.
1615         return true;
1616     }
1617
1618     @Override
1619     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1620     @SuppressLint("SetJavaScriptEnabled")
1621     // removeAllCookies is deprecated, but it is required for API < 21.
1622     @SuppressWarnings("deprecation")
1623     public boolean onOptionsItemSelected(MenuItem menuItem) {
1624         // Get the selected menu item ID.
1625         int menuItemId = menuItem.getItemId();
1626
1627         // Set the commands that relate to the menu entries.
1628         switch (menuItemId) {
1629             case R.id.add_or_edit_domain:
1630                 if (domainSettingsApplied) {  // Edit the current domain settings.
1631                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1632                     reapplyDomainSettingsOnRestart = true;
1633                     currentDomainName = "";
1634
1635                     // Create an intent to launch the domains activity.
1636                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1637
1638                     // Put extra information instructing the domains activity to directly load the current domain.
1639                     domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1640
1641                     // Make it so.
1642                     startActivity(domainsIntent);
1643                 } else {  // Add a new domain.
1644                     // Show the add domain `AlertDialog`.
1645                     AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1646                     addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1647                 }
1648                 return true;
1649
1650             case R.id.toggle_javascript:
1651                 // Switch the status of javaScriptEnabled.
1652                 javaScriptEnabled = !javaScriptEnabled;
1653
1654                 // Apply the new JavaScript status.
1655                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1656
1657                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1658                 updatePrivacyIcons(true);
1659
1660                 // Display a `Snackbar`.
1661                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1662                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1663                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1664                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1665                 } else {  // Privacy mode.
1666                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1667                 }
1668
1669                 // Reload the WebView.
1670                 mainWebView.reload();
1671                 return true;
1672
1673             case R.id.toggle_first_party_cookies:
1674                 // Switch the status of firstPartyCookiesEnabled.
1675                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1676
1677                 // Update the menu checkbox.
1678                 menuItem.setChecked(firstPartyCookiesEnabled);
1679
1680                 // Apply the new cookie status.
1681                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1682
1683                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1684                 updatePrivacyIcons(true);
1685
1686                 // Display a `Snackbar`.
1687                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1688                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1689                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
1690                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1691                 } else {  // Privacy mode.
1692                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1693                 }
1694
1695                 // Reload the WebView.
1696                 mainWebView.reload();
1697                 return true;
1698
1699             case R.id.toggle_third_party_cookies:
1700                 if (Build.VERSION.SDK_INT >= 21) {
1701                     // Switch the status of thirdPartyCookiesEnabled.
1702                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1703
1704                     // Update the menu checkbox.
1705                     menuItem.setChecked(thirdPartyCookiesEnabled);
1706
1707                     // Apply the new cookie status.
1708                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1709
1710                     // Display a `Snackbar`.
1711                     if (thirdPartyCookiesEnabled) {
1712                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1713                     } else {
1714                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1715                     }
1716
1717                     // Reload the WebView.
1718                     mainWebView.reload();
1719                 } // Else do nothing because SDK < 21.
1720                 return true;
1721
1722             case R.id.toggle_dom_storage:
1723                 // Switch the status of domStorageEnabled.
1724                 domStorageEnabled = !domStorageEnabled;
1725
1726                 // Update the menu checkbox.
1727                 menuItem.setChecked(domStorageEnabled);
1728
1729                 // Apply the new DOM Storage status.
1730                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1731
1732                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1733                 updatePrivacyIcons(true);
1734
1735                 // Display a `Snackbar`.
1736                 if (domStorageEnabled) {
1737                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1738                 } else {
1739                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1740                 }
1741
1742                 // Reload the WebView.
1743                 mainWebView.reload();
1744                 return true;
1745
1746             case R.id.toggle_save_form_data:
1747                 // Switch the status of saveFormDataEnabled.
1748                 saveFormDataEnabled = !saveFormDataEnabled;
1749
1750                 // Update the menu checkbox.
1751                 menuItem.setChecked(saveFormDataEnabled);
1752
1753                 // Apply the new form data status.
1754                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1755
1756                 // Display a `Snackbar`.
1757                 if (saveFormDataEnabled) {
1758                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1759                 } else {
1760                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1761                 }
1762
1763                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1764                 updatePrivacyIcons(true);
1765
1766                 // Reload the WebView.
1767                 mainWebView.reload();
1768                 return true;
1769
1770             case R.id.clear_cookies:
1771                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1772                         .setAction(R.string.undo, v -> {
1773                             // Do nothing because everything will be handled by `onDismissed()` below.
1774                         })
1775                         .addCallback(new Snackbar.Callback() {
1776                             @Override
1777                             public void onDismissed(Snackbar snackbar, int event) {
1778                                 switch (event) {
1779                                     // The user pushed the `Undo` button.
1780                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1781                                         // Do nothing.
1782                                         break;
1783
1784                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1785                                     default:
1786                                         // `cookieManager.removeAllCookie()` varies by SDK.
1787                                         if (Build.VERSION.SDK_INT < 21) {
1788                                             cookieManager.removeAllCookie();
1789                                         } else {
1790                                             // `null` indicates no callback.
1791                                             cookieManager.removeAllCookies(null);
1792                                         }
1793                                 }
1794                             }
1795                         })
1796                         .show();
1797                 return true;
1798
1799             case R.id.clear_dom_storage:
1800                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1801                         .setAction(R.string.undo, v -> {
1802                             // Do nothing because everything will be handled by `onDismissed()` below.
1803                         })
1804                         .addCallback(new Snackbar.Callback() {
1805                             @Override
1806                             public void onDismissed(Snackbar snackbar, int event) {
1807                                 switch (event) {
1808                                     // The user pushed the `Undo` button.
1809                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1810                                         // Do nothing.
1811                                         break;
1812
1813                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1814                                     default:
1815                                         // Delete the DOM Storage.
1816                                         WebStorage webStorage = WebStorage.getInstance();
1817                                         webStorage.deleteAllData();
1818
1819                                         // Manually delete the DOM storage files and directories.
1820                                         try {
1821                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1822                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1823
1824                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1825                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1826                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1827                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1828                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1829                                         } catch (IOException e) {
1830                                             // Do nothing if an error is thrown.
1831                                         }
1832                                 }
1833                             }
1834                         })
1835                         .show();
1836                 return true;
1837
1838             case R.id.clear_form_data:
1839                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1840                         .setAction(R.string.undo, v -> {
1841                             // Do nothing because everything will be handled by `onDismissed()` below.
1842                         })
1843                         .addCallback(new Snackbar.Callback() {
1844                             @Override
1845                             public void onDismissed(Snackbar snackbar, int event) {
1846                                 switch (event) {
1847                                     // The user pushed the `Undo` button.
1848                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1849                                         // Do nothing.
1850                                         break;
1851
1852                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1853                                     default:
1854                                         // Delete the form data.
1855                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1856                                         mainWebViewDatabase.clearFormData();
1857                                 }
1858                             }
1859                         })
1860                         .show();
1861                 return true;
1862
1863             case R.id.font_size_twenty_five_percent:
1864                 mainWebView.getSettings().setTextZoom(25);
1865                 return true;
1866
1867             case R.id.font_size_fifty_percent:
1868                 mainWebView.getSettings().setTextZoom(50);
1869                 return true;
1870
1871             case R.id.font_size_seventy_five_percent:
1872                 mainWebView.getSettings().setTextZoom(75);
1873                 return true;
1874
1875             case R.id.font_size_one_hundred_percent:
1876                 mainWebView.getSettings().setTextZoom(100);
1877                 return true;
1878
1879             case R.id.font_size_one_hundred_twenty_five_percent:
1880                 mainWebView.getSettings().setTextZoom(125);
1881                 return true;
1882
1883             case R.id.font_size_one_hundred_fifty_percent:
1884                 mainWebView.getSettings().setTextZoom(150);
1885                 return true;
1886
1887             case R.id.font_size_one_hundred_seventy_five_percent:
1888                 mainWebView.getSettings().setTextZoom(175);
1889                 return true;
1890
1891             case R.id.font_size_two_hundred_percent:
1892                 mainWebView.getSettings().setTextZoom(200);
1893                 return true;
1894
1895             case R.id.display_images:
1896                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1897                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
1898                     mainWebView.reload();
1899                 } else {  // Images are not currently loaded automatically.
1900                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
1901                 }
1902
1903                 // Set `onTheFlyDisplayImagesSet`.
1904                 onTheFlyDisplayImagesSet = true;
1905                 return true;
1906
1907             case R.id.share:
1908                 // Setup the share string.
1909                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1910
1911                 // Create the share intent.
1912                 Intent shareIntent = new Intent();
1913                 shareIntent.setAction(Intent.ACTION_SEND);
1914                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1915                 shareIntent.setType("text/plain");
1916
1917                 // Make it so.
1918                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1919                 return true;
1920
1921             case R.id.find_on_page:
1922                 // Hide the URL app bar.
1923                 supportAppBar.setVisibility(View.GONE);
1924
1925                 // Show the Find on Page `RelativeLayout`.
1926                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1927
1928                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
1929                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1930                 findOnPageEditText.postDelayed(() -> {
1931                     // Set the focus on `findOnPageEditText`.
1932                     findOnPageEditText.requestFocus();
1933
1934                     // Display the keyboard.  `0` sets no input flags.
1935                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
1936                 }, 200);
1937                 return true;
1938
1939             case R.id.print:
1940                 // Get a `PrintManager` instance.
1941                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1942
1943                 // Convert `mainWebView` to `printDocumentAdapter`.
1944                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1945
1946                 // Remove the lint error below that `printManager` might be `null`.
1947                 assert printManager != null;
1948
1949                 // Print the document.  The print attributes are `null`.
1950                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1951                 return true;
1952
1953             case R.id.view_source:
1954                 // Launch the Vew Source activity.
1955                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1956                 startActivity(viewSourceIntent);
1957                 return true;
1958
1959             case R.id.add_to_homescreen:
1960                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1961                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1962                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1963
1964                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1965                 return true;
1966
1967             case R.id.refresh:
1968                 mainWebView.reload();
1969                 return true;
1970
1971             default:
1972                 // Don't consume the event.
1973                 return super.onOptionsItemSelected(menuItem);
1974         }
1975     }
1976
1977     // removeAllCookies is deprecated, but it is required for API < 21.
1978     @SuppressWarnings("deprecation")
1979     @Override
1980     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1981         int menuItemId = menuItem.getItemId();
1982
1983         switch (menuItemId) {
1984             case R.id.home:
1985                 loadUrl(homepage);
1986                 break;
1987
1988             case R.id.back:
1989                 if (mainWebView.canGoBack()) {
1990                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1991                     navigatingHistory = true;
1992
1993                     // Load the previous website in the history.
1994                     mainWebView.goBack();
1995                 }
1996                 break;
1997
1998             case R.id.forward:
1999                 if (mainWebView.canGoForward()) {
2000                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2001                     navigatingHistory = true;
2002
2003                     // Load the next website in the history.
2004                     mainWebView.goForward();
2005                 }
2006                 break;
2007
2008             case R.id.history:
2009                 // Get the `WebBackForwardList`.
2010                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2011
2012                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2013                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2014                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2015                 break;
2016
2017             case R.id.downloads:
2018                 // Launch the system Download Manager.
2019                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2020
2021                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2022                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2023
2024                 startActivity(downloadManagerIntent);
2025                 break;
2026
2027             case R.id.domains:
2028                 // Reapply the domain settings on returning to `MainWebViewActivity`.
2029                 reapplyDomainSettingsOnRestart = true;
2030                 currentDomainName = "";
2031
2032                 // Launch `DomainsActivity`.
2033                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2034                 startActivity(domainsIntent);
2035                 break;
2036
2037             case R.id.settings:
2038                 // Reapply the domain settings on returning to `MainWebViewActivity`.
2039                 reapplyDomainSettingsOnRestart = true;
2040                 currentDomainName = "";
2041
2042                 // Mark a flag to reapply app settings on restart only when returning from Settings.
2043                 returnFromSettings = true;
2044
2045                 // Launch `SettingsActivity`.
2046                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2047                 startActivity(settingsIntent);
2048                 break;
2049
2050             case R.id.guide:
2051                 // Launch `GuideActivity`.
2052                 Intent guideIntent = new Intent(this, GuideActivity.class);
2053                 startActivity(guideIntent);
2054                 break;
2055
2056             case R.id.about:
2057                 // Launch `AboutActivity`.
2058                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2059                 startActivity(aboutIntent);
2060                 break;
2061
2062             case R.id.clearAndExit:
2063                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2064                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2065
2066                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2067
2068                 // Clear cookies.
2069                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2070                     // The command to remove cookies changed slightly in API 21.
2071                     if (Build.VERSION.SDK_INT >= 21) {
2072                         cookieManager.removeAllCookies(null);
2073                     } else {
2074                         cookieManager.removeAllCookie();
2075                     }
2076
2077                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2078                     try {
2079                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2080                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2081                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2082                     } catch (IOException e) {
2083                         // Do nothing if an error is thrown.
2084                     }
2085                 }
2086
2087                 // Clear DOM storage.
2088                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2089                     // Ask `WebStorage` to clear the DOM storage.
2090                     WebStorage webStorage = WebStorage.getInstance();
2091                     webStorage.deleteAllData();
2092
2093                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2094                     try {
2095                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2096                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2097
2098                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2099                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2100                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2101                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2102                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2103                     } catch (IOException e) {
2104                         // Do nothing if an error is thrown.
2105                     }
2106                 }
2107
2108                 // Clear form data.
2109                 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2110                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2111                     webViewDatabase.clearFormData();
2112
2113                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2114                     try {
2115                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2116                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2117                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2118                     } catch (IOException e) {
2119                         // Do nothing if an error is thrown.
2120                     }
2121                 }
2122
2123                 // Clear the cache.
2124                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2125                     // `true` includes disk files.
2126                     mainWebView.clearCache(true);
2127
2128                     // Manually delete the cache directories.
2129                     try {
2130                         // Delete the main cache directory.
2131                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2132                         // Delete the secondary `Service Worker` cache directory.
2133                         // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2134                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2135                     } catch (IOException e) {
2136                         // Do nothing if an error is thrown.
2137                     }
2138                 }
2139
2140                 // Clear SSL certificate preferences.
2141                 mainWebView.clearSslPreferences();
2142
2143                 // Clear the back/forward history.
2144                 mainWebView.clearHistory();
2145
2146                 // Clear `formattedUrlString`.
2147                 formattedUrlString = null;
2148
2149                 // Clear `customHeaders`.
2150                 customHeaders.clear();
2151
2152                 // Detach all views from `mainWebViewRelativeLayout`.
2153                 mainWebViewRelativeLayout.removeAllViews();
2154
2155                 // Destroy the internal state of `mainWebView`.
2156                 mainWebView.destroy();
2157
2158                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2159                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2160                 if (clearEverything) {
2161                     try {
2162                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2163                     } catch (IOException e) {
2164                         // Do nothing if an error is thrown.
2165                     }
2166                 }
2167
2168                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2169                 if (Build.VERSION.SDK_INT >= 21) {
2170                     finishAndRemoveTask();
2171                 } else {
2172                     finish();
2173                 }
2174
2175                 // Remove the terminated program from RAM.  The status code is `0`.
2176                 System.exit(0);
2177                 break;
2178         }
2179
2180         // Close the navigation drawer.
2181         drawerLayout.closeDrawer(GravityCompat.START);
2182         return true;
2183     }
2184
2185     @Override
2186     public void onPostCreate(Bundle savedInstanceState) {
2187         super.onPostCreate(savedInstanceState);
2188
2189         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2190         drawerToggle.syncState();
2191     }
2192
2193     @Override
2194     public void onConfigurationChanged(Configuration newConfig) {
2195         super.onConfigurationChanged(newConfig);
2196
2197         // Reload the ad for the free flavor if we are not in full screen mode.
2198         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2199             // Reload the ad.
2200             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2201
2202             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2203             adView = findViewById(R.id.adview);
2204         }
2205
2206         // `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:
2207         // https://code.google.com/p/android/issues/detail?id=20493#c8
2208         // ActivityCompat.invalidateOptionsMenu(this);
2209     }
2210
2211     @Override
2212     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2213         // Store the `HitTestResult`.
2214         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2215
2216         // Create strings.
2217         final String imageUrl;
2218         final String linkUrl;
2219
2220         // Get a handle for the `ClipboardManager`.
2221         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2222
2223         // Remove the lint errors below that `clipboardManager` might be `null`.
2224         assert clipboardManager != null;
2225
2226         switch (hitTestResult.getType()) {
2227             // `SRC_ANCHOR_TYPE` is a link.
2228             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2229                 // Get the target URL.
2230                 linkUrl = hitTestResult.getExtra();
2231
2232                 // Set the target URL as the title of the `ContextMenu`.
2233                 menu.setHeaderTitle(linkUrl);
2234
2235                 // Add a `Load URL` entry.
2236                 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2237                     loadUrl(linkUrl);
2238                     return false;
2239                 });
2240
2241                 // Add a `Copy URL` entry.
2242                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2243                     // Save the link URL in a `ClipData`.
2244                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2245
2246                     // Set the `ClipData` as the clipboard's primary clip.
2247                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2248                     return false;
2249                 });
2250
2251                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2252                 menu.add(R.string.cancel);
2253                 break;
2254
2255             case WebView.HitTestResult.EMAIL_TYPE:
2256                 // Get the target URL.
2257                 linkUrl = hitTestResult.getExtra();
2258
2259                 // Set the target URL as the title of the `ContextMenu`.
2260                 menu.setHeaderTitle(linkUrl);
2261
2262                 // Add a `Write Email` entry.
2263                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2264                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2265                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2266
2267                     // Parse the url and set it as the data for the `Intent`.
2268                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2269
2270                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2271                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2272
2273                     // Make it so.
2274                     startActivity(emailIntent);
2275                     return false;
2276                 });
2277
2278                 // Add a `Copy Email Address` entry.
2279                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2280                     // Save the email address in a `ClipData`.
2281                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2282
2283                     // Set the `ClipData` as the clipboard's primary clip.
2284                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2285                     return false;
2286                 });
2287
2288                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2289                 menu.add(R.string.cancel);
2290                 break;
2291
2292             // `IMAGE_TYPE` is an image.
2293             case WebView.HitTestResult.IMAGE_TYPE:
2294                 // Get the image URL.
2295                 imageUrl = hitTestResult.getExtra();
2296
2297                 // Set the image URL as the title of the `ContextMenu`.
2298                 menu.setHeaderTitle(imageUrl);
2299
2300                 // Add a `View Image` entry.
2301                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2302                     loadUrl(imageUrl);
2303                     return false;
2304                 });
2305
2306                 // Add a `Download Image` entry.
2307                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2308                     // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2309                     AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2310                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2311                     return false;
2312                 });
2313
2314                 // Add a `Copy URL` entry.
2315                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2316                     // Save the image URL in a `ClipData`.
2317                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2318
2319                     // Set the `ClipData` as the clipboard's primary clip.
2320                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
2321                     return false;
2322                 });
2323
2324                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2325                 menu.add(R.string.cancel);
2326                 break;
2327
2328
2329             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2330             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2331                 // Get the image URL.
2332                 imageUrl = hitTestResult.getExtra();
2333
2334                 // Set the image URL as the title of the `ContextMenu`.
2335                 menu.setHeaderTitle(imageUrl);
2336
2337                 // Add a `View Image` entry.
2338                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2339                     loadUrl(imageUrl);
2340                     return false;
2341                 });
2342
2343                 // Add a `Download Image` entry.
2344                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2345                     // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2346                     AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2347                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2348                     return false;
2349                 });
2350
2351                 // Add a `Copy URL` entry.
2352                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2353                     // Save the image URL in a `ClipData`.
2354                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2355
2356                     // Set the `ClipData` as the clipboard's primary clip.
2357                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2358                     return false;
2359                 });
2360
2361                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2362                 menu.add(R.string.cancel);
2363                 break;
2364         }
2365     }
2366
2367     @Override
2368     public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2369         // Reapply the domain settings on returning to `MainWebViewActivity`.
2370         reapplyDomainSettingsOnRestart = true;
2371         currentDomainName = "";
2372
2373         // Get the new domain name `String` from `dialogFragment`.
2374         EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2375         String domainNameString = domainNameEditText.getText().toString();
2376
2377         // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
2378         // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2379         DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2380
2381         // Create the domain and store the database ID in `currentDomainDatabaseId`.
2382         int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2383
2384         // Create an intent to launch the domains activity.
2385         Intent domainsIntent = new Intent(this, DomainsActivity.class);
2386
2387         // Put extra information instructing the domains activity to directly load the current domain.
2388         domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2389
2390         // Make it so.
2391         startActivity(domainsIntent);
2392     }
2393
2394     @Override
2395     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2396         // Get the `EditTexts` from the `dialogFragment`.
2397         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2398         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2399
2400         // Extract the strings from the `EditTexts`.
2401         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2402         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2403
2404         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2405         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2406         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2407         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2408
2409         // Display the new bookmark below the current items in the (0 indexed) list.
2410         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2411
2412         // Create the bookmark.
2413         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2414
2415         // Update `bookmarksCursor` with the current contents of this folder.
2416         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2417
2418         // Update the `ListView`.
2419         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2420
2421         // Scroll to the new bookmark.
2422         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2423     }
2424
2425     @Override
2426     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2427         // Get handles for the views in `dialogFragment`.
2428         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2429         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2430         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2431
2432         // Get new folder name string.
2433         String folderNameString = createFolderNameEditText.getText().toString();
2434
2435         // Get the new folder icon `Bitmap`.
2436         Bitmap folderIconBitmap;
2437         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2438             // Get the default folder icon and convert it to a `Bitmap`.
2439             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2440             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2441             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2442         } else {  // Use the `WebView` favorite icon.
2443             folderIconBitmap = favoriteIconBitmap;
2444         }
2445
2446         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2447         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2448         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2449         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2450
2451         // Move all the bookmarks down one in the display order.
2452         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2453             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2454             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2455         }
2456
2457         // Create the folder, which will be placed at the top of the `ListView`.
2458         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2459
2460         // Update `bookmarksCursor` with the current contents of this folder.
2461         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2462
2463         // Update the `ListView`.
2464         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2465
2466         // Scroll to the new folder.
2467         bookmarksListView.setSelection(0);
2468     }
2469
2470     @Override
2471     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2472         // Get the shortcut name.
2473         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2474         String shortcutNameString = shortcutNameEditText.getText().toString();
2475
2476         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
2477         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2478
2479         // Setup the shortcut intent.
2480         Intent shortcutIntent = new Intent();
2481         shortcutIntent.setAction(Intent.ACTION_VIEW);
2482         shortcutIntent.setData(Uri.parse(formattedUrlString));
2483
2484         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
2485         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2486
2487         // Add the required fields to the shortcut info builder.
2488         shortcutInfoBuilder.setIcon(favoriteIcon);
2489         shortcutInfoBuilder.setIntent(shortcutIntent);
2490         shortcutInfoBuilder.setShortLabel(shortcutNameString);
2491
2492         // Request the pin.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2493         ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2494     }
2495
2496     @Override
2497     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2498         // Download the image if it has an HTTP or HTTPS URI.
2499         if (imageUrl.startsWith("http")) {
2500             // Get a handle for the system `DOWNLOAD_SERVICE`.
2501             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2502
2503             // Parse `imageUrl`.
2504             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2505
2506             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
2507             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2508             if (firstPartyCookiesEnabled) {
2509                 // Get the cookies for `imageUrl`.
2510                 String cookies = cookieManager.getCookie(imageUrl);
2511
2512                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2513                 downloadRequest.addRequestHeader("Cookie", cookies);
2514             }
2515
2516             // Get the file name from `dialogFragment`.
2517             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2518             String imageName = downloadImageNameEditText.getText().toString();
2519
2520             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2521             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2522                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2523             } else { // Only set the title using `imageName`.
2524                 downloadRequest.setTitle(imageName);
2525             }
2526
2527             // Allow `MediaScanner` to index the download if it is a media file.
2528             downloadRequest.allowScanningByMediaScanner();
2529
2530             // Add the URL as the description for the download.
2531             downloadRequest.setDescription(imageUrl);
2532
2533             // Show the download notification after the download is completed.
2534             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2535
2536             // Remove the lint warning below that `downloadManager` might be `null`.
2537             assert downloadManager != null;
2538
2539             // Initiate the download.
2540             downloadManager.enqueue(downloadRequest);
2541         } else {  // The image is not an HTTP or HTTPS URI.
2542             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2543         }
2544     }
2545
2546     @Override
2547     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2548         // Download the file if it has an HTTP or HTTPS URI.
2549         if (downloadUrl.startsWith("http")) {
2550
2551             // Get a handle for the system `DOWNLOAD_SERVICE`.
2552             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2553
2554             // Parse `downloadUrl`.
2555             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2556
2557             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
2558             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2559             if (firstPartyCookiesEnabled) {
2560                 // Get the cookies for `downloadUrl`.
2561                 String cookies = cookieManager.getCookie(downloadUrl);
2562
2563                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2564                 downloadRequest.addRequestHeader("Cookie", cookies);
2565             }
2566
2567             // Get the file name from `dialogFragment`.
2568             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2569             String fileName = downloadFileNameEditText.getText().toString();
2570
2571             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2572             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2573                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2574             } else { // Only set the title using `fileName`.
2575                 downloadRequest.setTitle(fileName);
2576             }
2577
2578             // Allow `MediaScanner` to index the download if it is a media file.
2579             downloadRequest.allowScanningByMediaScanner();
2580
2581             // Add the URL as the description for the download.
2582             downloadRequest.setDescription(downloadUrl);
2583
2584             // Show the download notification after the download is completed.
2585             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2586
2587             // Remove the lint warning below that `downloadManager` might be `null`.
2588             assert downloadManager != null;
2589
2590             // Initiate the download.
2591             downloadManager.enqueue(downloadRequest);
2592         } else {  // The download is not an HTTP or HTTPS URI.
2593             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2594         }
2595     }
2596
2597     @Override
2598     public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2599         // Get handles for the views from `dialogFragment`.
2600         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2601         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2602         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2603
2604         // Store the bookmark strings.
2605         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2606         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2607
2608         // Update the bookmark.
2609         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
2610             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2611         } else {  // Update the bookmark using the `WebView` favorite icon.
2612             // Convert the favorite icon to a byte array.  `0` is for lossless compression (the only option for a PNG).
2613             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2614             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2615             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2616
2617             //  Update the bookmark and the favorite icon.
2618             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2619         }
2620
2621         // Update `bookmarksCursor` with the current contents of this folder.
2622         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2623
2624         // Update the `ListView`.
2625         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2626     }
2627
2628     @Override
2629     public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2630         // Get handles for the views from `dialogFragment`.
2631         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2632         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2633         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2634         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2635
2636         // Get the new folder name.
2637         String newFolderNameString = editFolderNameEditText.getText().toString();
2638
2639         // Check if the favorite icon has changed.
2640         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
2641             // Update the name in the database.
2642             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2643         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
2644             // Get the new folder icon `Bitmap`.
2645             Bitmap folderIconBitmap;
2646             if (defaultFolderIconRadioButton.isChecked()) {
2647                 // Get the default folder icon and convert it to a `Bitmap`.
2648                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2649                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2650                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2651             } else {  // Use the `WebView` favorite icon.
2652                 folderIconBitmap = favoriteIconBitmap;
2653             }
2654
2655             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2656             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2657             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2658             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2659
2660             // Update the folder icon in the database.
2661             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2662         } else {  // The folder icon and the name have changed.
2663             // Get the new folder icon `Bitmap`.
2664             Bitmap folderIconBitmap;
2665             if (defaultFolderIconRadioButton.isChecked()) {
2666                 // Get the default folder icon and convert it to a `Bitmap`.
2667                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2668                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2669                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2670             } else {  // Use the `WebView` favorite icon.
2671                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2672             }
2673
2674             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2675             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2676             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2677             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2678
2679             // Update the folder name and icon in the database.
2680             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2681         }
2682
2683         // Update `bookmarksCursor` with the current contents of this folder.
2684         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2685
2686         // Update the `ListView`.
2687         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2688     }
2689
2690     @Override
2691     public void onHttpAuthenticationCancel() {
2692         // Cancel the `HttpAuthHandler`.
2693         httpAuthHandler.cancel();
2694     }
2695
2696     @Override
2697     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2698         // Get handles for the `EditTexts`.
2699         EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2700         EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2701
2702         // Proceed with the HTTP authentication.
2703         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2704     }
2705
2706     public void viewSslCertificate(View view) {
2707         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2708         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2709         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2710     }
2711
2712     @Override
2713     public void onSslErrorCancel() {
2714         sslErrorHandler.cancel();
2715     }
2716
2717     @Override
2718     public void onSslErrorProceed() {
2719         sslErrorHandler.proceed();
2720     }
2721
2722     @Override
2723     public void onSslMismatchBack() {
2724         if (mainWebView.canGoBack()) {  // There is a back page in the history.
2725             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2726             navigatingHistory = true;
2727
2728             // Go back.
2729             mainWebView.goBack();
2730         } else {  // There are no pages to go back to.
2731             // Load a blank page
2732             loadUrl("");
2733         }
2734     }
2735
2736     @Override
2737     public void onSslMismatchProceed() {
2738         // Do not check the pinned SSL certificate for this domain again until the domain changes.
2739         ignorePinnedSslCertificate = true;
2740     }
2741
2742     @Override
2743     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2744         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2745         navigatingHistory = true;
2746
2747         // Load the history entry.
2748         mainWebView.goBackOrForward(moveBackOrForwardSteps);
2749     }
2750
2751     @Override
2752     public void onClearHistory() {
2753         // Clear the history.
2754         mainWebView.clearHistory();
2755     }
2756
2757     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2758     @Override
2759     public void onBackPressed() {
2760         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
2761             // Close the navigation drawer.
2762             drawerLayout.closeDrawer(GravityCompat.START);
2763         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
2764             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
2765                 // close the bookmarks drawer.
2766                 drawerLayout.closeDrawer(GravityCompat.END);
2767             } else {  // A subfolder is displayed.
2768                 // Place the former parent folder in `currentFolder`.
2769                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2770
2771                 // Load the new folder.
2772                 loadBookmarksFolder();
2773             }
2774
2775         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
2776             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2777             navigatingHistory = true;
2778
2779             // Go back.
2780             mainWebView.goBack();
2781         } else {  // There isn't anything to do in Privacy Browser.
2782             // Pass `onBackPressed()` to the system.
2783             super.onBackPressed();
2784         }
2785     }
2786
2787     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2788         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
2789         String unformattedUrlString = urlTextBox.getText().toString().trim();
2790
2791         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
2792         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2793             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
2794             if (!unformattedUrlString.startsWith("http")) {
2795                 unformattedUrlString = "http://" + unformattedUrlString;
2796             }
2797
2798             // Initialize `unformattedUrl`.
2799             URL unformattedUrl = null;
2800
2801             // 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.
2802             try {
2803                 unformattedUrl = new URL(unformattedUrlString);
2804             } catch (MalformedURLException e) {
2805                 e.printStackTrace();
2806             }
2807
2808             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2809             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2810             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2811             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2812             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2813             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2814
2815             // Build the URI.
2816             Uri.Builder formattedUri = new Uri.Builder();
2817             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2818
2819             // Decode `formattedUri` as a `String` in `UTF-8`.
2820             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2821         } else {
2822             // Sanitize the search input and convert it to a search.
2823             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2824
2825             // Add the base search URL.
2826             formattedUrlString = searchURL + encodedUrlString;
2827         }
2828
2829         // Clear the focus from the URL text box.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
2830         urlTextBox.clearFocus();
2831
2832         loadUrl(formattedUrlString);
2833     }
2834
2835
2836     private void loadUrl(String url) {
2837         // Apply any custom domain settings.
2838         applyDomainSettings(url);
2839
2840         // Load the URL.
2841         mainWebView.loadUrl(url, customHeaders);
2842
2843         // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2844         urlIsLoading = true;
2845     }
2846
2847     public void findPreviousOnPage(View view) {
2848         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
2849         mainWebView.findNext(false);
2850     }
2851
2852     public void findNextOnPage(View view) {
2853         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2854         mainWebView.findNext(true);
2855     }
2856
2857     public void closeFindOnPage(View view) {
2858         // Delete the contents of `find_on_page_edittext`.
2859         findOnPageEditText.setText(null);
2860
2861         // Clear the highlighted phrases.
2862         mainWebView.clearMatches();
2863
2864         // Hide the Find on Page `RelativeLayout`.
2865         findOnPageLinearLayout.setVisibility(View.GONE);
2866
2867         // Show the URL app bar.
2868         supportAppBar.setVisibility(View.VISIBLE);
2869
2870         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2871         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2872     }
2873
2874     private void applyAppSettings() {
2875         // Get a handle for the shared preferences.
2876         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2877
2878         // Store the values from the shared preferences in variables.
2879         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2880         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2881         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2882         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2883         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2884         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2885         easyListEnabled = sharedPreferences.getBoolean("easylist", true);
2886         easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
2887         fanboyAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
2888         fanboySocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
2889         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2890         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2891         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2892         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2893         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2894         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2895         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2896         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2897
2898         // Set the homepage, search, and proxy options.
2899         if (proxyThroughOrbot) {  // Set the Tor options.
2900             // Set `torHomepageString` as `homepage`.
2901             homepage = torHomepageString;
2902
2903             // If formattedUrlString is null assign the homepage to it.
2904             if (formattedUrlString == null) {
2905                 formattedUrlString = homepage;
2906             }
2907
2908             // Set the search URL.
2909             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
2910                 searchURL = torSearchCustomURLString;
2911             } else {  // Use the string from the pre-built list.
2912                 searchURL = torSearchString;
2913             }
2914
2915             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
2916             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2917
2918             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
2919             if (darkTheme) {
2920                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2921             } else {
2922                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2923             }
2924
2925             // Display a message to the user if we are waiting on Orbot.
2926             if (!orbotStatus.equals("ON")) {
2927                 // Set `waitingForOrbot`.
2928                 waitingForOrbot = true;
2929
2930                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
2931                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2932             }
2933         } else {  // Set the non-Tor options.
2934             // Set `homepageString` as `homepage`.
2935             homepage = homepageString;
2936
2937             // If formattedUrlString is null assign the homepage to it.
2938             if (formattedUrlString == null) {
2939                 formattedUrlString = homepage;
2940             }
2941
2942             // Set the search URL.
2943             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
2944                 searchURL = searchCustomURLString;
2945             } else {  // Use the string from the pre-built list.
2946                 searchURL = searchString;
2947             }
2948
2949             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
2950             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2951
2952             // Set the default `appBar` background.  `this` refers to the context.
2953             if (darkTheme) {
2954                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2955             } else {
2956                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2957             }
2958
2959             // Reset `waitingForOrbot.
2960             waitingForOrbot = false;
2961         }
2962
2963         // Set swipe to refresh.
2964         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2965
2966         // Set Do Not Track status.
2967         if (doNotTrackEnabled) {
2968             customHeaders.put("DNT", "1");
2969         } else {
2970             customHeaders.remove("DNT");
2971         }
2972
2973         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2974         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2975             if (hideSystemBarsOnFullscreen) {  // Hide everything.
2976                 // Remove the translucent navigation setting if it is currently flagged.
2977                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2978
2979                 // Remove the translucent status bar overlay.
2980                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2981
2982                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2983                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2984
2985                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2986                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2987                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2988                  */
2989                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2990             } else {  // Hide everything except the status and navigation bars.
2991                 // Add the translucent status flag if it is unset.
2992                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2993
2994                 if (translucentNavigationBarOnFullscreen) {
2995                     // Set the navigation bar to be translucent.
2996                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2997                 } else {
2998                     // Set the navigation bar to be black.
2999                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3000                 }
3001             }
3002         } else {  // Switch to normal viewing mode.
3003             // Reset `inFullScreenBrowsingMode` to `false`.
3004             inFullScreenBrowsingMode = false;
3005
3006             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3007             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3008                 appBar.show();
3009             }
3010
3011             // Show the `BannerAd` in the free flavor.
3012             if (BuildConfig.FLAVOR.contentEquals("free")) {
3013                 // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
3014                 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3015
3016                 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3017                 adView = findViewById(R.id.adview);
3018             }
3019
3020             // Remove the translucent navigation bar flag if it is set.
3021             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3022
3023             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3024             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3025
3026             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3027             rootCoordinatorLayout.setSystemUiVisibility(0);
3028
3029             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3030             rootCoordinatorLayout.setFitsSystemWindows(true);
3031         }
3032     }
3033
3034     // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3035     @SuppressWarnings("deprecation")
3036     private void applyDomainSettings(String url) {
3037         // Reset `navigatingHistory`.
3038         navigatingHistory = false;
3039
3040         // Parse the URL into a URI.
3041         Uri uri = Uri.parse(url);
3042
3043         // Extract the domain from `uri`.
3044         String hostName = uri.getHost();
3045
3046         // Initialize `loadingNewDomainName`.
3047         boolean loadingNewDomainName;
3048
3049         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3050         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3051         //noinspection SimplifiableIfStatement
3052         if ((hostName == null) || (currentDomainName == null)) {
3053             loadingNewDomainName = true;
3054         } else {  // Determine if `hostName` equals `currentDomainName`.
3055             loadingNewDomainName = !hostName.equals(currentDomainName);
3056         }
3057
3058         // Only apply the domain settings if a new domain is being loaded.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3059         if (loadingNewDomainName) {
3060             // Set the new `hostname` as the `currentDomainName`.
3061             currentDomainName = hostName;
3062
3063             // Reset `ignorePinnedSslCertificate`.
3064             ignorePinnedSslCertificate = false;
3065
3066             // Reset `favoriteIconBitmap` and display it in the `appbar`.
3067             favoriteIconBitmap = favoriteIconDefaultBitmap;
3068             favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3069
3070             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3071             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3072             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3073
3074             // Get a full cursor from `domainsDatabaseHelper`.
3075             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3076
3077             // Initialize `domainSettingsSet`.
3078             Set<String> domainSettingsSet = new HashSet<>();
3079
3080             // Get the domain name column index.
3081             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3082
3083             // Populate `domainSettingsSet`.
3084             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3085                 // Move `domainsCursor` to the current row.
3086                 domainNameCursor.moveToPosition(i);
3087
3088                 // Store the domain name in `domainSettingsSet`.
3089                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3090             }
3091
3092             // Close `domainNameCursor.
3093             domainNameCursor.close();
3094
3095             // Initialize variables to track if domain settings will be applied and, if so, under which name.
3096             domainSettingsApplied = false;
3097             String domainNameInDatabase = null;
3098
3099             // Check the hostname.
3100             if (domainSettingsSet.contains(hostName)) {
3101                 domainSettingsApplied = true;
3102                 domainNameInDatabase = hostName;
3103             }
3104
3105             // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3106             if (hostName != null) {
3107                 while (hostName.contains(".") && !domainSettingsApplied) {  // Stop checking if we run out of  `.` or if we already know that `domainSettingsApplied` is `true`.
3108                     if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
3109                         domainSettingsApplied = true;
3110                         domainNameInDatabase = "*." + hostName;
3111                     }
3112
3113                     // Strip out the lowest subdomain of `host`.
3114                     hostName = hostName.substring(hostName.indexOf(".") + 1);
3115                 }
3116             }
3117
3118             // Get a handle for the shared preference.  `this` references the current context.
3119             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3120
3121             // Store the general preference information.
3122             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3123             String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3124             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3125             nightMode = sharedPreferences.getBoolean("night_mode", false);
3126
3127             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
3128                 // Get a cursor for the current host and move it to the first position.
3129                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3130                 currentHostDomainSettingsCursor.moveToFirst();
3131
3132                 // Get the settings from the cursor.
3133                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3134                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3135                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3136                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3137                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3138                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3139                 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3140                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3141                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3142                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3143                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3144                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3145                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3146                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3147                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3148                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3149                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3150
3151                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3152                 switch (nightModeInt) {
3153                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3154                         nightMode = true;
3155                         break;
3156
3157                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3158                         nightMode = false;
3159                         break;
3160                 }
3161
3162                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3163                 if (nightMode) {
3164                     javaScriptEnabled = true;
3165                 }
3166
3167                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3168                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3169                     pinnedDomainSslStartDate = null;
3170                 } else {
3171                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3172                 }
3173
3174                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3175                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3176                     pinnedDomainSslEndDate = null;
3177                 } else {
3178                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3179                 }
3180
3181                 // Close `currentHostDomainSettingsCursor`.
3182                 currentHostDomainSettingsCursor.close();
3183
3184                 // Apply the domain settings.
3185                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3186                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3187                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3188                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3189
3190                 // Apply the font size.
3191                 if (fontSize == 0) {  // Apply the default font size.
3192                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3193                 } else {  // Apply the specified font size.
3194                     mainWebView.getSettings().setTextZoom(fontSize);
3195                 }
3196
3197                 // Set third-party cookies status if API >= 21.
3198                 if (Build.VERSION.SDK_INT >= 21) {
3199                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3200                 }
3201
3202                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
3203                 // <https://redmine.stoutner.com/issues/160>
3204                 if (!urlIsLoading) {
3205                     switch (userAgentString) {
3206                         case "System default user agent":
3207                             // Set the user agent according to the system default.
3208                             switch (defaultUserAgentString) {
3209                                 case "WebView default user agent":
3210                                     // Set the user agent to `""`, which uses the default value.
3211                                     mainWebView.getSettings().setUserAgentString("");
3212                                     break;
3213
3214                                 case "Custom user agent":
3215                                     // Set the custom user agent.
3216                                     mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3217                                     break;
3218
3219                                 default:
3220                                     // Use the selected user agent.
3221                                     mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3222                             }
3223                             break;
3224
3225                         case "WebView default user agent":
3226                             // Set the user agent to `""`, which uses the default value.
3227                             mainWebView.getSettings().setUserAgentString("");
3228                             break;
3229
3230                         default:
3231                             // Use the selected user agent.
3232                             mainWebView.getSettings().setUserAgentString(userAgentString);
3233                     }
3234
3235                     // Store the applied user agent string.
3236                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3237                 }
3238
3239                 // 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.
3240                 if (darkTheme) {
3241                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3242                 } else {
3243                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3244                 }
3245             } else {  // The URL we are loading does not have custom domain settings.  Load the defaults.
3246                 // Store the values from `sharedPreferences` in variables.
3247                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3248                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3249                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3250                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3251                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3252
3253                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3254                 if (nightMode) {
3255                     javaScriptEnabled = true;
3256                 }
3257
3258                 // Apply the default settings.
3259                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3260                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3261                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3262                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3263                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3264
3265                 // Reset the pinned SSL certificate information.
3266                 domainSettingsDatabaseId = -1;
3267                 pinnedDomainSslCertificate = false;
3268                 pinnedDomainSslIssuedToCNameString = "";
3269                 pinnedDomainSslIssuedToONameString = "";
3270                 pinnedDomainSslIssuedToUNameString = "";
3271                 pinnedDomainSslIssuedByCNameString = "";
3272                 pinnedDomainSslIssuedByONameString = "";
3273                 pinnedDomainSslIssuedByUNameString = "";
3274                 pinnedDomainSslStartDate = null;
3275                 pinnedDomainSslEndDate = null;
3276
3277                 // Set third-party cookies status if API >= 21.
3278                 if (Build.VERSION.SDK_INT >= 21) {
3279                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3280                 }
3281
3282                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
3283                 // <https://redmine.stoutner.com/issues/160>
3284                 if (!urlIsLoading) {
3285                     switch (defaultUserAgentString) {
3286                         case "WebView default user agent":
3287                             // Set the user agent to `""`, which uses the default value.
3288                             mainWebView.getSettings().setUserAgentString("");
3289                             break;
3290
3291                         case "Custom user agent":
3292                             // Set the custom user agent.
3293                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3294                             break;
3295
3296                         default:
3297                             // Use the selected user agent.
3298                             mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3299                     }
3300
3301                     // Store the applied user agent string.
3302                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3303                 }
3304
3305                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3306                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3307             }
3308
3309             // Close `domainsDatabaseHelper`.
3310             domainsDatabaseHelper.close();
3311
3312             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
3313             onTheFlyDisplayImagesSet = false;
3314             setDisplayWebpageImages();
3315
3316             // Update the privacy icons, but only if `mainMenu` has already been populated.
3317             if (mainMenu != null) {
3318                 updatePrivacyIcons(true);
3319             }
3320         }
3321     }
3322
3323     private void setDisplayWebpageImages() {
3324         if (!onTheFlyDisplayImagesSet) {
3325             if (domainSettingsApplied) {  // Custom domain settings are applied.
3326                 switch (displayWebpageImagesInt) {
3327                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3328                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3329                         break;
3330
3331                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3332                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
3333                         break;
3334
3335                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3336                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
3337                         break;
3338                 }
3339             } else {  // Default settings are applied.
3340                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3341             }
3342         }
3343     }
3344
3345     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3346         // Get handles for the icons.
3347         MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3348         MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3349         MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3350         MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3351
3352         // Update `privacyIcon`.
3353         if (javaScriptEnabled) {  // JavaScript is enabled.
3354             privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3355         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
3356             privacyIconMenuItem.setIcon(R.drawable.warning);
3357         } else {  // All the dangerous features are disabled.
3358             privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3359         }
3360
3361         // Update `firstPartyCookiesIcon`.
3362         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
3363             firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3364         } else {  // First-party cookies are disabled.
3365             if (darkTheme) {
3366                 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3367             } else {
3368                 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3369             }
3370         }
3371
3372         // Update `domStorageIcon`.
3373         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
3374             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3375         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
3376             if (darkTheme) {
3377                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3378             } else {
3379                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3380             }
3381         } else {  // JavaScript is disabled, so DOM storage is ghosted.
3382             if (darkTheme) {
3383                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3384             } else {
3385                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3386             }
3387         }
3388
3389         // Update `formDataIcon`.
3390         if (saveFormDataEnabled) {  // Form data is enabled.
3391             formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3392         } else {  // Form data is disabled.
3393             if (darkTheme) {
3394                 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3395             } else {
3396                 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3397             }
3398         }
3399
3400         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3401         if (runInvalidateOptionsMenu) {
3402             invalidateOptionsMenu();
3403         }
3404     }
3405
3406     private void highlightUrlText() {
3407         String urlString = urlTextBox.getText().toString();
3408
3409         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
3410             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3411         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
3412             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3413         }
3414
3415         // Get the index of the `/` immediately after the domain name.
3416         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3417
3418         // De-emphasize the text after the domain name.
3419         if (endOfDomainName > 0) {
3420             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3421         }
3422     }
3423
3424     private void loadBookmarksFolder() {
3425         // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3426         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3427
3428         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
3429         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3430             @Override
3431             public View newView(Context context, Cursor cursor, ViewGroup parent) {
3432                 // Inflate the individual item layout.  `false` does not attach it to the root.
3433                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3434             }
3435
3436             @Override
3437             public void bindView(View view, Context context, Cursor cursor) {
3438                 // Get handles for the views.
3439                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3440                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3441
3442                 // Get the favorite icon byte array from the `Cursor`.
3443                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3444
3445                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3446                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3447
3448                 // Display the bitmap in `bookmarkFavoriteIcon`.
3449                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3450
3451                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3452                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3453                 bookmarkNameTextView.setText(bookmarkNameString);
3454
3455                 // Make the font bold for folders.
3456                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3457                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3458                 } else {  // Reset the font to default for normal bookmarks.
3459                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3460                 }
3461             }
3462         };
3463
3464         // Populate the `ListView` with the adapter.
3465         bookmarksListView.setAdapter(bookmarksCursorAdapter);
3466
3467         // Set the bookmarks drawer title.
3468         if (currentBookmarksFolder.isEmpty()) {
3469             bookmarksTitleTextView.setText(R.string.bookmarks);
3470         } else {
3471             bookmarksTitleTextView.setText(currentBookmarksFolder);
3472         }
3473     }
3474 }