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