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