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