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