Bump the target API to 28.
[PrivacyBrowser.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.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.ActivityNotFoundException;
29 import android.content.BroadcastReceiver;
30 import android.content.ClipData;
31 import android.content.ClipboardManager;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageManager;
37 import android.content.res.Configuration;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Typeface;
42 import android.graphics.drawable.BitmapDrawable;
43 import android.graphics.drawable.Drawable;
44 import android.net.Uri;
45 import android.net.http.SslCertificate;
46 import android.net.http.SslError;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.Environment;
50 import android.os.Handler;
51 import android.preference.PreferenceManager;
52 import android.print.PrintDocumentAdapter;
53 import android.print.PrintManager;
54 import android.support.annotation.NonNull;
55 import android.support.design.widget.CoordinatorLayout;
56 import android.support.design.widget.FloatingActionButton;
57 import android.support.design.widget.NavigationView;
58 import android.support.design.widget.Snackbar;
59 import android.support.v4.app.ActivityCompat;
60 import android.support.v4.content.ContextCompat;
61 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
62 import android.support.v4.content.pm.ShortcutInfoCompat;
63 import android.support.v4.content.pm.ShortcutManagerCompat;
64 import android.support.v4.graphics.drawable.IconCompat;
65 import android.support.v4.view.GravityCompat;
66 import android.support.v4.widget.DrawerLayout;
67 import android.support.v4.widget.SwipeRefreshLayout;
68 import android.support.v7.app.ActionBar;
69 import android.support.v7.app.ActionBarDrawerToggle;
70 import android.support.v7.app.AppCompatActivity;
71 import android.support.v7.app.AppCompatDialogFragment;
72 import android.support.v7.widget.Toolbar;
73 import android.text.Editable;
74 import android.text.Spanned;
75 import android.text.TextWatcher;
76 import android.text.style.ForegroundColorSpan;
77 import android.util.Patterns;
78 import android.view.ContextMenu;
79 import android.view.GestureDetector;
80 import android.view.KeyEvent;
81 import android.view.Menu;
82 import android.view.MenuItem;
83 import android.view.MotionEvent;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.WindowManager;
87 import android.view.inputmethod.InputMethodManager;
88 import android.webkit.CookieManager;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.SslErrorHandler;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebBackForwardList;
93 import android.webkit.WebChromeClient;
94 import android.webkit.WebResourceResponse;
95 import android.webkit.WebStorage;
96 import android.webkit.WebView;
97 import android.webkit.WebViewClient;
98 import android.webkit.WebViewDatabase;
99 import android.widget.ArrayAdapter;
100 import android.widget.CursorAdapter;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.ImageView;
104 import android.widget.LinearLayout;
105 import android.widget.ListView;
106 import android.widget.ProgressBar;
107 import android.widget.RadioButton;
108 import android.widget.RelativeLayout;
109 import android.widget.TextView;
110
111 import com.stoutner.privacybrowser.BuildConfig;
112 import com.stoutner.privacybrowser.R;
113 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
122 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
123 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
124 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
125 import com.stoutner.privacybrowser.helpers.AdHelper;
126 import com.stoutner.privacybrowser.helpers.BlockListHelper;
127 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
128 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
130 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
131 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
132
133 import java.io.ByteArrayInputStream;
134 import java.io.ByteArrayOutputStream;
135 import java.io.File;
136 import java.io.IOException;
137 import java.io.UnsupportedEncodingException;
138 import java.net.MalformedURLException;
139 import java.net.URL;
140 import java.net.URLDecoder;
141 import java.net.URLEncoder;
142 import java.util.ArrayList;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map;
148 import java.util.Set;
149
150 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
151 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
152         CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
153         DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
154         HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
155         SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
156
157     // `darkTheme` is public static so it can be accessed from everywhere.
158     public static boolean darkTheme;
159
160     // `allowScreenshots` is public static so it can be accessed from everywhere.  It is also used in `onCreate()`.
161     public static boolean allowScreenshots;
162
163     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
164     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
165     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
166     public static Bitmap favoriteIconBitmap;
167
168     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
169     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
170     public static String formattedUrlString;
171
172     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
173     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
174     public static SslCertificate sslCertificate;
175
176     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()` and `onResume()`.
177     public static String orbotStatus;
178
179     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
180     public static String webViewTitle;
181
182     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
183     public static String appliedUserAgentString;
184
185     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
186     public static boolean reloadOnRestart;
187
188     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`.  It is also used in `onRestart()`.
189     public static boolean loadUrlOnRestart;
190
191     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
192     public static boolean restartFromBookmarksActivity;
193
194     // The block list versions are public static so they can be accessed from `AboutTabFragment`.  They are also used in `onCreate()`.
195     public static String easyListVersion;
196     public static String easyPrivacyVersion;
197     public static String fanboysAnnoyanceVersion;
198     public static String fanboysSocialVersion;
199     public static String ultraPrivacyVersion;
200
201     // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`.  They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
202     public static List<String[]> resourceRequests;
203     public static String[] whiteListResultStringArray;
204     int easyListBlockedRequests;
205     int easyPrivacyBlockedRequests;
206     int fanboysAnnoyanceListBlockedRequests;
207     int fanboysSocialBlockingListBlockedRequests;
208     int ultraPrivacyBlockedRequests;
209     int thirdPartyBlockedRequests;
210
211     public final static int REQUEST_DISPOSITION = 0;
212     public final static int REQUEST_URL = 1;
213     public final static int REQUEST_BLOCKLIST = 2;
214     public final static int REQUEST_SUBLIST = 3;
215     public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
216     public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
217
218     public final static int REQUEST_DEFAULT = 0;
219     public final static int REQUEST_ALLOWED = 1;
220     public final static int REQUEST_THIRD_PARTY = 2;
221     public final static int REQUEST_BLOCKED = 3;
222
223     public final static int MAIN_WHITELIST = 1;
224     public final static int FINAL_WHITELIST = 2;
225     public final static int DOMAIN_WHITELIST = 3;
226     public final static int DOMAIN_INITIAL_WHITELIST = 4;
227     public final static int DOMAIN_FINAL_WHITELIST = 5;
228     public final static int THIRD_PARTY_WHITELIST = 6;
229     public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
230     public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
231
232     public final static int MAIN_BLACKLIST = 9;
233     public final static int INITIAL_BLACKLIST = 10;
234     public final static int FINAL_BLACKLIST = 11;
235     public final static int DOMAIN_BLACKLIST = 12;
236     public final static int DOMAIN_INITIAL_BLACKLIST = 13;
237     public final static int DOMAIN_FINAL_BLACKLIST = 14;
238     public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
239     public final static int THIRD_PARTY_BLACKLIST = 16;
240     public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
241     public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
242     public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
243     public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
244     public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
245     public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
246
247     // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
248     // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
249     public static boolean blockAllThirdPartyRequests;
250
251     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
252     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
253     public static String currentBookmarksFolder;
254
255     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
256     public static int domainSettingsDatabaseId;
257
258     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
259     public static String pinnedDomainSslIssuedToCNameString;
260     public static String pinnedDomainSslIssuedToONameString;
261     public static String pinnedDomainSslIssuedToUNameString;
262     public static String pinnedDomainSslIssuedByCNameString;
263     public static String pinnedDomainSslIssuedByONameString;
264     public static String pinnedDomainSslIssuedByUNameString;
265     public static Date pinnedDomainSslStartDate;
266     public static Date pinnedDomainSslEndDate;
267
268     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
269     public final static int UNRECOGNIZED_USER_AGENT = -1;
270     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
271     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
272     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
273     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
274     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
275
276
277     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
278     private ActionBar appBar;
279
280     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
281     private boolean navigatingHistory;
282
283     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
284     private Bitmap favoriteIconDefaultBitmap;
285
286     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
287     private DrawerLayout drawerLayout;
288
289     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
290     private CoordinatorLayout rootCoordinatorLayout;
291
292     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
293     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
294     private WebView mainWebView;
295
296     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
297     private FrameLayout fullScreenVideoFrameLayout;
298
299     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
300     private SwipeRefreshLayout swipeRefreshLayout;
301
302     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
303     private RelativeLayout urlAppBarRelativeLayout;
304
305     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
306     private ImageView favoriteIconImageView;
307
308     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
309     private CookieManager cookieManager;
310
311     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
312     private final Map<String, String> customHeaders = new HashMap<>();
313
314     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
315     private boolean javaScriptEnabled;
316
317     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
318     private boolean firstPartyCookiesEnabled;
319
320     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
321     private boolean thirdPartyCookiesEnabled;
322
323     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
324     private boolean domStorageEnabled;
325
326     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.  It can be removed once the minimum API >= 26.
327     private boolean saveFormDataEnabled;
328
329     // `nightMode` is used in `onCreate()` and  `applyDomainSettings()`.
330     private boolean nightMode;
331
332     // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
333     private boolean displayWebpageImagesBoolean;
334
335     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
336     private String homepage;
337
338     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
339     private String searchURL;
340
341     // The block list variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
342     private boolean easyListEnabled;
343     private boolean easyPrivacyEnabled;
344     private boolean fanboysAnnoyanceListEnabled;
345     private boolean fanboysSocialBlockingListEnabled;
346     private boolean ultraPrivacyEnabled;
347
348     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
349     private Runtime privacyBrowserRuntime;
350
351     // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
352     private boolean proxyThroughOrbot;
353
354     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
355     private boolean incognitoModeEnabled;
356
357     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
358     private boolean fullScreenBrowsingModeEnabled;
359
360     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
361     private boolean inFullScreenBrowsingMode;
362
363     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
364     private boolean hideSystemBarsOnFullscreen;
365
366     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
367     private boolean translucentNavigationBarOnFullscreen;
368
369     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
370     private boolean reapplyDomainSettingsOnRestart;
371
372     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
373     private boolean reapplyAppSettingsOnRestart;
374
375     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
376     private boolean displayingFullScreenVideo;
377
378     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
379     private String currentDomainName;
380
381     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
382     private boolean ignorePinnedSslCertificate;
383
384     // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
385     private BroadcastReceiver orbotStatusBroadcastReceiver;
386
387     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
388     private boolean waitingForOrbot;
389
390     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
391     private boolean domainSettingsApplied;
392
393     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
394     private int displayWebpageImagesInt;
395
396     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
397     private boolean onTheFlyDisplayImagesSet;
398
399     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
400     private String waitingForOrbotHTMLString;
401
402     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
403     private String privateDataDirectoryString;
404
405     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
406     private LinearLayout findOnPageLinearLayout;
407
408     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
409     private EditText findOnPageEditText;
410
411     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
412     private Menu mainMenu;
413
414     // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsItem()`.
415     private MenuItem refreshMenuItem;
416
417     // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
418     private boolean displayAdditionalAppBarIcons;
419
420     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
421     private ActionBarDrawerToggle drawerToggle;
422
423     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
424     private Toolbar supportAppBar;
425
426     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
427     private EditText urlTextBox;
428
429     // The color spans are used in `onCreate()` and `highlightUrlText()`.
430     private ForegroundColorSpan redColorSpan;
431     private ForegroundColorSpan initialGrayColorSpan;
432     private ForegroundColorSpan finalGrayColorSpan;
433
434     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
435     private SslErrorHandler sslErrorHandler;
436
437     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
438     private static HttpAuthHandler httpAuthHandler;
439
440     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
441     private InputMethodManager inputMethodManager;
442
443     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
444     private RelativeLayout mainWebViewRelativeLayout;
445
446     // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
447     private boolean urlIsLoading;
448
449     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
450     private boolean pinnedDomainSslCertificate;
451
452     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
453     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
454
455     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
456     private ListView bookmarksListView;
457
458     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
459     private TextView bookmarksTitleTextView;
460
461     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
462     private Cursor bookmarksCursor;
463
464     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
465     private CursorAdapter bookmarksCursorAdapter;
466
467     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
468     private String oldFolderNameString;
469
470     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
471     private ValueCallback<Uri[]> fileChooserCallback;
472
473     // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
474     private String downloadUrl;
475     private String downloadContentDisposition;
476     private long downloadContentLength;
477
478     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
479     private String downloadImageUrl;
480
481     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
482     private ArrayAdapter<CharSequence> userAgentNamesArray;
483     private String[] userAgentDataArray;
484
485     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
486     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
487     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
488
489     @Override
490     // 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.
491     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
492     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
493     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
494     @SuppressWarnings("deprecation")
495     protected void onCreate(Bundle savedInstanceState) {
496         // Get a handle for the shared preferences.
497         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
498
499         // Get the theme and screenshot preferences.
500         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
501         allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
502
503         // Disable screenshots if not allowed.
504         if (!allowScreenshots) {
505             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
506         }
507
508         // Set the activity theme.
509         if (darkTheme) {
510             setTheme(R.style.PrivacyBrowserDark);
511         } else {
512             setTheme(R.style.PrivacyBrowserLight);
513         }
514
515         // Run the default commands.
516         super.onCreate(savedInstanceState);
517
518         // Set the content view.
519         setContentView(R.layout.main_drawerlayout);
520
521         // Get a handle for `inputMethodManager`.
522         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
523
524         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
525         supportAppBar = findViewById(R.id.app_bar);
526         setSupportActionBar(supportAppBar);
527         appBar = getSupportActionBar();
528
529         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
530         assert appBar != null;
531
532         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
533         appBar.setCustomView(R.layout.url_app_bar);
534         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
535
536         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
537         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
538         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
539         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
540
541         // Get a handle for `urlTextBox`.
542         urlTextBox = findViewById(R.id.url_edittext);
543
544         // Remove the formatting from `urlTextBar` when the user is editing the text.
545         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
546             if (hasFocus) {  // The user is editing `urlTextBox`.
547                 // Remove the highlighting.
548                 urlTextBox.getText().removeSpan(redColorSpan);
549                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
550                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
551             } else {  // The user has stopped editing `urlTextBox`.
552                 // Reapply the highlighting.
553                 highlightUrlText();
554             }
555         });
556
557         // Set the go button on the keyboard to load the URL in `urlTextBox`.
558         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
559             // If the event is a key-down event on the `enter` button, load the URL.
560             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
561                 // Load the URL into the mainWebView and consume the event.
562                 try {
563                     loadUrlFromTextBox();
564                 } catch (UnsupportedEncodingException e) {
565                     e.printStackTrace();
566                 }
567                 // If the enter key was pressed, consume the event.
568                 return true;
569             } else {
570                 // If any other key was pressed, do not consume the event.
571                 return false;
572             }
573         });
574
575         // Set `waitingForOrbotHTMLString`.
576         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
577
578         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
579         currentDomainName = "";
580         orbotStatus = "unknown";
581         waitingForOrbot = false;
582
583         // Create an Orbot status `BroadcastReceiver`.
584         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
585             @Override
586             public void onReceive(Context context, Intent intent) {
587                 // Store the content of the status message in `orbotStatus`.
588                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
589
590                 // If we are waiting on Orbot, load the website now that Orbot is connected.
591                 if (orbotStatus.equals("ON") && waitingForOrbot) {
592                     // Reset `waitingForOrbot`.
593                     waitingForOrbot = false;
594
595                     // Load `formattedUrlString
596                     loadUrl(formattedUrlString);
597                 }
598             }
599         };
600
601         // Register `orbotStatusBroadcastReceiver` on `this` context.
602         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
603
604         // Get handles for views that need to be accessed.
605         drawerLayout = findViewById(R.id.drawerlayout);
606         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
607         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
608         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
609         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
610         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
611         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
612         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
613         mainWebView = findViewById(R.id.main_webview);
614         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
615         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
616         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
617         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
618         favoriteIconImageView = findViewById(R.id.favorite_icon);
619
620         // 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.
621         if (darkTheme) {
622             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
623             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
624             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
625             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
626         } else {
627             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
628             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
629             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
630             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
631         }
632
633         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
634         launchBookmarksActivityFab.setOnClickListener(v -> {
635             // Create an intent to launch the bookmarks activity.
636             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
637
638             // Include the current folder with the `Intent`.
639             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
640
641             // Make it so.
642             startActivity(bookmarksIntent);
643         });
644
645         // Set the create new bookmark folder FAB to display an alert dialog.
646         createBookmarkFolderFab.setOnClickListener(v -> {
647             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
648             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
649             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
650         });
651
652         // Set the create new bookmark FAB to display an alert dialog.
653         createBookmarkFab.setOnClickListener(view -> {
654             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
655             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
656             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
657         });
658
659         // Create a double-tap listener to toggle full-screen mode.
660         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
661             // Override `onDoubleTap()`.  All other events are handled using the default settings.
662             @Override
663             public boolean onDoubleTap(MotionEvent event) {
664                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
665                     // Toggle `inFullScreenBrowsingMode`.
666                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
667
668                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
669                         // Hide the `appBar`.
670                         appBar.hide();
671
672                         // Hide the banner ad in the free flavor.
673                         if (BuildConfig.FLAVOR.contentEquals("free")) {
674                             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
675                             AdHelper.hideAd(findViewById(R.id.adview));
676                         }
677
678                         // Modify the system bars.
679                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
680                             // Remove the translucent overlays.
681                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
682
683                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
684                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
685
686                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
687                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
688                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
689                              */
690                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
691
692                             // Set `rootCoordinatorLayout` to fill the whole screen.
693                             rootCoordinatorLayout.setFitsSystemWindows(false);
694                         } else {  // Hide everything except the status and navigation bars.
695                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
696                             rootCoordinatorLayout.setFitsSystemWindows(false);
697
698                             // 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.
699                             if (translucentNavigationBarOnFullscreen) {
700                                 // Set the navigation bar to be translucent.
701                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
702                             }
703                         }
704                     } else {  // Switch to normal viewing mode.
705                         // Show the `appBar`.
706                         appBar.show();
707
708                         // Show the `BannerAd` in the free flavor.
709                         if (BuildConfig.FLAVOR.contentEquals("free")) {
710                             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
711                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
712                         }
713
714                         // Remove the translucent navigation bar flag if it is set.
715                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
716
717                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
718                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
719
720                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
721                         rootCoordinatorLayout.setSystemUiVisibility(0);
722
723                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
724                         rootCoordinatorLayout.setFitsSystemWindows(true);
725                     }
726
727                     // Consume the double-tap.
728                     return true;
729                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
730                     return false;
731                 }
732             }
733         });
734
735         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
736         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
737             // Call `performClick()` on the view, which is required for accessibility.
738             v.performClick();
739
740             // Send the `event` to `gestureDetector`.
741             return gestureDetector.onTouchEvent(event);
742         });
743
744         // Update `findOnPageCountTextView`.
745         mainWebView.setFindListener(new WebView.FindListener() {
746             // Get a handle for `findOnPageCountTextView`.
747             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
748
749             @Override
750             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
751                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
752                     // Set `findOnPageCountTextView` to `0/0`.
753                     findOnPageCountTextView.setText(R.string.zero_of_zero);
754                 } else if (isDoneCounting) {  // There are matches.
755                     // `activeMatchOrdinal` is zero-based.
756                     int activeMatch = activeMatchOrdinal + 1;
757
758                     // Build the match string.
759                     String matchString = activeMatch + "/" + numberOfMatches;
760
761                     // Set `findOnPageCountTextView`.
762                     findOnPageCountTextView.setText(matchString);
763                 }
764             }
765         });
766
767         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
768         findOnPageEditText.addTextChangedListener(new TextWatcher() {
769             @Override
770             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
771                 // Do nothing.
772             }
773
774             @Override
775             public void onTextChanged(CharSequence s, int start, int before, int count) {
776                 // Do nothing.
777             }
778
779             @Override
780             public void afterTextChanged(Editable s) {
781                 // Search for the text in `mainWebView`.
782                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
783             }
784         });
785
786         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
787         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
788             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
789                 // Hide the soft keyboard.  `0` indicates no additional flags.
790                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
791
792                 // Consume the event.
793                 return true;
794             } else {  // A different key was pressed.
795                 // Do not consume the event.
796                 return false;
797             }
798         });
799
800         // Implement swipe to refresh
801         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
802         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
803         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
804
805         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
806         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
807         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
808
809         // Listen for touches on the navigation menu.
810         final NavigationView navigationView = findViewById(R.id.navigationview);
811         navigationView.setNavigationItemSelectedListener(this);
812
813         // 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.
814         final Menu navigationMenu = navigationView.getMenu();
815         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
816         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
817         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
818         final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
819
820         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
821         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
822         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
823
824         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
825         currentBookmarksFolder = "";
826
827         // Load the home folder, which is `""` in the database.
828         loadBookmarksFolder();
829
830         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
831             // Convert the id from long to int to match the format of the bookmarks database.
832             int databaseID = (int) id;
833
834             // Get the bookmark cursor for this ID and move it to the first row.
835             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
836             bookmarkCursor.moveToFirst();
837
838             // Act upon the bookmark according to the type.
839             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
840                 // Store the new folder name in `currentBookmarksFolder`.
841                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
842
843                 // Load the new folder.
844                 loadBookmarksFolder();
845             } else {  // The selected bookmark is not a folder.
846                 // Load the bookmark URL.
847                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
848
849                 // Close the bookmarks drawer.
850                 drawerLayout.closeDrawer(GravityCompat.END);
851             }
852
853             // Close the `Cursor`.
854             bookmarkCursor.close();
855         });
856
857         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
858             // Convert the database ID from `long` to `int`.
859             int databaseId = (int) id;
860
861             // Find out if the selected bookmark is a folder.
862             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
863
864             if (isFolder) {
865                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
866                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
867
868                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
869                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
870                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
871             } else {
872                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
873                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
874                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
875             }
876
877             // Consume the event.
878             return true;
879         });
880
881         // The `DrawerListener` is used to update the Navigation Menu.
882         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
883             @Override
884             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
885             }
886
887             @Override
888             public void onDrawerOpened(@NonNull View drawerView) {
889             }
890
891             @Override
892             public void onDrawerClosed(@NonNull View drawerView) {
893             }
894
895             @Override
896             public void onDrawerStateChanged(int newState) {
897                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // The drawer is opening or closing.
898                     // Calculate the total blocked requests counter.
899                     int totalBlockedRequests = easyListBlockedRequests + easyPrivacyBlockedRequests + fanboysAnnoyanceListBlockedRequests + fanboysSocialBlockingListBlockedRequests +
900                             ultraPrivacyBlockedRequests + thirdPartyBlockedRequests;
901
902                     // Update the back, forward, history, and requests menu items.
903                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
904                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
905                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
906                     navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + totalBlockedRequests);
907
908                     // Hide the keyboard (if displayed) so we can see the navigation menu.  `0` indicates no additional flags.
909                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
910
911                     // Clear the focus from `urlTextBox` if it has it.
912                     urlTextBox.clearFocus();
913                 }
914             }
915         });
916
917         // drawerToggle creates the hamburger icon at the start of the AppBar.
918         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
919
920         // Get a handle for the progress bar.
921         final ProgressBar progressBar = findViewById(R.id.progress_bar);
922
923         mainWebView.setWebChromeClient(new WebChromeClient() {
924             // Update the progress bar when a page is loading.
925             @Override
926             public void onProgressChanged(WebView view, int progress) {
927                 // Inject the night mode CSS if night mode is enabled.
928                 if (nightMode) {
929                     // `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
930                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
931                     // `border: none` removes all borders, which can also be used to underline text.
932                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
933                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
934                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
935                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
936                                 // Initialize a `Handler` to display `mainWebView`.
937                                 Handler displayWebViewHandler = new Handler();
938
939                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
940                                 Runnable displayWebViewRunnable = () -> {
941                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
942                                     if (progressBar.getVisibility() == View.GONE) {
943                                         mainWebView.setVisibility(View.VISIBLE);
944                                     }
945                                 };
946
947                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
948                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
949                             });
950                 }
951
952                 // Update the progress bar.
953                 progressBar.setProgress(progress);
954
955                 // Set the visibility of the progress bar.
956                 if (progress < 100) {
957                     // Show the progress bar.
958                     progressBar.setVisibility(View.VISIBLE);
959                 } else {
960                     // Hide the progress bar.
961                     progressBar.setVisibility(View.GONE);
962
963                     // Display `mainWebView` if night mode is disabled.
964                     // 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
965                     // currently enabled.
966                     if (!nightMode) {
967                         mainWebView.setVisibility(View.VISIBLE);
968                     }
969
970                     //Stop the swipe to refresh indicator if it is running
971                     swipeRefreshLayout.setRefreshing(false);
972                 }
973             }
974
975             // Set the favorite icon when it changes.
976             @Override
977             public void onReceivedIcon(WebView view, Bitmap icon) {
978                 // Only update the favorite icon if the website has finished loading.
979                 if (progressBar.getVisibility() == View.GONE) {
980                     // Save a copy of the favorite icon.
981                     favoriteIconBitmap = icon;
982
983                     // Place the favorite icon in the appBar.
984                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
985                 }
986             }
987
988             // Save a copy of the title when it changes.
989             @Override
990             public void onReceivedTitle(WebView view, String title) {
991                 // Save a copy of the title.
992                 webViewTitle = title;
993             }
994
995             // Enter full screen video.
996             @Override
997             public void onShowCustomView(View view, CustomViewCallback callback) {
998                 // Set the full screen video flag.
999                 displayingFullScreenVideo = true;
1000
1001                 // Pause the ad if this is the free flavor.
1002                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1003                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1004                     AdHelper.pauseAd(findViewById(R.id.adview));
1005                 }
1006
1007                 // Remove the translucent overlays.
1008                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1009
1010                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1011                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1012
1013                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1014                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1015                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1016                  */
1017                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1018
1019                 // Set `rootCoordinatorLayout` to fill the entire screen.
1020                 rootCoordinatorLayout.setFitsSystemWindows(false);
1021
1022                 // Disable the sliding drawers.
1023                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1024
1025                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1026                 fullScreenVideoFrameLayout.addView(view);
1027                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1028             }
1029
1030             // Exit full screen video.
1031             @Override
1032             public void onHideCustomView() {
1033                 // Unset the full screen video flag.
1034                 displayingFullScreenVideo = true;
1035
1036                 // Hide `fullScreenVideoFrameLayout`.
1037                 fullScreenVideoFrameLayout.removeAllViews();
1038                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1039
1040                 // Enable the sliding drawers.
1041                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1042
1043                 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1044                 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
1045                     if (hideSystemBarsOnFullscreen) {  // Hide everything.
1046                         // Remove the translucent navigation setting if it is currently flagged.
1047                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1048
1049                         // Remove the translucent status bar overlay.
1050                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1051
1052                         // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1053                         drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1054
1055                         /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1056                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1057                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1058                          */
1059                         rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1060                     } else {  // Hide everything except the status and navigation bars.
1061                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1062                         rootCoordinatorLayout.setSystemUiVisibility(0);
1063
1064                         // Add the translucent status flag if it is unset.
1065                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1066
1067                         if (translucentNavigationBarOnFullscreen) {
1068                             // Set the navigation bar to be translucent.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1069                             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1070                         } else {
1071                             // Set the navigation bar to be black.
1072                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1073                         }
1074                     }
1075                 } else {  // Switch to normal viewing mode.
1076                     // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1077                     if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1078                         appBar.show();
1079                     }
1080
1081                     // Show the `BannerAd` in the free flavor.
1082                     if (BuildConfig.FLAVOR.contentEquals("free")) {
1083                         // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1084                         AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1085                     }
1086
1087                     // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1088                     rootCoordinatorLayout.setSystemUiVisibility(0);
1089
1090                     // Remove the translucent navigation bar flag if it is set.
1091                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1092
1093                     // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1094                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1095
1096                     // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1097                     rootCoordinatorLayout.setFitsSystemWindows(true);
1098                 }
1099
1100                 // Show the ad if this is the free flavor.
1101                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1102                     // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1103                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1104                 }
1105             }
1106
1107             // Upload files.
1108             @Override
1109             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1110                 // Show the file chooser if the device is running API >= 21.
1111                 if (Build.VERSION.SDK_INT >= 21) {
1112                     // Store the file path callback.
1113                     fileChooserCallback = filePathCallback;
1114
1115                     // Create an intent to open a chooser based ont the file chooser parameters.
1116                     Intent fileChooserIntent = fileChooserParams.createIntent();
1117
1118                     // Open the file chooser.  Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1119                     startActivityForResult(fileChooserIntent, 0);
1120                 }
1121                 return true;
1122             }
1123         });
1124
1125         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
1126         registerForContextMenu(mainWebView);
1127
1128         // Allow the downloading of files.
1129         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1130             // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1131             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1132                 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1133
1134                 // Store the variables for future use by `onRequestPermissionsResult()`.
1135                 downloadUrl = url;
1136                 downloadContentDisposition = contentDisposition;
1137                 downloadContentLength = contentLength;
1138
1139                 // Show a dialog if the user has previously denied the permission.
1140                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
1141                     // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1142                     DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1143
1144                     // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
1145                     downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1146                 } else {  // Show the permission request directly.
1147                     // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
1148                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1149                 }
1150             } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1151                 // Get a handle for the download file alert dialog.
1152                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1153
1154                 // Show the download file alert dialog.
1155                 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1156             }
1157         });
1158
1159         // Allow pinch to zoom.
1160         mainWebView.getSettings().setBuiltInZoomControls(true);
1161
1162         // Hide zoom controls.
1163         mainWebView.getSettings().setDisplayZoomControls(false);
1164
1165         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
1166         mainWebView.getSettings().setUseWideViewPort(true);
1167
1168         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1169         mainWebView.getSettings().setLoadWithOverviewMode(true);
1170
1171         // Explicitly disable geolocation.
1172         mainWebView.getSettings().setGeolocationEnabled(false);
1173
1174         // Initialize cookieManager.
1175         cookieManager = CookieManager.getInstance();
1176
1177         // 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).
1178         customHeaders.put("X-Requested-With", "");
1179
1180         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
1181         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1182
1183         // Get the intent that started the app.
1184         final Intent launchingIntent = getIntent();
1185
1186         // Extract the launching intent data as `launchingIntentUriData`.
1187         final Uri launchingIntentUriData = launchingIntent.getData();
1188
1189         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1190         if (launchingIntentUriData != null) {
1191             formattedUrlString = launchingIntentUriData.toString();
1192         }
1193
1194         // Get a handle for the `Runtime`.
1195         privacyBrowserRuntime = Runtime.getRuntime();
1196
1197         // Store the application's private data directory.
1198         privateDataDirectoryString = getApplicationInfo().dataDir;
1199         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1200
1201         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1202         inFullScreenBrowsingMode = false;
1203
1204         // Initialize the privacy settings variables.
1205         javaScriptEnabled = false;
1206         firstPartyCookiesEnabled = false;
1207         thirdPartyCookiesEnabled = false;
1208         domStorageEnabled = false;
1209         saveFormDataEnabled = false;  // Form data can be removed once the minimum API >= 26.
1210         nightMode = false;
1211
1212         // Initialize the WebView title.
1213         webViewTitle = getString(R.string.no_title);
1214
1215         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1216         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1217         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1218         assert favoriteIconBitmapDrawable != null;
1219         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1220
1221         // If the favorite icon is null, load the default.
1222         if (favoriteIconBitmap == null) {
1223             favoriteIconBitmap = favoriteIconDefaultBitmap;
1224         }
1225
1226         // Initialize the user agent array adapter and string array.
1227         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1228         userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1229
1230         // Apply the app settings from the shared preferences.
1231         applyAppSettings();
1232
1233         // Instantiate the block list helper.
1234         BlockListHelper blockListHelper = new BlockListHelper();
1235
1236         // Initialize the list of resource requests.
1237         resourceRequests = new ArrayList<>();
1238
1239         // Parse the block lists.
1240         final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1241         final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1242         final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1243         final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1244         final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1245
1246         // Store the list versions.
1247         easyListVersion = easyList.get(0).get(0)[0];
1248         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1249         fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1250         fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1251         ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1252
1253         mainWebView.setWebViewClient(new WebViewClient() {
1254             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1255             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1256             @SuppressWarnings("deprecation")
1257             @Override
1258             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1259                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
1260                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1261                     formattedUrlString = "";
1262
1263                     // Apply the domain settings for the new URL.  `applyDomainSettings` doesn't do anything if the domain has not changed.
1264                     applyDomainSettings(url, true, false);
1265
1266                     // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1267                     return false;
1268                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1269                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1270                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1271
1272                     // Parse the url and set it as the data for the intent.
1273                     emailIntent.setData(Uri.parse(url));
1274
1275                     // Open the email program in a new task instead of as part of Privacy Browser.
1276                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1277
1278                     // Make it so.
1279                     startActivity(emailIntent);
1280
1281                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1282                     return true;
1283                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1284                     // Open the dialer and load the phone number, but wait for the user to place the call.
1285                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1286
1287                     // Add the phone number to the intent.
1288                     dialIntent.setData(Uri.parse(url));
1289
1290                     // Open the dialer in a new task instead of as part of Privacy Browser.
1291                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1292
1293                     // Make it so.
1294                     startActivity(dialIntent);
1295
1296                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1297                     return true;
1298                 } else {  // Load a system chooser to select an app that can handle the URL.
1299                     // Open an app that can handle the URL.
1300                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1301
1302                     // Add the URL to the intent.
1303                     genericIntent.setData(Uri.parse(url));
1304
1305                     // List all apps that can handle the URL instead of just opening the first one.
1306                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1307
1308                     // Open the app in a new task instead of as part of Privacy Browser.
1309                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1310
1311                     // Start the app or display a snackbar if no app is available to handle the URL.
1312                     try {
1313                         startActivity(genericIntent);
1314                     } catch (ActivityNotFoundException exception) {
1315                         Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
1316                     }
1317
1318                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1319                     return true;
1320                 }
1321             }
1322
1323             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1324             @SuppressWarnings("deprecation")
1325             @Override
1326             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1327                 // Create an empty web resource response to be used if the resource request is blocked.
1328                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1329
1330                 // Reset the whitelist results tracker.
1331                 whiteListResultStringArray = null;
1332
1333                 // Initialize the third party request tracker.
1334                 boolean isThirdPartyRequest = false;
1335
1336                 // Initialize the current domain string.
1337                 String currentDomain = "";
1338
1339                 // Nobody is happy when comparing null strings.
1340                 if (!(formattedUrlString == null) && !(url == null)) {
1341                     // Get the domain strings to URIs.
1342                     Uri currentDomainUri = Uri.parse(formattedUrlString);
1343                     Uri requestDomainUri = Uri.parse(url);
1344
1345                     // Get the domain host names.
1346                     String currentBaseDomain = currentDomainUri.getHost();
1347                     String requestBaseDomain = requestDomainUri.getHost();
1348
1349                     // Update the current domain variable.
1350                     currentDomain = currentBaseDomain;
1351
1352                     // Only compare the current base domain and the request base domain if neither is null.
1353                     if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1354                         // Determine the current base domain.
1355                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1356                             // Remove the first subdomain.
1357                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1358                         }
1359
1360                         // Determine the request base domain.
1361                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1362                             // Remove the first subdomain.
1363                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1364                         }
1365
1366                         // Update the third party request tracker.
1367                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1368                     }
1369                 }
1370
1371                 // Block third-party requests if enabled.
1372                 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1373                     // Increment the third-party blocked requests counter.
1374                     thirdPartyBlockedRequests++;
1375
1376                     // Add the request to the log.
1377                     resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1378
1379                     // Return an empty web resource response.
1380                     return emptyWebResourceResponse;
1381                 }
1382
1383                 // Check UltraPrivacy if it is enabled.
1384                 if (ultraPrivacyEnabled) {
1385                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1386                         // Increment the UltraPrivacy blocked requests counter.
1387                         ultraPrivacyBlockedRequests++;
1388
1389                         // The resource request was blocked.  Return an empty web resource response.
1390                         return emptyWebResourceResponse;
1391                     }
1392
1393                     // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1394                     if (whiteListResultStringArray != null) {
1395                         // Add a whitelist entry to the resource requests array.
1396                         resourceRequests.add(whiteListResultStringArray);
1397
1398                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
1399                         return null;
1400                     }
1401                 }
1402
1403                 // Check EasyList if it is enabled.
1404                 if (easyListEnabled) {
1405                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1406                         // Increment the EasyList blocked requests counter.
1407                         easyListBlockedRequests++;
1408
1409                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1410                         whiteListResultStringArray = null;
1411
1412                         // The resource request was blocked.  Return an empty web resource response.
1413                         return emptyWebResourceResponse;
1414                     }
1415                 }
1416
1417                 // Check EasyPrivacy if it is enabled.
1418                 if (easyPrivacyEnabled) {
1419                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1420                         // Increment the EasyPrivacy blocked requests counter.
1421                         easyPrivacyBlockedRequests++;
1422
1423                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1424                         whiteListResultStringArray = null;
1425
1426                         // The resource request was blocked.  Return an empty web resource response.
1427                         return emptyWebResourceResponse;
1428                     }
1429                 }
1430
1431                 // Check Fanboy’s Annoyance List if it is enabled.
1432                 if (fanboysAnnoyanceListEnabled) {
1433                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1434                         // Increment the Fanboy's Annoyance List blocked requests counter.
1435                         fanboysAnnoyanceListBlockedRequests++;
1436
1437                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1438                         whiteListResultStringArray = null;
1439
1440                         // The resource request was blocked.  Return an empty web resource response.
1441                         return emptyWebResourceResponse;
1442                     }
1443                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1444                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1445                         // Increment the Fanboy's Social Blocking List blocked requests counter.
1446                         fanboysSocialBlockingListBlockedRequests++;
1447
1448                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1449                         whiteListResultStringArray = null;
1450
1451                         // The resource request was blocked.  Return an empty web resource response.
1452                         return emptyWebResourceResponse;
1453                     }
1454                 }
1455
1456                 // Add the request to the log because it hasn't been processed by any of the previous checks.
1457                 if (whiteListResultStringArray != null ) {  // The request was processed by a whitelist.
1458                     resourceRequests.add(whiteListResultStringArray);
1459                 } else {  // The request didn't match any blocklist entry.  Log it as a defult request.
1460                     resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1461                 }
1462
1463                 // The resource request has not been blocked.  `return null` loads the requested resource.
1464                 return null;
1465             }
1466
1467             // Handle HTTP authentication requests.
1468             @Override
1469             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1470                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1471                 httpAuthHandler = handler;
1472
1473                 // Display the HTTP authentication dialog.
1474                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1475                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1476             }
1477
1478             // Update the URL in urlTextBox when the page starts to load.
1479             @Override
1480             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1481                 // Reset the list of resource requests.
1482                 resourceRequests.clear();
1483
1484                 // Initialize the counters for requests blocked by each blocklist.
1485                 easyListBlockedRequests = 0;
1486                 easyPrivacyBlockedRequests = 0;
1487                 fanboysAnnoyanceListBlockedRequests = 0;
1488                 fanboysSocialBlockingListBlockedRequests = 0;
1489                 ultraPrivacyBlockedRequests = 0;
1490                 thirdPartyBlockedRequests = 0;
1491
1492                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1493                 if (nightMode) {
1494                     mainWebView.setVisibility(View.INVISIBLE);
1495                 }
1496
1497                 // Hide the keyboard.  `0` indicates no additional flags.
1498                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1499
1500                 // Check to see if Privacy Browser is waiting on Orbot.
1501                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1502                     // 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.
1503                     formattedUrlString = url;
1504
1505                     // Display the formatted URL text.
1506                     urlTextBox.setText(formattedUrlString);
1507
1508                     // Apply text highlighting to `urlTextBox`.
1509                     highlightUrlText();
1510
1511                     // Apply any custom domain settings if the URL was loaded by navigating history.
1512                     if (navigatingHistory) {
1513                         // Reset `navigatingHistory`.
1514                         navigatingHistory = false;
1515
1516                         // Apply the domain settings.
1517                         applyDomainSettings(url, true, false);
1518                     }
1519
1520                     // 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.
1521                     urlIsLoading = true;
1522
1523                     // Replace Refresh with Stop if the menu item has been created.  (The WebView typically begins loading before the menu items are instantiated.)
1524                     if (refreshMenuItem != null) {
1525                         // Set the title.
1526                         refreshMenuItem.setTitle(R.string.stop);
1527
1528                         // If the icon is displayed in the AppBar, set it according to the theme.
1529                         if (displayAdditionalAppBarIcons) {
1530                             if (darkTheme) {
1531                                 refreshMenuItem.setIcon(R.drawable.close_dark);
1532                             } else {
1533                                 refreshMenuItem.setIcon(R.drawable.close_light);
1534                             }
1535                         }
1536                     }
1537                 }
1538             }
1539
1540             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1541             @Override
1542             public void onPageFinished(WebView view, String url) {
1543                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1544                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1545                     cookieManager.flush();
1546                 }
1547
1548                 // Update the Refresh menu item if it has been created.
1549                 if (refreshMenuItem != null) {
1550                     // Reset the Refresh title.
1551                     refreshMenuItem.setTitle(R.string.refresh);
1552
1553                     // If the icon is displayed in the AppBar, reset it according to the theme.
1554                     if (displayAdditionalAppBarIcons) {
1555                         if (darkTheme) {
1556                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1557                         } else {
1558                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1559                         }
1560                     }
1561                 }
1562
1563                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1564                 urlIsLoading = false;
1565
1566                 // Clear the cache and history if Incognito Mode is enabled.
1567                 if (incognitoModeEnabled) {
1568                     // Clear the cache.  `true` includes disk files.
1569                     mainWebView.clearCache(true);
1570
1571                     // Clear the back/forward history.
1572                     mainWebView.clearHistory();
1573
1574                     // Manually delete cache folders.
1575                     try {
1576                         // Delete the main cache directory.
1577                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1578
1579                         // Delete the secondary `Service Worker` cache directory.
1580                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1581                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1582                     } catch (IOException e) {
1583                         // Do nothing if an error is thrown.
1584                     }
1585                 }
1586
1587                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1588                 if (!waitingForOrbot) {
1589                     // Check to see if `WebView` has set `url` to be `about:blank`.
1590                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1591                         // Set `formattedUrlString` to `""`.
1592                         formattedUrlString = "";
1593
1594                         urlTextBox.setText(formattedUrlString);
1595
1596                         // Request focus for `urlTextBox`.
1597                         urlTextBox.requestFocus();
1598
1599                         // Display the keyboard.
1600                         inputMethodManager.showSoftInput(urlTextBox, 0);
1601
1602                         // Apply the domain settings.  This clears any settings from the previous domain.
1603                         applyDomainSettings(formattedUrlString, true, false);
1604                     } else {  // `WebView` has loaded a webpage.
1605                         // Set `formattedUrlString`.
1606                         formattedUrlString = url;
1607
1608                         // Only update `urlTextBox` if the user is not typing in it.
1609                         if (!urlTextBox.hasFocus()) {
1610                             // Display the formatted URL text.
1611                             urlTextBox.setText(formattedUrlString);
1612
1613                             // Apply text highlighting to `urlTextBox`.
1614                             highlightUrlText();
1615                         }
1616                     }
1617
1618                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1619                     sslCertificate = mainWebView.getCertificate();
1620
1621                     // 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.
1622                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1623                         // Initialize the current SSL certificate variables.
1624                         String currentWebsiteIssuedToCName = "";
1625                         String currentWebsiteIssuedToOName = "";
1626                         String currentWebsiteIssuedToUName = "";
1627                         String currentWebsiteIssuedByCName = "";
1628                         String currentWebsiteIssuedByOName = "";
1629                         String currentWebsiteIssuedByUName = "";
1630                         Date currentWebsiteSslStartDate = null;
1631                         Date currentWebsiteSslEndDate = null;
1632
1633
1634                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1635                         if (sslCertificate != null) {
1636                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1637                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1638                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1639                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1640                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1641                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1642                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1643                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1644                         }
1645
1646                         // 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`.
1647                         String currentWebsiteSslStartDateString = "";
1648                         String currentWebsiteSslEndDateString = "";
1649                         String pinnedDomainSslStartDateString = "";
1650                         String pinnedDomainSslEndDateString = "";
1651
1652                         // Convert the `Dates` to `Strings` if they are not `null`.
1653                         if (currentWebsiteSslStartDate != null) {
1654                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1655                         }
1656
1657                         if (currentWebsiteSslEndDate != null) {
1658                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1659                         }
1660
1661                         if (pinnedDomainSslStartDate != null) {
1662                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1663                         }
1664
1665                         if (pinnedDomainSslEndDate != null) {
1666                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1667                         }
1668
1669                         // Check to see if the pinned SSL certificate matches the current website certificate.
1670                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1671                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1672                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1673                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1674                             // The pinned SSL certificate doesn't match the current domain certificate.
1675                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1676                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1677                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1678                         }
1679                     }
1680                 }
1681             }
1682
1683             // Handle SSL Certificate errors.
1684             @Override
1685             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1686                 // Get the current website SSL certificate.
1687                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1688
1689                 // Extract the individual pieces of information from the current website SSL certificate.
1690                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1691                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1692                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1693                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1694                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1695                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1696                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1697                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1698
1699                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1700                 if (pinnedDomainSslCertificate &&
1701                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1702                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1703                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1704                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1705                     // An SSL certificate is pinned and matches the current domain certificate.
1706                     // Proceed to the website without displaying an error.
1707                     handler.proceed();
1708                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1709                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1710                     sslErrorHandler = handler;
1711
1712                     // Display the SSL error `AlertDialog`.
1713                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1714                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1715                 }
1716             }
1717         });
1718
1719         // Load the website if not waiting for Orbot to connect.
1720         if (!waitingForOrbot) {
1721             loadUrl(formattedUrlString);
1722         }
1723     }
1724
1725     @Override
1726     protected void onNewIntent(Intent intent) {
1727         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1728         setIntent(intent);
1729
1730         // Check to see if the intent contains a new URL.
1731         if (intent.getData() != null) {
1732             // Get the intent data.
1733             final Uri intentUriData = intent.getData();
1734
1735             // Load the website.
1736             loadUrl(intentUriData.toString());
1737
1738             // Close the navigation drawer if it is open.
1739             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1740                 drawerLayout.closeDrawer(GravityCompat.START);
1741             }
1742
1743             // Close the bookmarks drawer if it is open.
1744             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1745                 drawerLayout.closeDrawer(GravityCompat.END);
1746             }
1747
1748             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1749             mainWebView.requestFocus();
1750         }
1751     }
1752
1753     @Override
1754     public void onRestart() {
1755         // Run the default commands.
1756         super.onRestart();
1757
1758         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1759         if (proxyThroughOrbot) {
1760             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1761             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1762
1763             // Send the intent to the Orbot package.
1764             orbotIntent.setPackage("org.torproject.android");
1765
1766             // Make it so.
1767             sendBroadcast(orbotIntent);
1768         }
1769
1770         // Apply the app settings if returning from the Settings activity..
1771         if (reapplyAppSettingsOnRestart) {
1772             // Apply the app settings.
1773             applyAppSettings();
1774
1775             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1776             if (reloadOnRestart) {
1777                 // Reload `mainWebView`.
1778                 mainWebView.reload();
1779
1780                 // Reset `reloadOnRestartBoolean`.
1781                 reloadOnRestart = false;
1782             }
1783
1784             // Reset the return from settings flag.
1785             reapplyAppSettingsOnRestart = false;
1786         }
1787
1788         // Apply the domain settings if returning from the Domains activity.
1789         if (reapplyDomainSettingsOnRestart) {
1790             // Reapply the domain settings.
1791             applyDomainSettings(formattedUrlString, false, true);
1792
1793             // Reset `reapplyDomainSettingsOnRestart`.
1794             reapplyDomainSettingsOnRestart = false;
1795         }
1796
1797         // Load the URL on restart to apply changes to night mode.
1798         if (loadUrlOnRestart) {
1799             // Load the current `formattedUrlString`.
1800             loadUrl(formattedUrlString);
1801
1802             // Reset `loadUrlOnRestart.
1803             loadUrlOnRestart = false;
1804         }
1805
1806         // Update the bookmarks drawer if returning from the Bookmarks activity.
1807         if (restartFromBookmarksActivity) {
1808             // Close the bookmarks drawer.
1809             drawerLayout.closeDrawer(GravityCompat.END);
1810
1811             // Reload the bookmarks drawer.
1812             loadBookmarksFolder();
1813
1814             // Reset `restartFromBookmarksActivity`.
1815             restartFromBookmarksActivity = false;
1816         }
1817
1818         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1819         updatePrivacyIcons(true);
1820     }
1821
1822     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1823     @Override
1824     public void onResume() {
1825         // Run the default commands.
1826         super.onResume();
1827
1828         // Resume JavaScript (if enabled).
1829         mainWebView.resumeTimers();
1830
1831         // Resume `mainWebView`.
1832         mainWebView.onResume();
1833
1834         // Resume the adView for the free flavor.
1835         if (BuildConfig.FLAVOR.contentEquals("free")) {
1836             // Resume the ad.
1837             AdHelper.resumeAd(findViewById(R.id.adview));
1838         }
1839
1840         // Display a message to the user if waiting for Orbot.
1841         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1842             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1843             mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1844         }
1845
1846         if (displayingFullScreenVideo) {
1847             // Remove the translucent overlays.
1848             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1849
1850             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1851             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1852
1853             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1854              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1855              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1856              */
1857             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1858         }
1859     }
1860
1861     @Override
1862     public void onPause() {
1863         // Run the default commands.
1864         super.onPause();
1865
1866         // Pause `mainWebView`.
1867         mainWebView.onPause();
1868
1869         // Stop all JavaScript.
1870         mainWebView.pauseTimers();
1871
1872         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1873         if (BuildConfig.FLAVOR.contentEquals("free")) {
1874             // Pause the ad.
1875             AdHelper.pauseAd(findViewById(R.id.adview));
1876         }
1877     }
1878
1879     @Override
1880     public void onDestroy() {
1881         // Unregister the Orbot status broadcast receiver.
1882         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1883
1884         // Run the default commands.
1885         super.onDestroy();
1886     }
1887
1888     @Override
1889     public boolean onCreateOptionsMenu(Menu menu) {
1890         // Inflate the menu; this adds items to the action bar if it is present.
1891         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1892
1893         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1894         mainMenu = menu;
1895
1896         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1897         updatePrivacyIcons(false);
1898
1899         // Get handles for the menu items.
1900         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1901         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1902         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1903         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1904         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1905         refreshMenuItem = menu.findItem(R.id.refresh);
1906         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1907
1908         // Only display third-party cookies if API >= 21
1909         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1910
1911         // Only display the form data menu items if the API < 26.
1912         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1913         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1914
1915         // Only show Ad Consent if this is the free flavor.
1916         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1917
1918         // Get the shared preference values.
1919         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1920
1921         // Get the status of the additional AppBar icons.
1922         displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1923
1924         // Set the status of the additional app bar icons.  Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
1925         if (displayAdditionalAppBarIcons) {
1926             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1927             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1928             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1929         } else { //Do not display the additional icons.
1930             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1931             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1932             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1933         }
1934
1935         // Replace Refresh with Stop if a URL is already loading.
1936         if (urlIsLoading) {
1937             // Set the title.
1938             refreshMenuItem.setTitle(R.string.stop);
1939
1940             // If the icon is displayed in the AppBar, set it according to the theme.
1941             if (displayAdditionalAppBarIcons) {
1942                 if (darkTheme) {
1943                     refreshMenuItem.setIcon(R.drawable.close_dark);
1944                 } else {
1945                     refreshMenuItem.setIcon(R.drawable.close_light);
1946                 }
1947             }
1948         }
1949
1950         return true;
1951     }
1952
1953     @Override
1954     public boolean onPrepareOptionsMenu(Menu menu) {
1955         // Get handles for the menu items.
1956         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1957         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1958         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1959         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1960         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1961         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1962         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1963         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1964         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1965         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1966         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1967         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1968         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1969         MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1970         MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1971         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1972         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1973         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1974
1975         // Set the text for the domain menu item.
1976         if (domainSettingsApplied) {
1977             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1978         } else {
1979             addOrEditDomain.setTitle(R.string.add_domain_settings);
1980         }
1981
1982         // Set the status of the menu item checkboxes.
1983         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1984         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1985         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1986         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1987         easyListMenuItem.setChecked(easyListEnabled);
1988         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1989         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1990         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1991         ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1992         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1993         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1994         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1995
1996         // Enable third-party cookies if first-party cookies are enabled.
1997         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1998
1999         // Enable DOM Storage if JavaScript is enabled.
2000         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2001
2002         // Enable Clear Cookies if there are any.
2003         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2004
2005         // Get a count of the number of files in the Local Storage directory.
2006         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2007         int localStorageDirectoryNumberOfFiles = 0;
2008         if (localStorageDirectory.exists()) {
2009             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2010         }
2011
2012         // Get a count of the number of files in the IndexedDB directory.
2013         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2014         int indexedDBDirectoryNumberOfFiles = 0;
2015         if (indexedDBDirectory.exists()) {
2016             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2017         }
2018
2019         // Enable Clear DOM Storage if there is any.
2020         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2021
2022         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
2023         if (Build.VERSION.SDK_INT < 26) {
2024             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2025             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2026         } else {
2027             // Disable clear form data because it is not supported on current version of Android.
2028             clearFormDataMenuItem.setEnabled(false);
2029         }
2030
2031         // Enable Clear Data if any of the submenu items are enabled.
2032         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2033
2034         // Update the display names for the blocklists with the number of blocked requests.
2035         easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2036         easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2037         fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2038         fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2039         ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2040         blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2041
2042         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2043         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2044
2045         // Initialize font size variables.
2046         int fontSize = mainWebView.getSettings().getTextZoom();
2047         String fontSizeTitle;
2048         MenuItem selectedFontSizeMenuItem;
2049
2050         // Prepare the font size title and current size menu item.
2051         switch (fontSize) {
2052             case 25:
2053                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2054                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2055                 break;
2056
2057             case 50:
2058                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2059                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2060                 break;
2061
2062             case 75:
2063                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2064                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2065                 break;
2066
2067             case 100:
2068                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2069                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2070                 break;
2071
2072             case 125:
2073                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2074                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2075                 break;
2076
2077             case 150:
2078                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2079                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2080                 break;
2081
2082             case 175:
2083                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2084                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2085                 break;
2086
2087             case 200:
2088                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2089                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2090                 break;
2091
2092             default:
2093                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2094                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2095                 break;
2096         }
2097
2098         // Set the font size title and select the current size menu item.
2099         fontSizeMenuItem.setTitle(fontSizeTitle);
2100         selectedFontSizeMenuItem.setChecked(true);
2101
2102         // Run all the other default commands.
2103         super.onPrepareOptionsMenu(menu);
2104
2105         // Display the menu.
2106         return true;
2107     }
2108
2109     @Override
2110     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2111     @SuppressLint("SetJavaScriptEnabled")
2112     // removeAllCookies is deprecated, but it is required for API < 21.
2113     @SuppressWarnings("deprecation")
2114     public boolean onOptionsItemSelected(MenuItem menuItem) {
2115         // Get the selected menu item ID.
2116         int menuItemId = menuItem.getItemId();
2117
2118         // Set the commands that relate to the menu entries.
2119         switch (menuItemId) {
2120             case R.id.toggle_javascript:
2121                 // Switch the status of javaScriptEnabled.
2122                 javaScriptEnabled = !javaScriptEnabled;
2123
2124                 // Apply the new JavaScript status.
2125                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2126
2127                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2128                 updatePrivacyIcons(true);
2129
2130                 // Display a `Snackbar`.
2131                 if (javaScriptEnabled) {  // JavaScrip is enabled.
2132                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2133                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
2134                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2135                 } else {  // Privacy mode.
2136                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2137                 }
2138
2139                 // Reload the WebView.
2140                 mainWebView.reload();
2141                 return true;
2142
2143             case R.id.add_or_edit_domain:
2144                 if (domainSettingsApplied) {  // Edit the current domain settings.
2145                     // Reapply the domain settings on returning to `MainWebViewActivity`.
2146                     reapplyDomainSettingsOnRestart = true;
2147                     currentDomainName = "";
2148
2149                     // Create an intent to launch the domains activity.
2150                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2151
2152                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2153                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2154                     domainsIntent.putExtra("closeOnBack", true);
2155
2156                     // Make it so.
2157                     startActivity(domainsIntent);
2158                 } else {  // Add a new domain.
2159                     // Apply the new domain settings on returning to `MainWebViewActivity`.
2160                     reapplyDomainSettingsOnRestart = true;
2161                     currentDomainName = "";
2162
2163                     // Get the current domain
2164                     Uri currentUri = Uri.parse(formattedUrlString);
2165                     String currentDomain = currentUri.getHost();
2166
2167                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2168                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2169
2170                     // Create the domain and store the database ID.
2171                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2172
2173                     // Create an intent to launch the domains activity.
2174                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2175
2176                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2177                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2178                     domainsIntent.putExtra("closeOnBack", true);
2179
2180                     // Make it so.
2181                     startActivity(domainsIntent);
2182                 }
2183                 return true;
2184
2185             case R.id.toggle_first_party_cookies:
2186                 // Switch the status of firstPartyCookiesEnabled.
2187                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2188
2189                 // Update the menu checkbox.
2190                 menuItem.setChecked(firstPartyCookiesEnabled);
2191
2192                 // Apply the new cookie status.
2193                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2194
2195                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2196                 updatePrivacyIcons(true);
2197
2198                 // Display a `Snackbar`.
2199                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2200                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2201                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
2202                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2203                 } else {  // Privacy mode.
2204                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2205                 }
2206
2207                 // Reload the WebView.
2208                 mainWebView.reload();
2209                 return true;
2210
2211             case R.id.toggle_third_party_cookies:
2212                 if (Build.VERSION.SDK_INT >= 21) {
2213                     // Switch the status of thirdPartyCookiesEnabled.
2214                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2215
2216                     // Update the menu checkbox.
2217                     menuItem.setChecked(thirdPartyCookiesEnabled);
2218
2219                     // Apply the new cookie status.
2220                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2221
2222                     // Display a `Snackbar`.
2223                     if (thirdPartyCookiesEnabled) {
2224                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2225                     } else {
2226                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2227                     }
2228
2229                     // Reload the WebView.
2230                     mainWebView.reload();
2231                 } // Else do nothing because SDK < 21.
2232                 return true;
2233
2234             case R.id.toggle_dom_storage:
2235                 // Switch the status of domStorageEnabled.
2236                 domStorageEnabled = !domStorageEnabled;
2237
2238                 // Update the menu checkbox.
2239                 menuItem.setChecked(domStorageEnabled);
2240
2241                 // Apply the new DOM Storage status.
2242                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2243
2244                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2245                 updatePrivacyIcons(true);
2246
2247                 // Display a `Snackbar`.
2248                 if (domStorageEnabled) {
2249                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2250                 } else {
2251                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2252                 }
2253
2254                 // Reload the WebView.
2255                 mainWebView.reload();
2256                 return true;
2257
2258             // Form data can be removed once the minimum API >= 26.
2259             case R.id.toggle_save_form_data:
2260                 // Switch the status of saveFormDataEnabled.
2261                 saveFormDataEnabled = !saveFormDataEnabled;
2262
2263                 // Update the menu checkbox.
2264                 menuItem.setChecked(saveFormDataEnabled);
2265
2266                 // Apply the new form data status.
2267                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2268
2269                 // Display a `Snackbar`.
2270                 if (saveFormDataEnabled) {
2271                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2272                 } else {
2273                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2274                 }
2275
2276                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2277                 updatePrivacyIcons(true);
2278
2279                 // Reload the WebView.
2280                 mainWebView.reload();
2281                 return true;
2282
2283             case R.id.clear_cookies:
2284                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2285                         .setAction(R.string.undo, v -> {
2286                             // Do nothing because everything will be handled by `onDismissed()` below.
2287                         })
2288                         .addCallback(new Snackbar.Callback() {
2289                             @Override
2290                             public void onDismissed(Snackbar snackbar, int event) {
2291                                 switch (event) {
2292                                     // The user pushed the `Undo` button.
2293                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2294                                         // Do nothing.
2295                                         break;
2296
2297                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2298                                     default:
2299                                         // `cookieManager.removeAllCookie()` varies by SDK.
2300                                         if (Build.VERSION.SDK_INT < 21) {
2301                                             cookieManager.removeAllCookie();
2302                                         } else {
2303                                             // `null` indicates no callback.
2304                                             cookieManager.removeAllCookies(null);
2305                                         }
2306                                 }
2307                             }
2308                         })
2309                         .show();
2310                 return true;
2311
2312             case R.id.clear_dom_storage:
2313                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2314                         .setAction(R.string.undo, v -> {
2315                             // Do nothing because everything will be handled by `onDismissed()` below.
2316                         })
2317                         .addCallback(new Snackbar.Callback() {
2318                             @Override
2319                             public void onDismissed(Snackbar snackbar, int event) {
2320                                 switch (event) {
2321                                     // The user pushed the `Undo` button.
2322                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2323                                         // Do nothing.
2324                                         break;
2325
2326                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2327                                     default:
2328                                         // Delete the DOM Storage.
2329                                         WebStorage webStorage = WebStorage.getInstance();
2330                                         webStorage.deleteAllData();
2331
2332                                         // Manually delete the DOM storage files and directories.
2333                                         try {
2334                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2335                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2336
2337                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2338                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2339                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2340                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2341                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2342                                         } catch (IOException e) {
2343                                             // Do nothing if an error is thrown.
2344                                         }
2345                                 }
2346                             }
2347                         })
2348                         .show();
2349                 return true;
2350
2351             // Form data can be remove once the minimum API >= 26.
2352             case R.id.clear_form_data:
2353                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2354                         .setAction(R.string.undo, v -> {
2355                             // Do nothing because everything will be handled by `onDismissed()` below.
2356                         })
2357                         .addCallback(new Snackbar.Callback() {
2358                             @Override
2359                             public void onDismissed(Snackbar snackbar, int event) {
2360                                 switch (event) {
2361                                     // The user pushed the `Undo` button.
2362                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2363                                         // Do nothing.
2364                                         break;
2365
2366                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2367                                     default:
2368                                         // Delete the form data.
2369                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2370                                         mainWebViewDatabase.clearFormData();
2371                                 }
2372                             }
2373                         })
2374                         .show();
2375                 return true;
2376
2377             case R.id.font_size_twenty_five_percent:
2378                 mainWebView.getSettings().setTextZoom(25);
2379                 return true;
2380
2381             case R.id.font_size_fifty_percent:
2382                 mainWebView.getSettings().setTextZoom(50);
2383                 return true;
2384
2385             case R.id.font_size_seventy_five_percent:
2386                 mainWebView.getSettings().setTextZoom(75);
2387                 return true;
2388
2389             case R.id.font_size_one_hundred_percent:
2390                 mainWebView.getSettings().setTextZoom(100);
2391                 return true;
2392
2393             case R.id.font_size_one_hundred_twenty_five_percent:
2394                 mainWebView.getSettings().setTextZoom(125);
2395                 return true;
2396
2397             case R.id.font_size_one_hundred_fifty_percent:
2398                 mainWebView.getSettings().setTextZoom(150);
2399                 return true;
2400
2401             case R.id.font_size_one_hundred_seventy_five_percent:
2402                 mainWebView.getSettings().setTextZoom(175);
2403                 return true;
2404
2405             case R.id.font_size_two_hundred_percent:
2406                 mainWebView.getSettings().setTextZoom(200);
2407                 return true;
2408
2409             case R.id.swipe_to_refresh:
2410                 // Toggle swipe to refresh.
2411                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2412                 return true;
2413
2414             case R.id.display_images:
2415                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2416                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2417                     mainWebView.reload();
2418                 } else {  // Images are not currently loaded automatically.
2419                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2420                 }
2421
2422                 // Set `onTheFlyDisplayImagesSet`.
2423                 onTheFlyDisplayImagesSet = true;
2424                 return true;
2425
2426             case R.id.view_source:
2427                 // Launch the View Source activity.
2428                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2429                 startActivity(viewSourceIntent);
2430                 return true;
2431
2432             case R.id.easylist:
2433                 // Toggle the EasyList status.
2434                 easyListEnabled = !easyListEnabled;
2435
2436                 // Update the menu checkbox.
2437                 menuItem.setChecked(easyListEnabled);
2438
2439                 // Reload the main WebView.
2440                 mainWebView.reload();
2441                 return true;
2442
2443             case R.id.easyprivacy:
2444                 // Toggle the EasyPrivacy status.
2445                 easyPrivacyEnabled = !easyPrivacyEnabled;
2446
2447                 // Update the menu checkbox.
2448                 menuItem.setChecked(easyPrivacyEnabled);
2449
2450                 // Reload the main WebView.
2451                 mainWebView.reload();
2452                 return true;
2453
2454             case R.id.fanboys_annoyance_list:
2455                 // Toggle Fanboy's Annoyance List status.
2456                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2457
2458                 // Update the menu checkbox.
2459                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2460
2461                 // Update the staus of Fanboy's Social Blocking List.
2462                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2463                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2464
2465                 // Reload the main WebView.
2466                 mainWebView.reload();
2467                 return true;
2468
2469             case R.id.fanboys_social_blocking_list:
2470                 // Toggle Fanboy's Social Blocking List status.
2471                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2472
2473                 // Update the menu checkbox.
2474                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2475
2476                 // Reload the main WebView.
2477                 mainWebView.reload();
2478                 return true;
2479
2480             case R.id.ultraprivacy:
2481                 // Toggle the UltraPrivacy status.
2482                 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2483
2484                 // Update the menu checkbox.
2485                 menuItem.setChecked(ultraPrivacyEnabled);
2486
2487                 // Reload the main WebView.
2488                 mainWebView.reload();
2489                 return true;
2490
2491             case R.id.block_all_third_party_requests:
2492                 //Toggle the third-party requests blocker status.
2493                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2494
2495                 // Update the menu checkbox.
2496                 menuItem.setChecked(blockAllThirdPartyRequests);
2497
2498                 // Reload the main WebView.
2499                 mainWebView.reload();
2500                 return true;
2501
2502             case R.id.share:
2503                 // Setup the share string.
2504                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2505
2506                 // Create the share intent.
2507                 Intent shareIntent = new Intent();
2508                 shareIntent.setAction(Intent.ACTION_SEND);
2509                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2510                 shareIntent.setType("text/plain");
2511
2512                 // Make it so.
2513                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2514                 return true;
2515
2516             case R.id.find_on_page:
2517                 // Hide the URL app bar.
2518                 supportAppBar.setVisibility(View.GONE);
2519
2520                 // Show the Find on Page `RelativeLayout`.
2521                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2522
2523                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2524                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2525                 findOnPageEditText.postDelayed(() -> {
2526                     // Set the focus on `findOnPageEditText`.
2527                     findOnPageEditText.requestFocus();
2528
2529                     // Display the keyboard.  `0` sets no input flags.
2530                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2531                 }, 200);
2532                 return true;
2533
2534             case R.id.print:
2535                 // Get a `PrintManager` instance.
2536                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2537
2538                 // Convert `mainWebView` to `printDocumentAdapter`.
2539                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2540
2541                 // Remove the lint error below that `printManager` might be `null`.
2542                 assert printManager != null;
2543
2544                 // Print the document.  The print attributes are `null`.
2545                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2546                 return true;
2547
2548             case R.id.add_to_homescreen:
2549                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2550                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2551                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2552
2553                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2554                 return true;
2555
2556             case R.id.refresh:
2557                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2558                     // Reload the WebView.
2559                     mainWebView.reload();
2560                 } else {  // The stop button was pushed.
2561                     // Stop the loading of the WebView.
2562                     mainWebView.stopLoading();
2563                 }
2564                 return true;
2565
2566             case R.id.ad_consent:
2567                 // Display the ad consent dialog.
2568                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2569                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2570                 return true;
2571
2572             default:
2573                 // Don't consume the event.
2574                 return super.onOptionsItemSelected(menuItem);
2575         }
2576     }
2577
2578     // removeAllCookies is deprecated, but it is required for API < 21.
2579     @SuppressWarnings("deprecation")
2580     @Override
2581     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2582         int menuItemId = menuItem.getItemId();
2583
2584         switch (menuItemId) {
2585             case R.id.home:
2586                 loadUrl(homepage);
2587                 break;
2588
2589             case R.id.back:
2590                 if (mainWebView.canGoBack()) {
2591                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2592                     formattedUrlString = "";
2593
2594                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2595                     navigatingHistory = true;
2596
2597                     // Load the previous website in the history.
2598                     mainWebView.goBack();
2599                 }
2600                 break;
2601
2602             case R.id.forward: