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