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