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