Fix the waiting for Orbot message size. https://redmine.stoutner.com/issues/319
[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 Privacy Browser is 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                 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
1615                 if (!waitingForOrbot) {
1616                     mainWebView.getSettings().setUseWideViewPort(true);
1617                 }
1618
1619                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1620                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1621                     cookieManager.flush();
1622                 }
1623
1624                 // Update the Refresh menu item if it has been created.
1625                 if (refreshMenuItem != null) {
1626                     // Reset the Refresh title.
1627                     refreshMenuItem.setTitle(R.string.refresh);
1628
1629                     // If the icon is displayed in the AppBar, reset it according to the theme.
1630                     if (displayAdditionalAppBarIcons) {
1631                         if (darkTheme) {
1632                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1633                         } else {
1634                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1635                         }
1636                     }
1637                 }
1638
1639                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1640                 urlIsLoading = false;
1641
1642                 // Clear the cache and history if Incognito Mode is enabled.
1643                 if (incognitoModeEnabled) {
1644                     // Clear the cache.  `true` includes disk files.
1645                     mainWebView.clearCache(true);
1646
1647                     // Clear the back/forward history.
1648                     mainWebView.clearHistory();
1649
1650                     // Manually delete cache folders.
1651                     try {
1652                         // Delete the main cache directory.
1653                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1654
1655                         // Delete the secondary `Service Worker` cache directory.
1656                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1657                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1658                     } catch (IOException e) {
1659                         // Do nothing if an error is thrown.
1660                     }
1661                 }
1662
1663                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1664                 if (!waitingForOrbot) {
1665                     // Check to see if `WebView` has set `url` to be `about:blank`.
1666                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1667                         // Set `formattedUrlString` to `""`.
1668                         formattedUrlString = "";
1669
1670                         urlTextBox.setText(formattedUrlString);
1671
1672                         // Request focus for `urlTextBox`.
1673                         urlTextBox.requestFocus();
1674
1675                         // Display the keyboard.
1676                         inputMethodManager.showSoftInput(urlTextBox, 0);
1677
1678                         // Apply the domain settings.  This clears any settings from the previous domain.
1679                         applyDomainSettings(formattedUrlString, true, false);
1680                     } else {  // `WebView` has loaded a webpage.
1681                         // Set `formattedUrlString`.
1682                         formattedUrlString = url;
1683
1684                         // Only update `urlTextBox` if the user is not typing in it.
1685                         if (!urlTextBox.hasFocus()) {
1686                             // Display the formatted URL text.
1687                             urlTextBox.setText(formattedUrlString);
1688
1689                             // Apply text highlighting to `urlTextBox`.
1690                             highlightUrlText();
1691                         }
1692                     }
1693
1694                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1695                     sslCertificate = mainWebView.getCertificate();
1696
1697                     // 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.
1698                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1699                         // Initialize the current SSL certificate variables.
1700                         String currentWebsiteIssuedToCName = "";
1701                         String currentWebsiteIssuedToOName = "";
1702                         String currentWebsiteIssuedToUName = "";
1703                         String currentWebsiteIssuedByCName = "";
1704                         String currentWebsiteIssuedByOName = "";
1705                         String currentWebsiteIssuedByUName = "";
1706                         Date currentWebsiteSslStartDate = null;
1707                         Date currentWebsiteSslEndDate = null;
1708
1709
1710                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1711                         if (sslCertificate != null) {
1712                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1713                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1714                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1715                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1716                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1717                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1718                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1719                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1720                         }
1721
1722                         // 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`.
1723                         String currentWebsiteSslStartDateString = "";
1724                         String currentWebsiteSslEndDateString = "";
1725                         String pinnedDomainSslStartDateString = "";
1726                         String pinnedDomainSslEndDateString = "";
1727
1728                         // Convert the `Dates` to `Strings` if they are not `null`.
1729                         if (currentWebsiteSslStartDate != null) {
1730                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1731                         }
1732
1733                         if (currentWebsiteSslEndDate != null) {
1734                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1735                         }
1736
1737                         if (pinnedDomainSslStartDate != null) {
1738                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1739                         }
1740
1741                         if (pinnedDomainSslEndDate != null) {
1742                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1743                         }
1744
1745                         // Check to see if the pinned SSL certificate matches the current website certificate.
1746                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1747                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1748                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1749                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1750                             // The pinned SSL certificate doesn't match the current domain certificate.
1751                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1752                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1753                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1754                         }
1755                     }
1756                 }
1757             }
1758
1759             // Handle SSL Certificate errors.
1760             @Override
1761             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1762                 // Get the current website SSL certificate.
1763                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1764
1765                 // Extract the individual pieces of information from the current website SSL certificate.
1766                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1767                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1768                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1769                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1770                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1771                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1772                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1773                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1774
1775                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1776                 if (pinnedDomainSslCertificate &&
1777                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1778                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1779                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1780                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1781                     // An SSL certificate is pinned and matches the current domain certificate.
1782                     // Proceed to the website without displaying an error.
1783                     handler.proceed();
1784                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1785                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1786                     sslErrorHandler = handler;
1787
1788                     // Display the SSL error `AlertDialog`.
1789                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1790                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1791                 }
1792             }
1793         });
1794
1795         // Load the website if not waiting for Orbot to connect.
1796         if (!waitingForOrbot) {
1797             loadUrl(formattedUrlString);
1798         }
1799     }
1800
1801     @Override
1802     protected void onNewIntent(Intent intent) {
1803         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1804         setIntent(intent);
1805
1806         // Check to see if the intent contains a new URL.
1807         if (intent.getData() != null) {
1808             // Get the intent data.
1809             final Uri intentUriData = intent.getData();
1810
1811             // Load the website.
1812             loadUrl(intentUriData.toString());
1813
1814             // Close the navigation drawer if it is open.
1815             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1816                 drawerLayout.closeDrawer(GravityCompat.START);
1817             }
1818
1819             // Close the bookmarks drawer if it is open.
1820             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1821                 drawerLayout.closeDrawer(GravityCompat.END);
1822             }
1823
1824             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1825             mainWebView.requestFocus();
1826         }
1827     }
1828
1829     @Override
1830     public void onRestart() {
1831         // Run the default commands.
1832         super.onRestart();
1833
1834         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1835         if (proxyThroughOrbot) {
1836             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1837             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1838
1839             // Send the intent to the Orbot package.
1840             orbotIntent.setPackage("org.torproject.android");
1841
1842             // Make it so.
1843             sendBroadcast(orbotIntent);
1844         }
1845
1846         // Apply the app settings if returning from the Settings activity..
1847         if (reapplyAppSettingsOnRestart) {
1848             // Apply the app settings.
1849             applyAppSettings();
1850
1851             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1852             if (reloadOnRestart) {
1853                 // Reload `mainWebView`.
1854                 mainWebView.reload();
1855
1856                 // Reset `reloadOnRestartBoolean`.
1857                 reloadOnRestart = false;
1858             }
1859
1860             // Reset the return from settings flag.
1861             reapplyAppSettingsOnRestart = false;
1862         }
1863
1864         // Apply the domain settings if returning from the Domains activity.
1865         if (reapplyDomainSettingsOnRestart) {
1866             // Reapply the domain settings.
1867             applyDomainSettings(formattedUrlString, false, true);
1868
1869             // Reset `reapplyDomainSettingsOnRestart`.
1870             reapplyDomainSettingsOnRestart = false;
1871         }
1872
1873         // Load the URL on restart to apply changes to night mode.
1874         if (loadUrlOnRestart) {
1875             // Load the current `formattedUrlString`.
1876             loadUrl(formattedUrlString);
1877
1878             // Reset `loadUrlOnRestart.
1879             loadUrlOnRestart = false;
1880         }
1881
1882         // Update the bookmarks drawer if returning from the Bookmarks activity.
1883         if (restartFromBookmarksActivity) {
1884             // Close the bookmarks drawer.
1885             drawerLayout.closeDrawer(GravityCompat.END);
1886
1887             // Reload the bookmarks drawer.
1888             loadBookmarksFolder();
1889
1890             // Reset `restartFromBookmarksActivity`.
1891             restartFromBookmarksActivity = false;
1892         }
1893
1894         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1895         updatePrivacyIcons(true);
1896     }
1897
1898     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1899     @Override
1900     public void onResume() {
1901         // Run the default commands.
1902         super.onResume();
1903
1904         // Resume JavaScript (if enabled).
1905         mainWebView.resumeTimers();
1906
1907         // Resume `mainWebView`.
1908         mainWebView.onResume();
1909
1910         // Resume the adView for the free flavor.
1911         if (BuildConfig.FLAVOR.contentEquals("free")) {
1912             // Resume the ad.
1913             AdHelper.resumeAd(findViewById(R.id.adview));
1914         }
1915
1916         // Display a message to the user if waiting for Orbot.
1917         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1918             // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1919             mainWebView.getSettings().setUseWideViewPort(false);
1920
1921             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1922             mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1923         }
1924
1925         if (displayingFullScreenVideo) {
1926             // Remove the translucent overlays.
1927             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1928
1929             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1930             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1931
1932             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1933              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1934              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1935              */
1936             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1937         }
1938     }
1939
1940     @Override
1941     public void onPause() {
1942         // Run the default commands.
1943         super.onPause();
1944
1945         // Pause `mainWebView`.
1946         mainWebView.onPause();
1947
1948         // Stop all JavaScript.
1949         mainWebView.pauseTimers();
1950
1951         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1952         if (BuildConfig.FLAVOR.contentEquals("free")) {
1953             // Pause the ad.
1954             AdHelper.pauseAd(findViewById(R.id.adview));
1955         }
1956     }
1957
1958     @Override
1959     public void onDestroy() {
1960         // Unregister the Orbot status broadcast receiver.
1961         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1962
1963         // Run the default commands.
1964         super.onDestroy();
1965     }
1966
1967     @Override
1968     public boolean onCreateOptionsMenu(Menu menu) {
1969         // Inflate the menu; this adds items to the action bar if it is present.
1970         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1971
1972         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1973         mainMenu = menu;
1974
1975         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1976         updatePrivacyIcons(false);
1977
1978         // Get handles for the menu items.
1979         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1980         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1981         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1982         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1983         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1984         refreshMenuItem = menu.findItem(R.id.refresh);
1985         blocklistsMenuItem = menu.findItem(R.id.blocklists);
1986         easyListMenuItem = menu.findItem(R.id.easylist);
1987         easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1988         fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1989         fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1990         ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1991         blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1992         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1993
1994         // Only display third-party cookies if API >= 21
1995         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1996
1997         // Only display the form data menu items if the API < 26.
1998         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1999         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2000
2001         // Only show Ad Consent if this is the free flavor.
2002         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
2003
2004         // Get the shared preference values.
2005         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2006
2007         // Get the status of the additional AppBar icons.
2008         displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
2009
2010         // 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.
2011         if (displayAdditionalAppBarIcons) {
2012             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2013             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2014             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2015         } else { //Do not display the additional icons.
2016             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2017             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2018             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2019         }
2020
2021         // Replace Refresh with Stop if a URL is already loading.
2022         if (urlIsLoading) {
2023             // Set the title.
2024             refreshMenuItem.setTitle(R.string.stop);
2025
2026             // If the icon is displayed in the AppBar, set it according to the theme.
2027             if (displayAdditionalAppBarIcons) {
2028                 if (darkTheme) {
2029                     refreshMenuItem.setIcon(R.drawable.close_dark);
2030                 } else {
2031                     refreshMenuItem.setIcon(R.drawable.close_light);
2032                 }
2033             }
2034         }
2035
2036         return true;
2037     }
2038
2039     @Override
2040     public boolean onPrepareOptionsMenu(Menu menu) {
2041         // Get handles for the menu items.
2042         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2043         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2044         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2045         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2046         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
2047         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2048         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2049         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2050         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
2051         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2052         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2053         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2054         MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
2055
2056         // Set the text for the domain menu item.
2057         if (domainSettingsApplied) {
2058             addOrEditDomain.setTitle(R.string.edit_domain_settings);
2059         } else {
2060             addOrEditDomain.setTitle(R.string.add_domain_settings);
2061         }
2062
2063         // Set the status of the menu item checkboxes.
2064         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2065         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2066         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2067         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
2068         easyListMenuItem.setChecked(easyListEnabled);
2069         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2070         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2071         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2072         ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2073         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2074         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2075         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2076         nightModeMenuItem.setChecked(nightMode);
2077
2078         // Enable third-party cookies if first-party cookies are enabled.
2079         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2080
2081         // Enable DOM Storage if JavaScript is enabled.
2082         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2083
2084         // Enable Clear Cookies if there are any.
2085         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2086
2087         // Get a count of the number of files in the Local Storage directory.
2088         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2089         int localStorageDirectoryNumberOfFiles = 0;
2090         if (localStorageDirectory.exists()) {
2091             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2092         }
2093
2094         // Get a count of the number of files in the IndexedDB directory.
2095         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2096         int indexedDBDirectoryNumberOfFiles = 0;
2097         if (indexedDBDirectory.exists()) {
2098             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2099         }
2100
2101         // Enable Clear DOM Storage if there is any.
2102         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2103
2104         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
2105         if (Build.VERSION.SDK_INT < 26) {
2106             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2107             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2108         } else {
2109             // Disable clear form data because it is not supported on current version of Android.
2110             clearFormDataMenuItem.setEnabled(false);
2111         }
2112
2113         // Enable Clear Data if any of the submenu items are enabled.
2114         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2115
2116         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2117         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2118
2119         // Initialize the display names for the blocklists with the number of blocked requests.
2120         blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2121         easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2122         easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2123         fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2124         fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2125         ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2126         blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2127
2128         // Get the current user agent.
2129         String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2130
2131         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
2132         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
2133             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2134         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
2135             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2136         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
2137             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2138         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
2139             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2140         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
2141             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2142         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
2143             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2144         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
2145             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2146         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
2147             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2148         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
2149             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2150         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
2151             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2152         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
2153             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2154         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
2155             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2156         } else {  // Custom user agent.
2157             menu.findItem(R.id.user_agent_custom).setChecked(true);
2158         }
2159
2160         // Initialize font size variables.
2161         int fontSize = mainWebView.getSettings().getTextZoom();
2162         String fontSizeTitle;
2163         MenuItem selectedFontSizeMenuItem;
2164
2165         // Prepare the font size title and current size menu item.
2166         switch (fontSize) {
2167             case 25:
2168                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2169                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2170                 break;
2171
2172             case 50:
2173                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2174                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2175                 break;
2176
2177             case 75:
2178                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2179                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2180                 break;
2181
2182             case 100:
2183                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2184                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2185                 break;
2186
2187             case 125:
2188                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2189                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2190                 break;
2191
2192             case 150:
2193                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2194                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2195                 break;
2196
2197             case 175:
2198                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2199                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2200                 break;
2201
2202             case 200:
2203                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2204                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2205                 break;
2206
2207             default:
2208                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2209                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2210                 break;
2211         }
2212
2213         // Set the font size title and select the current size menu item.
2214         fontSizeMenuItem.setTitle(fontSizeTitle);
2215         selectedFontSizeMenuItem.setChecked(true);
2216
2217         // Run all the other default commands.
2218         super.onPrepareOptionsMenu(menu);
2219
2220         // Display the menu.
2221         return true;
2222     }
2223
2224     @Override
2225     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2226     @SuppressLint("SetJavaScriptEnabled")
2227     // removeAllCookies is deprecated, but it is required for API < 21.
2228     @SuppressWarnings("deprecation")
2229     public boolean onOptionsItemSelected(MenuItem menuItem) {
2230         // Get the selected menu item ID.
2231         int menuItemId = menuItem.getItemId();
2232
2233         // Set the commands that relate to the menu entries.
2234         switch (menuItemId) {
2235             case R.id.toggle_javascript:
2236                 // Switch the status of javaScriptEnabled.
2237                 javaScriptEnabled = !javaScriptEnabled;
2238
2239                 // Apply the new JavaScript status.
2240                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2241
2242                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2243                 updatePrivacyIcons(true);
2244
2245                 // Display a `Snackbar`.
2246                 if (javaScriptEnabled) {  // JavaScrip is enabled.
2247                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2248                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
2249                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2250                 } else {  // Privacy mode.
2251                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2252                 }
2253
2254                 // Reload the WebView.
2255                 mainWebView.reload();
2256                 return true;
2257
2258             case R.id.add_or_edit_domain:
2259                 if (domainSettingsApplied) {  // Edit the current domain settings.
2260                     // Reapply the domain settings on returning to `MainWebViewActivity`.
2261                     reapplyDomainSettingsOnRestart = true;
2262                     currentDomainName = "";
2263
2264                     // Create an intent to launch the domains activity.
2265                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2266
2267                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2268                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2269                     domainsIntent.putExtra("closeOnBack", true);
2270
2271                     // Make it so.
2272                     startActivity(domainsIntent);
2273                 } else {  // Add a new domain.
2274                     // Apply the new domain settings on returning to `MainWebViewActivity`.
2275                     reapplyDomainSettingsOnRestart = true;
2276                     currentDomainName = "";
2277
2278                     // Get the current domain
2279                     Uri currentUri = Uri.parse(formattedUrlString);
2280                     String currentDomain = currentUri.getHost();
2281
2282                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2283                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2284
2285                     // Create the domain and store the database ID.
2286                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2287
2288                     // Create an intent to launch the domains activity.
2289                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2290
2291                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2292                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2293                     domainsIntent.putExtra("closeOnBack", true);
2294
2295                     // Make it so.
2296                     startActivity(domainsIntent);
2297                 }
2298                 return true;
2299
2300             case R.id.toggle_first_party_cookies:
2301                 // Switch the status of firstPartyCookiesEnabled.
2302                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2303
2304                 // Update the menu checkbox.
2305                 menuItem.setChecked(firstPartyCookiesEnabled);
2306
2307                 // Apply the new cookie status.
2308                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2309
2310                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2311                 updatePrivacyIcons(true);
2312
2313                 // Display a `Snackbar`.
2314                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2315                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2316                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
2317                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2318                 } else {  // Privacy mode.
2319                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2320                 }
2321
2322                 // Reload the WebView.
2323                 mainWebView.reload();
2324                 return true;
2325
2326             case R.id.toggle_third_party_cookies:
2327                 if (Build.VERSION.SDK_INT >= 21) {
2328                     // Switch the status of thirdPartyCookiesEnabled.
2329                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2330
2331                     // Update the menu checkbox.
2332                     menuItem.setChecked(thirdPartyCookiesEnabled);
2333
2334                     // Apply the new cookie status.
2335                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2336
2337                     // Display a `Snackbar`.
2338                     if (thirdPartyCookiesEnabled) {
2339                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2340                     } else {
2341                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2342                     }
2343
2344                     // Reload the WebView.
2345                     mainWebView.reload();
2346                 } // Else do nothing because SDK < 21.
2347                 return true;
2348
2349             case R.id.toggle_dom_storage:
2350                 // Switch the status of domStorageEnabled.
2351                 domStorageEnabled = !domStorageEnabled;
2352
2353                 // Update the menu checkbox.
2354                 menuItem.setChecked(domStorageEnabled);
2355
2356                 // Apply the new DOM Storage status.
2357                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2358
2359                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2360                 updatePrivacyIcons(true);
2361
2362                 // Display a `Snackbar`.
2363                 if (domStorageEnabled) {
2364                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2365                 } else {
2366                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2367                 }
2368
2369                 // Reload the WebView.
2370                 mainWebView.reload();
2371                 return true;
2372
2373             // Form data can be removed once the minimum API >= 26.
2374             case R.id.toggle_save_form_data:
2375                 // Switch the status of saveFormDataEnabled.
2376                 saveFormDataEnabled = !saveFormDataEnabled;
2377
2378                 // Update the menu checkbox.
2379                 menuItem.setChecked(saveFormDataEnabled);
2380
2381                 // Apply the new form data status.
2382                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2383
2384                 // Display a `Snackbar`.
2385                 if (saveFormDataEnabled) {
2386                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2387                 } else {
2388                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2389                 }
2390
2391                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2392                 updatePrivacyIcons(true);
2393
2394                 // Reload the WebView.
2395                 mainWebView.reload();
2396                 return true;
2397
2398             case R.id.clear_cookies:
2399                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2400                         .setAction(R.string.undo, v -> {
2401                             // Do nothing because everything will be handled by `onDismissed()` below.
2402                         })
2403                         .addCallback(new Snackbar.Callback() {
2404                             @Override
2405                             public void onDismissed(Snackbar snackbar, int event) {
2406                                 switch (event) {
2407                                     // The user pushed the `Undo` button.
2408                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2409                                         // Do nothing.
2410                                         break;
2411
2412                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2413                                     default:
2414                                         // `cookieManager.removeAllCookie()` varies by SDK.
2415                                         if (Build.VERSION.SDK_INT < 21) {
2416                                             cookieManager.removeAllCookie();
2417                                         } else {
2418                                             // `null` indicates no callback.
2419                                             cookieManager.removeAllCookies(null);
2420                                         }
2421                                 }
2422                             }
2423                         })
2424                         .show();
2425                 return true;
2426
2427             case R.id.clear_dom_storage:
2428                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2429                         .setAction(R.string.undo, v -> {
2430                             // Do nothing because everything will be handled by `onDismissed()` below.
2431                         })
2432                         .addCallback(new Snackbar.Callback() {
2433                             @Override
2434                             public void onDismissed(Snackbar snackbar, int event) {
2435                                 switch (event) {
2436                                     // The user pushed the `Undo` button.
2437                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2438                                         // Do nothing.
2439                                         break;
2440
2441                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2442                                     default:
2443                                         // Delete the DOM Storage.
2444                                         WebStorage webStorage = WebStorage.getInstance();
2445                                         webStorage.deleteAllData();
2446
2447                                         // Manually delete the DOM storage files and directories.
2448                                         try {
2449                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2450                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2451
2452                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2453                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2454                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2455                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2456                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2457                                         } catch (IOException e) {
2458                                             // Do nothing if an error is thrown.
2459                                         }
2460                                 }
2461                             }
2462                         })
2463                         .show();
2464                 return true;
2465
2466             // Form data can be remove once the minimum API >= 26.
2467             case R.id.clear_form_data:
2468                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2469                         .setAction(R.string.undo, v -> {
2470                             // Do nothing because everything will be handled by `onDismissed()` below.
2471                         })
2472                         .addCallback(new Snackbar.Callback() {
2473                             @Override
2474                             public void onDismissed(Snackbar snackbar, int event) {
2475                                 switch (event) {
2476                                     // The user pushed the `Undo` button.
2477                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2478                                         // Do nothing.
2479                                         break;
2480
2481                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2482                                     default:
2483                                         // Delete the form data.
2484                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2485                                         mainWebViewDatabase.clearFormData();
2486                                 }
2487                             }
2488                         })
2489                         .show();
2490                 return true;
2491
2492             case R.id.easylist:
2493                 // Toggle the EasyList status.
2494                 easyListEnabled = !easyListEnabled;
2495
2496                 // Update the menu checkbox.
2497                 menuItem.setChecked(easyListEnabled);
2498
2499                 // Reload the main WebView.
2500                 mainWebView.reload();
2501                 return true;
2502
2503             case R.id.easyprivacy:
2504                 // Toggle the EasyPrivacy status.
2505                 easyPrivacyEnabled = !easyPrivacyEnabled;
2506
2507                 // Update the menu checkbox.
2508                 menuItem.setChecked(easyPrivacyEnabled);
2509
2510                 // Reload the main WebView.
2511                 mainWebView.reload();
2512                 return true;
2513
2514             case R.id.fanboys_annoyance_list:
2515                 // Toggle Fanboy's Annoyance List status.
2516                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2517
2518                 // Update the menu checkbox.
2519                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2520
2521                 // Update the staus of Fanboy's Social Blocking List.
2522                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2523                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2524
2525                 // Reload the main WebView.
2526                 mainWebView.reload();
2527                 return true;
2528
2529             case R.id.fanboys_social_blocking_list:
2530                 // Toggle Fanboy's Social Blocking List status.
2531                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2532
2533                 // Update the menu checkbox.
2534                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2535
2536                 // Reload the main WebView.
2537                 mainWebView.reload();
2538                 return true;
2539
2540             case R.id.ultraprivacy:
2541                 // Toggle the UltraPrivacy status.
2542                 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2543
2544                 // Update the menu checkbox.
2545                 menuItem.setChecked(ultraPrivacyEnabled);
2546
2547                 // Reload the main WebView.
2548                 mainWebView.reload();
2549                 return true;
2550
2551             case R.id.block_all_third_party_requests:
2552                 //Toggle the third-party requests blocker status.
2553                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2554
2555                 // Update the menu checkbox.
2556                 menuItem.setChecked(blockAllThirdPartyRequests);
2557
2558                 // Reload the main WebView.
2559                 mainWebView.reload();
2560                 return true;
2561
2562             case R.id.user_agent_privacy_browser:
2563                 // Update the user agent.
2564                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2565
2566                 // Reload the WebView.
2567                 mainWebView.reload();
2568                 return true;
2569
2570             case R.id.user_agent_webview_default:
2571                 // Update the user agent.
2572                 mainWebView.getSettings().setUserAgentString("");
2573
2574                 // Reload the WebView.
2575                 mainWebView.reload();
2576                 return true;
2577
2578             case R.id.user_agent_firefox_on_android:
2579                 // Update the user agent.
2580                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2581
2582                 // Reload the WebView.
2583                 mainWebView.reload();
2584                 return true;
2585
2586             case R.id.user_agent_chrome_on_android:
2587                 // Update the user agent.
2588                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2589
2590                 // Reload the WebView.
2591                 mainWebView.reload();
2592                 return true;
2593
2594             case R.id.user_agent_safari_on_ios:
2595                 // Update the user agent.
2596                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2597
2598                 // Reload the WebView.
2599                 mainWebView.reload();
2600                 return true;
2601
2602             case R.id.user_agent_firefox_on_linux:
2603                 // Update the user agent.
2604                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2605
2606                 // Reload the WebView.
2607                 mainWebView.reload();
2608                 return true;
2609
2610             case R.id.user_agent_chromium_on_linux:
2611                 // Update the user agent.
2612                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2613
2614                 // Reload the WebView.
2615                 mainWebView.reload();
2616                 return true;
2617
2618             case R.id.user_agent_firefox_on_windows:
2619                 // Update the user agent.
2620                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2621
2622                 // Reload the WebView.
2623                 mainWebView.reload();
2624                 return true;
2625
2626             case R.id.user_agent_chrome_on_windows:
2627                 // Update the user agent.
2628                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2629
2630                 // Reload the WebView.
2631                 mainWebView.reload();
2632                 return true;
2633
2634             case R.id.user_agent_edge_on_windows:
2635                 // Update the user agent.
2636                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2637
2638                 // Reload the WebView.
2639                 mainWebView.reload();
2640                 return true;
2641
2642             case R.id.user_agent_internet_explorer_on_windows:
2643                 // Update the user agent.
2644                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2645
2646                 // Reload the WebView.
2647                 mainWebView.reload();
2648                 return true;
2649
2650             case R.id.user_agent_safari_on_macos:
2651                 // Update the user agent.
2652                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2653
2654                 // Reload the WebView.
2655                 mainWebView.reload();
2656                 return true;
2657
2658             case R.id.user_agent_custom:
2659                 // Update the user agent.
2660                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2661
2662                 // Reload the WebView.
2663                 mainWebView.reload();
2664                 return true;
2665
2666             case R.id.font_size_twenty_five_percent:
2667                 mainWebView.getSettings().setTextZoom(25);
2668                 return true;
2669
2670             case R.id.font_size_fifty_percent:
2671                 mainWebView.getSettings().setTextZoom(50);
2672                 return true;
2673
2674             case R.id.font_size_seventy_five_percent:
2675                 mainWebView.getSettings().setTextZoom(75);
2676                 return true;
2677
2678             case R.id.font_size_one_hundred_percent:
2679                 mainWebView.getSettings().setTextZoom(100);
2680                 return true;
2681
2682             case R.id.font_size_one_hundred_twenty_five_percent:
2683                 mainWebView.getSettings().setTextZoom(125);
2684                 return true;
2685
2686             case R.id.font_size_one_hundred_fifty_percent:
2687                 mainWebView.getSettings().setTextZoom(150);
2688                 return true;
2689
2690             case R.id.font_size_one_hundred_seventy_five_percent:
2691                 mainWebView.getSettings().setTextZoom(175);
2692                 return true;
2693
2694             case R.id.font_size_two_hundred_percent:
2695                 mainWebView.getSettings().setTextZoom(200);
2696                 return true;
2697
2698             case R.id.swipe_to_refresh:
2699                 // Toggle swipe to refresh.
2700                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2701                 return true;
2702
2703             case R.id.display_images:
2704                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2705                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2706                     mainWebView.reload();
2707                 } else {  // Images are not currently loaded automatically.
2708                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2709                 }
2710
2711                 // Set `onTheFlyDisplayImagesSet`.
2712                 onTheFlyDisplayImagesSet = true;
2713                 return true;
2714
2715             case R.id.night_mode:
2716                 // Toggle night mode.
2717                 nightMode = !nightMode;
2718
2719                 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2720                 if (nightMode) {  // Night mode is enabled.  Enable JavaScript.
2721                     // Update the global variable.
2722                     javaScriptEnabled = true;
2723                 } else if (domainSettingsApplied) {  // Night mode is disabled and domain settings are applied.  Set JavaScript according to the domain settings.
2724                     // Get the JavaScript preference that was stored the last time domain settings were loaded.
2725                     javaScriptEnabled = domainSettingsJavaScriptEnabled;
2726                 } else {  // Night mode is disabled and domain settings are not applied.  Set JavaScript according to the global preference.
2727                     // Get a handle for the shared preference.
2728                     SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2729
2730                     // Get the JavaScript preference.
2731                     javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2732                 }
2733
2734                 // Apply the JavaScript setting to the WebView.
2735                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2736
2737                 // Update the privacy icons.
2738                 updatePrivacyIcons(false);
2739
2740                 // Reload the website.
2741                 mainWebView.reload();
2742                 return true;
2743
2744             case R.id.view_source:
2745                 // Launch the View Source activity.
2746                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2747                 startActivity(viewSourceIntent);
2748                 return true;
2749
2750             case R.id.share:
2751                 // Setup the share string.
2752                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2753
2754                 // Create the share intent.
2755                 Intent shareIntent = new Intent();
2756                 shareIntent.setAction(Intent.ACTION_SEND);
2757                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2758                 shareIntent.setType("text/plain");
2759
2760                 // Make it so.
2761                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2762                 return true;
2763
2764             case R.id.find_on_page:
2765                 // Hide the URL app bar.
2766                 supportAppBar.setVisibility(View.GONE);
2767
2768                 // Show the Find on Page `RelativeLayout`.
2769                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2770
2771                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2772                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2773                 findOnPageEditText.postDelayed(() -> {
2774                     // Set the focus on `findOnPageEditText`.
2775                     findOnPageEditText.requestFocus();
2776
2777                     // Display the keyboard.  `0` sets no input flags.
2778                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2779                 }, 200);
2780                 return true;
2781
2782             case R.id.print:
2783                 // Get a `PrintManager` instance.
2784                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2785
2786                 // Convert `mainWebView` to `printDocumentAdapter`.
2787                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2788
2789                 // Remove the lint error below that `printManager` might be `null`.
2790                 assert printManager != null;
2791
2792                 // Print the document.  The print attributes are `null`.
2793                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2794                 return true;
2795
2796             case R.id.add_to_homescreen:
2797                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2798                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2799                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2800
2801                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2802                 return true;
2803
2804             case R.id.refresh:
2805                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2806                     // Reload the WebView.
2807                     mainWebView.reload();
2808                 } else {  // The stop button was pushed.
2809                     // Stop the loading of the WebView.
2810                     mainWebView.stopLoading();
2811                 }
2812                 return true;
2813
2814             case R.id.ad_consent:
2815                 // Display the ad consent dialog.
2816                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2817                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2818                 return true;
2819
2820             default:
2821                 // Don't consume the event.
2822                 return super.onOptionsItemSelected(menuItem);
2823         }
2824     }
2825
2826     // removeAllCookies is deprecated, but it is required for API < 21.
2827     @SuppressWarnings("deprecation")
2828     @Override
2829     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2830         int menuItemId = menuItem.getItemId();
2831
2832         switch (menuItemId) {
2833             case R.id.home:
2834                 loadUrl(homepage);
2835                 break;
2836
2837             case R.id.back:
2838                 if (mainWebView.canGoBack()) {
2839                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2840                     formattedUrlString = "";
2841
2842                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2843                     navigatingHistory = true;
2844
2845                     // Load the previous website in the history.
2846                     mainWebView.goBack();
2847                 }
2848                 break;
2849
2850             case R.id.forward:
2851                 if (mainWebView.canGoForward()) {
2852                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2853                     formattedUrlString = "";
2854
2855                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2856                     navigatingHistory = true;
2857
2858                     // Load the next website in the history.
2859                     mainWebView.goForward();
2860                 }
2861                 break;
2862
2863             case R.id.history:
2864                 // Get the `WebBackForwardList`.
2865                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2866
2867                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2868                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2869                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2870                 break;
2871
2872             case R.id.requests:
2873                 // Launch the requests activity.
2874                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2875                 startActivity(requestsIntent);
2876                 break;
2877
2878             case R.id.downloads:
2879                 // Launch the system Download Manager.
2880                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2881
2882                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2883                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2884
2885                 startActivity(downloadManagerIntent);
2886                 break;
2887
2888             case R.id.domains:
2889                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2890                 reapplyDomainSettingsOnRestart = true;
2891                 currentDomainName = "";
2892
2893                 // Launch the domains activity.
2894                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2895                 startActivity(domainsIntent);
2896                 break;
2897
2898             case R.id.settings:
2899                 // Set the flag to reapply app settings on restart when returning from Settings.
2900                 reapplyAppSettingsOnRestart = true;
2901
2902                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2903                 reapplyDomainSettingsOnRestart = true;
2904                 currentDomainName = "";
2905
2906                 // Launch the settings activity.
2907                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2908                 startActivity(settingsIntent);
2909                 break;
2910