]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
115adcc2ca710f0881c90213658a903dc105efbe
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DialogFragment;
28 import android.app.DownloadManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.support.annotation.NonNull;
56 import android.support.design.widget.CoordinatorLayout;
57 import android.support.design.widget.FloatingActionButton;
58 import android.support.design.widget.NavigationView;
59 import android.support.design.widget.Snackbar;
60 import android.support.v4.app.ActivityCompat;
61 import android.support.v4.content.ContextCompat;
62 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
63 import android.support.v4.content.pm.ShortcutInfoCompat;
64 import android.support.v4.content.pm.ShortcutManagerCompat;
65 import android.support.v4.graphics.drawable.IconCompat;
66 import android.support.v4.view.GravityCompat;
67 import android.support.v4.widget.DrawerLayout;
68 import android.support.v4.widget.SwipeRefreshLayout;
69 import android.support.v7.app.ActionBar;
70 import android.support.v7.app.ActionBarDrawerToggle;
71 import android.support.v7.app.AppCompatActivity;
72 import android.support.v7.app.AppCompatDialogFragment;
73 import android.support.v7.widget.Toolbar;
74 import android.text.Editable;
75 import android.text.Spanned;
76 import android.text.TextWatcher;
77 import android.text.style.ForegroundColorSpan;
78 import android.util.Patterns;
79 import android.view.ContextMenu;
80 import android.view.GestureDetector;
81 import android.view.KeyEvent;
82 import android.view.Menu;
83 import android.view.MenuItem;
84 import android.view.MotionEvent;
85 import android.view.View;
86 import android.view.ViewGroup;
87 import android.view.WindowManager;
88 import android.view.inputmethod.InputMethodManager;
89 import android.webkit.CookieManager;
90 import android.webkit.HttpAuthHandler;
91 import android.webkit.SslErrorHandler;
92 import android.webkit.ValueCallback;
93 import android.webkit.WebBackForwardList;
94 import android.webkit.WebChromeClient;
95 import android.webkit.WebResourceResponse;
96 import android.webkit.WebStorage;
97 import android.webkit.WebView;
98 import android.webkit.WebViewClient;
99 import android.webkit.WebViewDatabase;
100 import android.widget.ArrayAdapter;
101 import android.widget.CursorAdapter;
102 import android.widget.EditText;
103 import android.widget.FrameLayout;
104 import android.widget.ImageView;
105 import android.widget.LinearLayout;
106 import android.widget.ListView;
107 import android.widget.ProgressBar;
108 import android.widget.RadioButton;
109 import android.widget.RelativeLayout;
110 import android.widget.TextView;
111
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
119 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
121 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
122 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
123 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
124 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
125 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
126 import com.stoutner.privacybrowser.helpers.AdHelper;
127 import com.stoutner.privacybrowser.helpers.BlockListHelper;
128 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
130 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
131 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
132 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
133
134 import java.io.ByteArrayInputStream;
135 import java.io.ByteArrayOutputStream;
136 import java.io.File;
137 import java.io.IOException;
138 import java.io.UnsupportedEncodingException;
139 import java.net.MalformedURLException;
140 import java.net.URL;
141 import java.net.URLDecoder;
142 import java.net.URLEncoder;
143 import java.util.ArrayList;
144 import java.util.Date;
145 import java.util.HashMap;
146 import java.util.HashSet;
147 import java.util.List;
148 import java.util.Map;
149 import java.util.Set;
150
151 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
152 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
153         CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
154         DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
155         HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
156         SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
157
158     // `darkTheme` is public static so it can be accessed from everywhere.
159     public static boolean darkTheme;
160
161     // `allowScreenshots` is public static so it can be accessed from everywhere.  It is also used in `onCreate()`.
162     public static boolean allowScreenshots;
163
164     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
165     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
166     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
167     public static Bitmap favoriteIconBitmap;
168
169     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
170     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
171     public static String formattedUrlString;
172
173     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
174     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
175     public static SslCertificate sslCertificate;
176
177     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()` and `onResume()`.
178     public static String orbotStatus;
179
180     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
181     public static String webViewTitle;
182
183     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
184     public static String appliedUserAgentString;
185
186     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
187     public static boolean reloadOnRestart;
188
189     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`.  It is also used in `onRestart()`.
190     public static boolean loadUrlOnRestart;
191
192     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
193     public static boolean restartFromBookmarksActivity;
194
195     // The block list versions are public static so they can be accessed from `AboutTabFragment`.  They are also used in `onCreate()`.
196     public static String easyListVersion;
197     public static String easyPrivacyVersion;
198     public static String fanboysAnnoyanceVersion;
199     public static String fanboysSocialVersion;
200     public static String ultraPrivacyVersion;
201
202     // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`.  They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
203     public static List<String[]> resourceRequests;
204     public static String[] whiteListResultStringArray;
205     int blockedRequests;
206     int easyListBlockedRequests;
207     int easyPrivacyBlockedRequests;
208     int fanboysAnnoyanceListBlockedRequests;
209     int fanboysSocialBlockingListBlockedRequests;
210     int ultraPrivacyBlockedRequests;
211     int thirdPartyBlockedRequests;
212
213     public final static int REQUEST_DISPOSITION = 0;
214     public final static int REQUEST_URL = 1;
215     public final static int REQUEST_BLOCKLIST = 2;
216     public final static int REQUEST_SUBLIST = 3;
217     public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
218     public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
219
220     public final static int REQUEST_DEFAULT = 0;
221     public final static int REQUEST_ALLOWED = 1;
222     public final static int REQUEST_THIRD_PARTY = 2;
223     public final static int REQUEST_BLOCKED = 3;
224
225     public final static int MAIN_WHITELIST = 1;
226     public final static int FINAL_WHITELIST = 2;
227     public final static int DOMAIN_WHITELIST = 3;
228     public final static int DOMAIN_INITIAL_WHITELIST = 4;
229     public final static int DOMAIN_FINAL_WHITELIST = 5;
230     public final static int THIRD_PARTY_WHITELIST = 6;
231     public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
232     public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
233
234     public final static int MAIN_BLACKLIST = 9;
235     public final static int INITIAL_BLACKLIST = 10;
236     public final static int FINAL_BLACKLIST = 11;
237     public final static int DOMAIN_BLACKLIST = 12;
238     public final static int DOMAIN_INITIAL_BLACKLIST = 13;
239     public final static int DOMAIN_FINAL_BLACKLIST = 14;
240     public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
241     public final static int THIRD_PARTY_BLACKLIST = 16;
242     public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
243     public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
244     public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
245     public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
246     public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
247     public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
248
249     // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
250     // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
251     public static boolean blockAllThirdPartyRequests;
252
253     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
254     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
255     public static String currentBookmarksFolder;
256
257     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
258     public static int domainSettingsDatabaseId;
259
260     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
261     public static String pinnedDomainSslIssuedToCNameString;
262     public static String pinnedDomainSslIssuedToONameString;
263     public static String pinnedDomainSslIssuedToUNameString;
264     public static String pinnedDomainSslIssuedByCNameString;
265     public static String pinnedDomainSslIssuedByONameString;
266     public static String pinnedDomainSslIssuedByUNameString;
267     public static Date pinnedDomainSslStartDate;
268     public static Date pinnedDomainSslEndDate;
269
270     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
271     public final static int UNRECOGNIZED_USER_AGENT = -1;
272     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
273     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
274     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
275     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
276     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
277
278
279     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
280     private ActionBar appBar;
281
282     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
283     private boolean navigatingHistory;
284
285     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
286     private Bitmap favoriteIconDefaultBitmap;
287
288     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
289     private DrawerLayout drawerLayout;
290
291     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
292     private CoordinatorLayout rootCoordinatorLayout;
293
294     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
295     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
296     private WebView mainWebView;
297
298     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
299     private FrameLayout fullScreenVideoFrameLayout;
300
301     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
302     private SwipeRefreshLayout swipeRefreshLayout;
303
304     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
305     private RelativeLayout urlAppBarRelativeLayout;
306
307     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
308     private ImageView favoriteIconImageView;
309
310     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
311     private CookieManager cookieManager;
312
313     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
314     private final Map<String, String> customHeaders = new HashMap<>();
315
316     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
317     private boolean javaScriptEnabled;
318
319     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
320     private boolean firstPartyCookiesEnabled;
321
322     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
323     private boolean thirdPartyCookiesEnabled;
324
325     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
326     private boolean domStorageEnabled;
327
328     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.  It can be removed once the minimum API >= 26.
329     private boolean saveFormDataEnabled;
330
331     // `nightMode` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and  `applyDomainSettings()`.
332     private boolean nightMode;
333
334     // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
335     private boolean displayWebpageImagesBoolean;
336
337     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
338     private String homepage;
339
340     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
341     private String searchURL;
342
343     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
344     private Menu mainMenu;
345
346     // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
347     private MenuItem refreshMenuItem;
348
349     // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
350     private MenuItem blocklistsMenuItem;
351     private MenuItem easyListMenuItem;
352     private MenuItem easyPrivacyMenuItem;
353     private MenuItem fanboysAnnoyanceListMenuItem;
354     private MenuItem fanboysSocialBlockingListMenuItem;
355     private MenuItem ultraPrivacyMenuItem;
356     private MenuItem blockAllThirdParyRequestsMenuItem;
357
358     // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
359     private boolean easyListEnabled;
360     private boolean easyPrivacyEnabled;
361     private boolean fanboysAnnoyanceListEnabled;
362     private boolean fanboysSocialBlockingListEnabled;
363     private boolean ultraPrivacyEnabled;
364
365     // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
366     private String webViewDefaultUserAgent;
367
368     // `defaultCustomUserAgentString` is used in `onPrepareOptionsMenu()` and `applyDomainSettings()`.
369     private String defaultCustomUserAgentString;
370
371     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
372     private Runtime privacyBrowserRuntime;
373
374     // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
375     private boolean proxyThroughOrbot;
376
377     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
378     private boolean incognitoModeEnabled;
379
380     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
381     private boolean fullScreenBrowsingModeEnabled;
382
383     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
384     private boolean inFullScreenBrowsingMode;
385
386     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
387     private boolean hideSystemBarsOnFullscreen;
388
389     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
390     private boolean translucentNavigationBarOnFullscreen;
391
392     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
393     private boolean reapplyDomainSettingsOnRestart;
394
395     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
396     private boolean reapplyAppSettingsOnRestart;
397
398     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
399     private boolean displayingFullScreenVideo;
400
401     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
402     private String currentDomainName;
403
404     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
405     private boolean ignorePinnedSslCertificate;
406
407     // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
408     private BroadcastReceiver orbotStatusBroadcastReceiver;
409
410     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
411     private boolean waitingForOrbot;
412
413     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
414     private boolean domainSettingsApplied;
415
416     // `domainSettingsJavaScriptEnabled` is used in `onOptionsItemSelected()` and `applyDomainSettings()`.
417     private Boolean domainSettingsJavaScriptEnabled;
418
419     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
420     private int displayWebpageImagesInt;
421
422     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
423     private boolean onTheFlyDisplayImagesSet;
424
425     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
426     private String waitingForOrbotHTMLString;
427
428     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
429     private String privateDataDirectoryString;
430
431     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
432     private LinearLayout findOnPageLinearLayout;
433
434     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
435     private EditText findOnPageEditText;
436
437     // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
438     private boolean displayAdditionalAppBarIcons;
439
440     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
441     private ActionBarDrawerToggle drawerToggle;
442
443     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
444     private Toolbar supportAppBar;
445
446     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
447     private EditText urlTextBox;
448
449     // The color spans are used in `onCreate()` and `highlightUrlText()`.
450     private ForegroundColorSpan redColorSpan;
451     private ForegroundColorSpan initialGrayColorSpan;
452     private ForegroundColorSpan finalGrayColorSpan;
453
454     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
455     private SslErrorHandler sslErrorHandler;
456
457     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
458     private static HttpAuthHandler httpAuthHandler;
459
460     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
461     private InputMethodManager inputMethodManager;
462
463     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
464     private RelativeLayout mainWebViewRelativeLayout;
465
466     // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
467     private boolean urlIsLoading;
468
469     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
470     private boolean pinnedDomainSslCertificate;
471
472     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
473     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
474
475     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
476     private ListView bookmarksListView;
477
478     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
479     private TextView bookmarksTitleTextView;
480
481     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
482     private Cursor bookmarksCursor;
483
484     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
485     private CursorAdapter bookmarksCursorAdapter;
486
487     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
488     private String oldFolderNameString;
489
490     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
491     private ValueCallback<Uri[]> fileChooserCallback;
492
493     // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
494     private String downloadUrl;
495     private String downloadContentDisposition;
496     private long downloadContentLength;
497
498     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
499     private String downloadImageUrl;
500
501     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
502     private ArrayAdapter<CharSequence> userAgentNamesArray;
503     private String[] userAgentDataArray;
504
505     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
506     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
507     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
508
509     @Override
510     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.  The whole premise of Privacy Browser is built around an understanding of these dangers.
511     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
512     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
513     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
514     @SuppressWarnings("deprecation")
515     protected void onCreate(Bundle savedInstanceState) {
516         // Get a handle for the shared preferences.
517         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
518
519         // Get the theme and screenshot preferences.
520         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
521         allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
522
523         // Disable screenshots if not allowed.
524         if (!allowScreenshots) {
525             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
526         }
527
528         // Set the activity theme.
529         if (darkTheme) {
530             setTheme(R.style.PrivacyBrowserDark);
531         } else {
532             setTheme(R.style.PrivacyBrowserLight);
533         }
534
535         // Run the default commands.
536         super.onCreate(savedInstanceState);
537
538         // Set the content view.
539         setContentView(R.layout.main_drawerlayout);
540
541         // Get a handle for `inputMethodManager`.
542         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
543
544         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
545         supportAppBar = findViewById(R.id.app_bar);
546         setSupportActionBar(supportAppBar);
547         appBar = getSupportActionBar();
548
549         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
550         assert appBar != null;
551
552         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
553         appBar.setCustomView(R.layout.url_app_bar);
554         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
555
556         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
557         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
558         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
559         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
560
561         // Get a handle for `urlTextBox`.
562         urlTextBox = findViewById(R.id.url_edittext);
563
564         // Remove the formatting from `urlTextBar` when the user is editing the text.
565         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
566             if (hasFocus) {  // The user is editing `urlTextBox`.
567                 // Remove the highlighting.
568                 urlTextBox.getText().removeSpan(redColorSpan);
569                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
570                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
571             } else {  // The user has stopped editing `urlTextBox`.
572                 // Reapply the highlighting.
573                 highlightUrlText();
574             }
575         });
576
577         // Set the go button on the keyboard to load the URL in `urlTextBox`.
578         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
579             // If the event is a key-down event on the `enter` button, load the URL.
580             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
581                 // Load the URL into the mainWebView and consume the event.
582                 try {
583                     loadUrlFromTextBox();
584                 } catch (UnsupportedEncodingException e) {
585                     e.printStackTrace();
586                 }
587                 // If the enter key was pressed, consume the event.
588                 return true;
589             } else {
590                 // If any other key was pressed, do not consume the event.
591                 return false;
592             }
593         });
594
595         // Set `waitingForOrbotHTMLString`.
596         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
597
598         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
599         currentDomainName = "";
600         orbotStatus = "unknown";
601         waitingForOrbot = false;
602
603         // Create an Orbot status `BroadcastReceiver`.
604         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
605             @Override
606             public void onReceive(Context context, Intent intent) {
607                 // Store the content of the status message in `orbotStatus`.
608                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
609
610                 // If we are waiting on Orbot, load the website now that Orbot is connected.
611                 if (orbotStatus.equals("ON") && waitingForOrbot) {
612                     // Reset `waitingForOrbot`.
613                     waitingForOrbot = false;
614
615                     // Load `formattedUrlString
616                     loadUrl(formattedUrlString);
617                 }
618             }
619         };
620
621         // Register `orbotStatusBroadcastReceiver` on `this` context.
622         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
623
624         // Get handles for views that need to be accessed.
625         drawerLayout = findViewById(R.id.drawerlayout);
626         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
627         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
628         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
629         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
630         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
631         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
632         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
633         mainWebView = findViewById(R.id.main_webview);
634         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
635         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
636         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
637         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
638         favoriteIconImageView = findViewById(R.id.favorite_icon);
639
640         // Set the bookmarks drawer resources according to the theme.  This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
641         if (darkTheme) {
642             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
643             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
644             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
645             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
646         } else {
647             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
648             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
649             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
650             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
651         }
652
653         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
654         launchBookmarksActivityFab.setOnClickListener(v -> {
655             // Create an intent to launch the bookmarks activity.
656             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
657
658             // Include the current folder with the `Intent`.
659             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
660
661             // Make it so.
662             startActivity(bookmarksIntent);
663         });
664
665         // Set the create new bookmark folder FAB to display an alert dialog.
666         createBookmarkFolderFab.setOnClickListener(v -> {
667             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
668             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
669             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
670         });
671
672         // Set the create new bookmark FAB to display an alert dialog.
673         createBookmarkFab.setOnClickListener(view -> {
674             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
675             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
676             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
677         });
678
679         // Create a double-tap listener to toggle full-screen mode.
680         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
681             // Override `onDoubleTap()`.  All other events are handled using the default settings.
682             @Override
683             public boolean onDoubleTap(MotionEvent event) {
684                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
685                     // Toggle `inFullScreenBrowsingMode`.
686                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
687
688                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
689                         // Hide the `appBar`.
690                         appBar.hide();
691
692                         // Hide the banner ad in the free flavor.
693                         if (BuildConfig.FLAVOR.contentEquals("free")) {
694                             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
695                             AdHelper.hideAd(findViewById(R.id.adview));
696                         }
697
698                         // Modify the system bars.
699                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
700                             // Remove the translucent overlays.
701                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
702
703                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
704                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
705
706                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
707                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
708                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
709                              */
710                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
711
712                             // Set `rootCoordinatorLayout` to fill the whole screen.
713                             rootCoordinatorLayout.setFitsSystemWindows(false);
714                         } else {  // Hide everything except the status and navigation bars.
715                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
716                             rootCoordinatorLayout.setFitsSystemWindows(false);
717
718                             // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
719                             if (translucentNavigationBarOnFullscreen) {
720                                 // Set the navigation bar to be translucent.
721                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
722                             }
723                         }
724                     } else {  // Switch to normal viewing mode.
725                         // Show the `appBar`.
726                         appBar.show();
727
728                         // Show the `BannerAd` in the free flavor.
729                         if (BuildConfig.FLAVOR.contentEquals("free")) {
730                             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
731                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
732                         }
733
734                         // Remove the translucent navigation bar flag if it is set.
735                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
736
737                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
738                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
739
740                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
741                         rootCoordinatorLayout.setSystemUiVisibility(0);
742
743                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
744                         rootCoordinatorLayout.setFitsSystemWindows(true);
745                     }
746
747                     // Consume the double-tap.
748                     return true;
749                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
750                     return false;
751                 }
752             }
753         });
754
755         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
756         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
757             // Call `performClick()` on the view, which is required for accessibility.
758             v.performClick();
759
760             // Send the `event` to `gestureDetector`.
761             return gestureDetector.onTouchEvent(event);
762         });
763
764         // Update `findOnPageCountTextView`.
765         mainWebView.setFindListener(new WebView.FindListener() {
766             // Get a handle for `findOnPageCountTextView`.
767             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
768
769             @Override
770             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
771                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
772                     // Set `findOnPageCountTextView` to `0/0`.
773                     findOnPageCountTextView.setText(R.string.zero_of_zero);
774                 } else if (isDoneCounting) {  // There are matches.
775                     // `activeMatchOrdinal` is zero-based.
776                     int activeMatch = activeMatchOrdinal + 1;
777
778                     // Build the match string.
779                     String matchString = activeMatch + "/" + numberOfMatches;
780
781                     // Set `findOnPageCountTextView`.
782                     findOnPageCountTextView.setText(matchString);
783                 }
784             }
785         });
786
787         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
788         findOnPageEditText.addTextChangedListener(new TextWatcher() {
789             @Override
790             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
791                 // Do nothing.
792             }
793
794             @Override
795             public void onTextChanged(CharSequence s, int start, int before, int count) {
796                 // Do nothing.
797             }
798
799             @Override
800             public void afterTextChanged(Editable s) {
801                 // Search for the text in `mainWebView`.
802                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
803             }
804         });
805
806         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
807         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
808             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
809                 // Hide the soft keyboard.  `0` indicates no additional flags.
810                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
811
812                 // Consume the event.
813                 return true;
814             } else {  // A different key was pressed.
815                 // Do not consume the event.
816                 return false;
817             }
818         });
819
820         // Implement swipe to refresh
821         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
822         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
823         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
824
825         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
826         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
827         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
828
829         // Listen for touches on the navigation menu.
830         final NavigationView navigationView = findViewById(R.id.navigationview);
831         navigationView.setNavigationItemSelectedListener(this);
832
833         // Get handles for `navigationMenu` and the back and forward menu items.  The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
834         final Menu navigationMenu = navigationView.getMenu();
835         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
836         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
837         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
838         final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
839
840         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
841         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
842         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
843
844         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
845         currentBookmarksFolder = "";
846
847         // Load the home folder, which is `""` in the database.
848         loadBookmarksFolder();
849
850         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
851             // Convert the id from long to int to match the format of the bookmarks database.
852             int databaseID = (int) id;
853
854             // Get the bookmark cursor for this ID and move it to the first row.
855             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
856             bookmarkCursor.moveToFirst();
857
858             // Act upon the bookmark according to the type.
859             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
860                 // Store the new folder name in `currentBookmarksFolder`.
861                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
862
863                 // Load the new folder.
864                 loadBookmarksFolder();
865             } else {  // The selected bookmark is not a folder.
866                 // Load the bookmark URL.
867                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
868
869                 // Close the bookmarks drawer.
870                 drawerLayout.closeDrawer(GravityCompat.END);
871             }
872
873             // Close the `Cursor`.
874             bookmarkCursor.close();
875         });
876
877         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
878             // Convert the database ID from `long` to `int`.
879             int databaseId = (int) id;
880
881             // Find out if the selected bookmark is a folder.
882             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
883
884             if (isFolder) {
885                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
886                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
887
888                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
889                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
890                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
891             } else {
892                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
893                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
894                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
895             }
896
897             // Consume the event.
898             return true;
899         });
900
901         // The drawer listener is used to update the navigation menu.
902         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
903             @Override
904             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
905             }
906
907             @Override
908             public void onDrawerOpened(@NonNull View drawerView) {
909             }
910
911             @Override
912             public void onDrawerClosed(@NonNull View drawerView) {
913             }
914
915             @Override
916             public void onDrawerStateChanged(int newState) {
917                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
918                     // Update the back, forward, history, and requests menu items.
919                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
920                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
921                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
922                     navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
923
924                     // Hide the keyboard (if displayed).
925                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
926
927                     // Clear the focus from from the URL text box.
928                     urlTextBox.clearFocus();
929                 }
930             }
931         });
932
933         // drawerToggle creates the hamburger icon at the start of the AppBar.
934         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
935
936         // Get a handle for the progress bar.
937         final ProgressBar progressBar = findViewById(R.id.progress_bar);
938
939         mainWebView.setWebChromeClient(new WebChromeClient() {
940             // Update the progress bar when a page is loading.
941             @Override
942             public void onProgressChanged(WebView view, int progress) {
943                 // Inject the night mode CSS if night mode is enabled.
944                 if (nightMode) {
945                     // `background-color: #212121` sets the background to be dark gray.  `color: #BDBDBD` sets the text color to be light gray.  `box-shadow: none` removes a lower underline on links
946                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
947                     // `border: none` removes all borders, which can also be used to underline text.
948                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
949                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
950                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
951                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
952                                 // Initialize a `Handler` to display `mainWebView`.
953                                 Handler displayWebViewHandler = new Handler();
954
955                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
956                                 Runnable displayWebViewRunnable = () -> {
957                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
958                                     if (progressBar.getVisibility() == View.GONE) {
959                                         mainWebView.setVisibility(View.VISIBLE);
960                                     }
961                                 };
962
963                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
964                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
965                             });
966                 }
967
968                 // Update the progress bar.
969                 progressBar.setProgress(progress);
970
971                 // Set the visibility of the progress bar.
972                 if (progress < 100) {
973                     // Show the progress bar.
974                     progressBar.setVisibility(View.VISIBLE);
975                 } else {
976                     // Hide the progress bar.
977                     progressBar.setVisibility(View.GONE);
978
979                     // Display `mainWebView` if night mode is disabled.
980                     // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not
981                     // currently enabled.
982                     if (!nightMode) {
983                         mainWebView.setVisibility(View.VISIBLE);
984                     }
985
986                     //Stop the swipe to refresh indicator if it is running
987                     swipeRefreshLayout.setRefreshing(false);
988                 }
989             }
990
991             // Set the favorite icon when it changes.
992             @Override
993             public void onReceivedIcon(WebView view, Bitmap icon) {
994                 // Only update the favorite icon if the website has finished loading.
995                 if (progressBar.getVisibility() == View.GONE) {
996                     // Save a copy of the favorite icon.
997                     favoriteIconBitmap = icon;
998
999                     // Place the favorite icon in the appBar.
1000                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1001                 }
1002             }
1003
1004             // Save a copy of the title when it changes.
1005             @Override
1006             public void onReceivedTitle(WebView view, String title) {
1007                 // Save a copy of the title.
1008                 webViewTitle = title;
1009             }
1010
1011             // Enter full screen video.
1012             @Override
1013             public void onShowCustomView(View view, CustomViewCallback callback) {
1014                 // Set the full screen video flag.
1015                 displayingFullScreenVideo = true;
1016
1017                 // Pause the ad if this is the free flavor.
1018                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1019                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1020                     AdHelper.pauseAd(findViewById(R.id.adview));
1021                 }
1022
1023                 // Remove the translucent overlays.
1024                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1025
1026                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1027                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1028
1029                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1030                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1031                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1032                  */
1033                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1034
1035                 // Set `rootCoordinatorLayout` to fill the entire screen.
1036                 rootCoordinatorLayout.setFitsSystemWindows(false);
1037
1038                 // Disable the sliding drawers.
1039                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1040
1041                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1042                 fullScreenVideoFrameLayout.addView(view);
1043                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1044             }
1045
1046             // Exit full screen video.
1047             @Override
1048             public void onHideCustomView() {
1049                 // Unset the full screen video flag.
1050                 displayingFullScreenVideo = false;
1051
1052                 // Hide `fullScreenVideoFrameLayout`.
1053                 fullScreenVideoFrameLayout.removeAllViews();
1054                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1055
1056                 // Enable the sliding drawers.
1057                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1058
1059                 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1060                 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
1061                     if (hideSystemBarsOnFullscreen) {  // Hide everything.
1062                         // Remove the translucent navigation setting if it is currently flagged.
1063                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1064
1065                         // Remove the translucent status bar overlay.
1066                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1067
1068                         // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1069                         drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1070
1071                         /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1072                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1073                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1074                          */
1075                         rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1076                     } else {  // Hide everything except the status and navigation bars.
1077                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1078                         rootCoordinatorLayout.setSystemUiVisibility(0);
1079
1080                         // Add the translucent status flag if it is unset.
1081                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1082
1083                         if (translucentNavigationBarOnFullscreen) {
1084                             // Set the navigation bar to be translucent.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1085                             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1086                         } else {
1087                             // Set the navigation bar to be black.
1088                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1089                         }
1090                     }
1091                 } else {  // Switch to normal viewing mode.
1092                     // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1093                     if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1094                         appBar.show();
1095                     }
1096
1097                     // Show the `BannerAd` in the free flavor.
1098                     if (BuildConfig.FLAVOR.contentEquals("free")) {
1099                         // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1100                         AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1101                     }
1102
1103                     // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1104                     rootCoordinatorLayout.setSystemUiVisibility(0);
1105
1106                     // Remove the translucent navigation bar flag if it is set.
1107                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1108
1109                     // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1110                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1111
1112                     // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1113                     rootCoordinatorLayout.setFitsSystemWindows(true);
1114                 }
1115
1116                 // Show the ad if this is the free flavor.
1117                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1118                     // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1119                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1120                 }
1121             }
1122
1123             // Upload files.
1124             @Override
1125             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1126                 // Show the file chooser if the device is running API >= 21.
1127                 if (Build.VERSION.SDK_INT >= 21) {
1128                     // Store the file path callback.
1129                     fileChooserCallback = filePathCallback;
1130
1131                     // Create an intent to open a chooser based ont the file chooser parameters.
1132                     Intent fileChooserIntent = fileChooserParams.createIntent();
1133
1134                     // Open the file chooser.  Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1135                     startActivityForResult(fileChooserIntent, 0);
1136                 }
1137                 return true;
1138             }
1139         });
1140
1141         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
1142         registerForContextMenu(mainWebView);
1143
1144         // Allow the downloading of files.
1145         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1146             // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1147             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1148                 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1149
1150                 // Store the variables for future use by `onRequestPermissionsResult()`.
1151                 downloadUrl = url;
1152                 downloadContentDisposition = contentDisposition;
1153                 downloadContentLength = contentLength;
1154
1155                 // Show a dialog if the user has previously denied the permission.
1156                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
1157                     // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1158                     DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1159
1160                     // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
1161                     downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1162                 } else {  // Show the permission request directly.
1163                     // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
1164                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1165                 }
1166             } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1167                 // Get a handle for the download file alert dialog.
1168                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1169
1170                 // Show the download file alert dialog.
1171                 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1172             }
1173         });
1174
1175         // Allow pinch to zoom.
1176         mainWebView.getSettings().setBuiltInZoomControls(true);
1177
1178         // Hide zoom controls.
1179         mainWebView.getSettings().setDisplayZoomControls(false);
1180
1181         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
1182         mainWebView.getSettings().setUseWideViewPort(true);
1183
1184         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1185         mainWebView.getSettings().setLoadWithOverviewMode(true);
1186
1187         // Explicitly disable geolocation.
1188         mainWebView.getSettings().setGeolocationEnabled(false);
1189
1190         // Initialize cookieManager.
1191         cookieManager = CookieManager.getInstance();
1192
1193         // Replace the header that `WebView` creates for `X-Requested-With` with a null value.  The default value is the application ID (com.stoutner.privacybrowser.standard).
1194         customHeaders.put("X-Requested-With", "");
1195
1196         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
1197         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1198
1199         // Get the intent that started the app.
1200         final Intent launchingIntent = getIntent();
1201
1202         // Extract the launching intent data as `launchingIntentUriData`.
1203         final Uri launchingIntentUriData = launchingIntent.getData();
1204
1205         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1206         if (launchingIntentUriData != null) {
1207             formattedUrlString = launchingIntentUriData.toString();
1208         }
1209
1210         // Get a handle for the `Runtime`.
1211         privacyBrowserRuntime = Runtime.getRuntime();
1212
1213         // Store the application's private data directory.
1214         privateDataDirectoryString = getApplicationInfo().dataDir;
1215         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1216
1217         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1218         inFullScreenBrowsingMode = false;
1219
1220         // Initialize the privacy settings variables.
1221         javaScriptEnabled = false;
1222         firstPartyCookiesEnabled = false;
1223         thirdPartyCookiesEnabled = false;
1224         domStorageEnabled = false;
1225         saveFormDataEnabled = false;  // Form data can be removed once the minimum API >= 26.
1226         nightMode = false;
1227
1228         // Store the default user agent.
1229         webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1230
1231         // Initialize the WebView title.
1232         webViewTitle = getString(R.string.no_title);
1233
1234         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1235         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1236         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1237         assert favoriteIconBitmapDrawable != null;
1238         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1239
1240         // If the favorite icon is null, load the default.
1241         if (favoriteIconBitmap == null) {
1242             favoriteIconBitmap = favoriteIconDefaultBitmap;
1243         }
1244
1245         // Initialize the user agent array adapter and string array.
1246         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1247         userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1248
1249         // Apply the app settings from the shared preferences.
1250         applyAppSettings();
1251
1252         // Instantiate the block list helper.
1253         BlockListHelper blockListHelper = new BlockListHelper();
1254
1255         // Initialize the list of resource requests.
1256         resourceRequests = new ArrayList<>();
1257
1258         // Parse the block lists.
1259         final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1260         final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1261         final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1262         final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1263         final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1264
1265         // Store the list versions.
1266         easyListVersion = easyList.get(0).get(0)[0];
1267         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1268         fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1269         fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1270         ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1271
1272         // Get a handle for the activity.  This is used to update the requests counter while the navigation menu is open.
1273         Activity activity = this;
1274
1275         mainWebView.setWebViewClient(new WebViewClient() {
1276             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1277             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1278             @SuppressWarnings("deprecation")
1279             @Override
1280             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1281                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
1282                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1283                     formattedUrlString = "";
1284
1285                     // Apply the domain settings for the new URL.  `applyDomainSettings` doesn't do anything if the domain has not changed.
1286                     applyDomainSettings(url, true, false);
1287
1288                     // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1289                     return false;
1290                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1291                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1292                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1293
1294                     // Parse the url and set it as the data for the intent.
1295                     emailIntent.setData(Uri.parse(url));
1296
1297                     // Open the email program in a new task instead of as part of Privacy Browser.
1298                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1299
1300                     // Make it so.
1301                     startActivity(emailIntent);
1302
1303                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1304                     return true;
1305                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1306                     // Open the dialer and load the phone number, but wait for the user to place the call.
1307                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1308
1309                     // Add the phone number to the intent.
1310                     dialIntent.setData(Uri.parse(url));
1311
1312                     // Open the dialer in a new task instead of as part of Privacy Browser.
1313                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1314
1315                     // Make it so.
1316                     startActivity(dialIntent);
1317
1318                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1319                     return true;
1320                 } else {  // Load a system chooser to select an app that can handle the URL.
1321                     // Open an app that can handle the URL.
1322                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1323
1324                     // Add the URL to the intent.
1325                     genericIntent.setData(Uri.parse(url));
1326
1327                     // List all apps that can handle the URL instead of just opening the first one.
1328                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1329
1330                     // Open the app in a new task instead of as part of Privacy Browser.
1331                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1332
1333                     // Start the app or display a snackbar if no app is available to handle the URL.
1334                     try {
1335                         startActivity(genericIntent);
1336                     } catch (ActivityNotFoundException exception) {
1337                         Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
1338                     }
1339
1340                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1341                     return true;
1342                 }
1343             }
1344
1345             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1346             @SuppressWarnings("deprecation")
1347             @Override
1348             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1349                 // Create an empty web resource response to be used if the resource request is blocked.
1350                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1351
1352                 // Reset the whitelist results tracker.
1353                 whiteListResultStringArray = null;
1354
1355                 // Initialize the third party request tracker.
1356                 boolean isThirdPartyRequest = false;
1357
1358                 // Initialize the current domain string.
1359                 String currentDomain = "";
1360
1361                 // Nobody is happy when comparing null strings.
1362                 if (!(formattedUrlString == null) && !(url == null)) {
1363                     // Get the domain strings to URIs.
1364                     Uri currentDomainUri = Uri.parse(formattedUrlString);
1365                     Uri requestDomainUri = Uri.parse(url);
1366
1367                     // Get the domain host names.
1368                     String currentBaseDomain = currentDomainUri.getHost();
1369                     String requestBaseDomain = requestDomainUri.getHost();
1370
1371                     // Update the current domain variable.
1372                     currentDomain = currentBaseDomain;
1373
1374                     // Only compare the current base domain and the request base domain if neither is null.
1375                     if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1376                         // Determine the current base domain.
1377                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1378                             // Remove the first subdomain.
1379                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1380                         }
1381
1382                         // Determine the request base domain.
1383                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1384                             // Remove the first subdomain.
1385                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1386                         }
1387
1388                         // Update the third party request tracker.
1389                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1390                     }
1391                 }
1392
1393                 // Block third-party requests if enabled.
1394                 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1395                     // Increment the blocked requests counters.
1396                     blockedRequests++;
1397                     thirdPartyBlockedRequests++;
1398
1399                     // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1400                     activity.runOnUiThread(() -> {
1401                         navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1402                         blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1403                         blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1404                     });
1405
1406                     // Add the request to the log.
1407                     resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1408
1409                     // Return an empty web resource response.
1410                     return emptyWebResourceResponse;
1411                 }
1412
1413                 // Check UltraPrivacy if it is enabled.
1414                 if (ultraPrivacyEnabled) {
1415                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1416                         // Increment the blocked requests counters.
1417                         blockedRequests++;
1418                         ultraPrivacyBlockedRequests++;
1419
1420                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1421                         activity.runOnUiThread(() -> {
1422                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1423                             blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1424                             ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1425                         });
1426
1427                         // The resource request was blocked.  Return an empty web resource response.
1428                         return emptyWebResourceResponse;
1429                     }
1430
1431                     // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1432                     if (whiteListResultStringArray != null) {
1433                         // Add a whitelist entry to the resource requests array.
1434                         resourceRequests.add(whiteListResultStringArray);
1435
1436                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
1437                         return null;
1438                     }
1439                 }
1440
1441                 // Check EasyList if it is enabled.
1442                 if (easyListEnabled) {
1443                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1444                         // Increment the blocked requests counters.
1445                         blockedRequests++;
1446                         easyListBlockedRequests++;
1447
1448                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1449                         activity.runOnUiThread(() -> {
1450                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1451                             blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1452                             easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1453                         });
1454
1455                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1456                         whiteListResultStringArray = null;
1457
1458                         // The resource request was blocked.  Return an empty web resource response.
1459                         return emptyWebResourceResponse;
1460                     }
1461                 }
1462
1463                 // Check EasyPrivacy if it is enabled.
1464                 if (easyPrivacyEnabled) {
1465                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1466                         // Increment the blocked requests counters.
1467                         blockedRequests++;
1468                         easyPrivacyBlockedRequests++;
1469
1470                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1471                         activity.runOnUiThread(() -> {
1472                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1473                             blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1474                             easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1475                         });
1476
1477                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1478                         whiteListResultStringArray = null;
1479
1480                         // The resource request was blocked.  Return an empty web resource response.
1481                         return emptyWebResourceResponse;
1482                     }
1483                 }
1484
1485                 // Check Fanboy’s Annoyance List if it is enabled.
1486                 if (fanboysAnnoyanceListEnabled) {
1487                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1488                         // Increment the blocked requests counters.
1489                         blockedRequests++;
1490                         fanboysAnnoyanceListBlockedRequests++;
1491
1492                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1493                         activity.runOnUiThread(() -> {
1494                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1495                             blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1496                             fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1497                         });
1498
1499                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1500                         whiteListResultStringArray = null;
1501
1502                         // The resource request was blocked.  Return an empty web resource response.
1503                         return emptyWebResourceResponse;
1504                     }
1505                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1506                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1507                         // Increment the blocked requests counters.
1508                         blockedRequests++;
1509                         fanboysSocialBlockingListBlockedRequests++;
1510
1511                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1512                         activity.runOnUiThread(() -> {
1513                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1514                             blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1515                             fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1516                         });
1517
1518                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1519                         whiteListResultStringArray = null;
1520
1521                         // The resource request was blocked.  Return an empty web resource response.
1522                         return emptyWebResourceResponse;
1523                     }
1524                 }
1525
1526                 // Add the request to the log because it hasn't been processed by any of the previous checks.
1527                 if (whiteListResultStringArray != null ) {  // The request was processed by a whitelist.
1528                     resourceRequests.add(whiteListResultStringArray);
1529                 } else {  // The request didn't match any blocklist entry.  Log it as a defult request.
1530                     resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1531                 }
1532
1533                 // The resource request has not been blocked.  `return null` loads the requested resource.
1534                 return null;
1535             }
1536
1537             // Handle HTTP authentication requests.
1538             @Override
1539             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1540                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1541                 httpAuthHandler = handler;
1542
1543                 // Display the HTTP authentication dialog.
1544                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1545                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1546             }
1547
1548             // Update the URL in urlTextBox when the page starts to load.
1549             @Override
1550             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1551                 // Reset the list of resource requests.
1552                 resourceRequests.clear();
1553
1554                 // Initialize the counters for requests blocked by each blocklist.
1555                 blockedRequests = 0;
1556                 easyListBlockedRequests = 0;
1557                 easyPrivacyBlockedRequests = 0;
1558                 fanboysAnnoyanceListBlockedRequests = 0;
1559                 fanboysSocialBlockingListBlockedRequests = 0;
1560                 ultraPrivacyBlockedRequests = 0;
1561                 thirdPartyBlockedRequests = 0;
1562
1563                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1564                 if (nightMode) {
1565                     mainWebView.setVisibility(View.INVISIBLE);
1566                 }
1567
1568                 // Hide the keyboard.  `0` indicates no additional flags.
1569                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1570
1571                 // Check to see if Privacy Browser is waiting on Orbot.
1572                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1573                     // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
1574                     formattedUrlString = url;
1575
1576                     // Display the formatted URL text.
1577                     urlTextBox.setText(formattedUrlString);
1578
1579                     // Apply text highlighting to `urlTextBox`.
1580                     highlightUrlText();
1581
1582                     // Apply any custom domain settings if the URL was loaded by navigating history.
1583                     if (navigatingHistory) {
1584                         // Reset `navigatingHistory`.
1585                         navigatingHistory = false;
1586
1587                         // Apply the domain settings.
1588                         applyDomainSettings(url, true, false);
1589                     }
1590
1591                     // Set `urlIsLoading` to `true`, so that redirects while loading do not trigger changes in the user agent, which forces another reload of the existing page.
1592                     urlIsLoading = true;
1593
1594                     // Replace Refresh with Stop if the menu item has been created.  (The WebView typically begins loading before the menu items are instantiated.)
1595                     if (refreshMenuItem != null) {
1596                         // Set the title.
1597                         refreshMenuItem.setTitle(R.string.stop);
1598
1599                         // If the icon is displayed in the AppBar, set it according to the theme.
1600                         if (displayAdditionalAppBarIcons) {
1601                             if (darkTheme) {
1602                                 refreshMenuItem.setIcon(R.drawable.close_dark);
1603                             } else {
1604                                 refreshMenuItem.setIcon(R.drawable.close_light);
1605                             }
1606                         }
1607                     }
1608                 }
1609             }
1610
1611             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1612             @Override
1613             public void onPageFinished(WebView view, String url) {
1614                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1615                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1616                     cookieManager.flush();
1617                 }
1618
1619                 // Update the Refresh menu item if it has been created.
1620                 if (refreshMenuItem != null) {
1621                     // Reset the Refresh title.
1622                     refreshMenuItem.setTitle(R.string.refresh);
1623
1624                     // If the icon is displayed in the AppBar, reset it according to the theme.
1625                     if (displayAdditionalAppBarIcons) {
1626                         if (darkTheme) {
1627                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1628                         } else {
1629                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1630                         }
1631                     }
1632                 }
1633
1634                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1635                 urlIsLoading = false;
1636
1637                 // Clear the cache and history if Incognito Mode is enabled.
1638                 if (incognitoModeEnabled) {
1639                     // Clear the cache.  `true` includes disk files.
1640                     mainWebView.clearCache(true);
1641
1642                     // Clear the back/forward history.
1643                     mainWebView.clearHistory();
1644
1645                     // Manually delete cache folders.
1646                     try {
1647                         // Delete the main cache directory.
1648                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1649
1650                         // Delete the secondary `Service Worker` cache directory.
1651                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1652                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1653                     } catch (IOException e) {
1654                         // Do nothing if an error is thrown.
1655                     }
1656                 }
1657
1658                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1659                 if (!waitingForOrbot) {
1660                     // Check to see if `WebView` has set `url` to be `about:blank`.
1661                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1662                         // Set `formattedUrlString` to `""`.
1663                         formattedUrlString = "";
1664
1665                         urlTextBox.setText(formattedUrlString);
1666
1667                         // Request focus for `urlTextBox`.
1668                         urlTextBox.requestFocus();
1669
1670                         // Display the keyboard.
1671                         inputMethodManager.showSoftInput(urlTextBox, 0);
1672
1673                         // Apply the domain settings.  This clears any settings from the previous domain.
1674                         applyDomainSettings(formattedUrlString, true, false);
1675                     } else {  // `WebView` has loaded a webpage.
1676                         // Set `formattedUrlString`.
1677                         formattedUrlString = url;
1678
1679                         // Only update `urlTextBox` if the user is not typing in it.
1680                         if (!urlTextBox.hasFocus()) {
1681                             // Display the formatted URL text.
1682                             urlTextBox.setText(formattedUrlString);
1683
1684                             // Apply text highlighting to `urlTextBox`.
1685                             highlightUrlText();
1686                         }
1687                     }
1688
1689                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1690                     sslCertificate = mainWebView.getCertificate();
1691
1692                     // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
1693                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1694                         // Initialize the current SSL certificate variables.
1695                         String currentWebsiteIssuedToCName = "";
1696                         String currentWebsiteIssuedToOName = "";
1697                         String currentWebsiteIssuedToUName = "";
1698                         String currentWebsiteIssuedByCName = "";
1699                         String currentWebsiteIssuedByOName = "";
1700                         String currentWebsiteIssuedByUName = "";
1701                         Date currentWebsiteSslStartDate = null;
1702                         Date currentWebsiteSslEndDate = null;
1703
1704
1705                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1706                         if (sslCertificate != null) {
1707                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1708                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1709                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1710                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1711                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1712                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1713                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1714                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1715                         }
1716
1717                         // Initialize `String` variables to store the SSL certificate dates.  `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
1718                         String currentWebsiteSslStartDateString = "";
1719                         String currentWebsiteSslEndDateString = "";
1720                         String pinnedDomainSslStartDateString = "";
1721                         String pinnedDomainSslEndDateString = "";
1722
1723                         // Convert the `Dates` to `Strings` if they are not `null`.
1724                         if (currentWebsiteSslStartDate != null) {
1725                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1726                         }
1727
1728                         if (currentWebsiteSslEndDate != null) {
1729                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1730                         }
1731
1732                         if (pinnedDomainSslStartDate != null) {
1733                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1734                         }
1735
1736                         if (pinnedDomainSslEndDate != null) {
1737                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1738                         }
1739
1740                         // Check to see if the pinned SSL certificate matches the current website certificate.
1741                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1742                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1743                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1744                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1745                             // The pinned SSL certificate doesn't match the current domain certificate.
1746                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1747                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1748                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1749                         }
1750                     }
1751                 }
1752             }
1753
1754             // Handle SSL Certificate errors.
1755             @Override
1756             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1757                 // Get the current website SSL certificate.
1758                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1759
1760                 // Extract the individual pieces of information from the current website SSL certificate.
1761                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1762                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1763                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1764                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1765                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1766                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1767                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1768                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1769
1770                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1771                 if (pinnedDomainSslCertificate &&
1772                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1773                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1774                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1775                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1776                     // An SSL certificate is pinned and matches the current domain certificate.
1777                     // Proceed to the website without displaying an error.
1778                     handler.proceed();
1779                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1780                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1781                     sslErrorHandler = handler;
1782
1783                     // Display the SSL error `AlertDialog`.
1784                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1785                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1786                 }
1787             }
1788         });
1789
1790         // Load the website if not waiting for Orbot to connect.
1791         if (!waitingForOrbot) {
1792             loadUrl(formattedUrlString);
1793         }
1794     }
1795
1796     @Override
1797     protected void onNewIntent(Intent intent) {
1798         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1799         setIntent(intent);
1800
1801         // Check to see if the intent contains a new URL.
1802         if (intent.getData() != null) {
1803             // Get the intent data.
1804             final Uri intentUriData = intent.getData();
1805
1806             // Load the website.
1807             loadUrl(intentUriData.toString());
1808
1809             // Close the navigation drawer if it is open.
1810             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1811                 drawerLayout.closeDrawer(GravityCompat.START);
1812             }
1813
1814             // Close the bookmarks drawer if it is open.
1815             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1816                 drawerLayout.closeDrawer(GravityCompat.END);
1817             }
1818
1819             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1820             mainWebView.requestFocus();
1821         }
1822     }
1823
1824     @Override
1825     public void onRestart() {
1826         // Run the default commands.
1827         super.onRestart();
1828
1829         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1830         if (proxyThroughOrbot) {
1831             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1832             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1833
1834             // Send the intent to the Orbot package.
1835             orbotIntent.setPackage("org.torproject.android");
1836
1837             // Make it so.
1838             sendBroadcast(orbotIntent);
1839         }
1840
1841         // Apply the app settings if returning from the Settings activity..
1842         if (reapplyAppSettingsOnRestart) {
1843             // Apply the app settings.
1844             applyAppSettings();
1845
1846             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1847             if (reloadOnRestart) {
1848                 // Reload `mainWebView`.
1849                 mainWebView.reload();
1850
1851                 // Reset `reloadOnRestartBoolean`.
1852                 reloadOnRestart = false;
1853             }
1854
1855             // Reset the return from settings flag.
1856             reapplyAppSettingsOnRestart = false;
1857         }
1858
1859         // Apply the domain settings if returning from the Domains activity.
1860         if (reapplyDomainSettingsOnRestart) {
1861             // Reapply the domain settings.
1862             applyDomainSettings(formattedUrlString, false, true);
1863
1864             // Reset `reapplyDomainSettingsOnRestart`.
1865             reapplyDomainSettingsOnRestart = false;
1866         }
1867
1868         // Load the URL on restart to apply changes to night mode.
1869         if (loadUrlOnRestart) {
1870             // Load the current `formattedUrlString`.
1871             loadUrl(formattedUrlString);
1872
1873             // Reset `loadUrlOnRestart.
1874             loadUrlOnRestart = false;
1875         }
1876
1877         // Update the bookmarks drawer if returning from the Bookmarks activity.
1878         if (restartFromBookmarksActivity) {
1879             // Close the bookmarks drawer.
1880             drawerLayout.closeDrawer(GravityCompat.END);
1881
1882             // Reload the bookmarks drawer.
1883             loadBookmarksFolder();
1884
1885             // Reset `restartFromBookmarksActivity`.
1886             restartFromBookmarksActivity = false;
1887         }
1888
1889         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1890         updatePrivacyIcons(true);
1891     }
1892
1893     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1894     @Override
1895     public void onResume() {
1896         // Run the default commands.
1897         super.onResume();
1898
1899         // Resume JavaScript (if enabled).
1900         mainWebView.resumeTimers();
1901
1902         // Resume `mainWebView`.
1903         mainWebView.onResume();
1904
1905         // Resume the adView for the free flavor.
1906         if (BuildConfig.FLAVOR.contentEquals("free")) {
1907             // Resume the ad.
1908             AdHelper.resumeAd(findViewById(R.id.adview));
1909         }
1910
1911         // Display a message to the user if waiting for Orbot.
1912         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1913             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1914             mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1915         }
1916
1917         if (displayingFullScreenVideo) {
1918             // Remove the translucent overlays.
1919             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1920
1921             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1922             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1923
1924             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1925              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1926              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1927              */
1928             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1929         }
1930     }
1931
1932     @Override
1933     public void onPause() {
1934         // Run the default commands.
1935         super.onPause();
1936
1937         // Pause `mainWebView`.
1938         mainWebView.onPause();
1939
1940         // Stop all JavaScript.
1941         mainWebView.pauseTimers();
1942
1943         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1944         if (BuildConfig.FLAVOR.contentEquals("free")) {
1945             // Pause the ad.
1946             AdHelper.pauseAd(findViewById(R.id.adview));
1947         }
1948     }
1949
1950     @Override
1951     public void onDestroy() {
1952         // Unregister the Orbot status broadcast receiver.
1953         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1954
1955         // Run the default commands.
1956         super.onDestroy();
1957     }
1958
1959     @Override
1960     public boolean onCreateOptionsMenu(Menu menu) {
1961         // Inflate the menu; this adds items to the action bar if it is present.
1962         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1963
1964         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1965         mainMenu = menu;
1966
1967         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1968         updatePrivacyIcons(false);
1969
1970         // Get handles for the menu items.
1971         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1972         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1973         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1974         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1975         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1976         refreshMenuItem = menu.findItem(R.id.refresh);
1977         blocklistsMenuItem = menu.findItem(R.id.blocklists);
1978         easyListMenuItem = menu.findItem(R.id.easylist);
1979         easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1980         fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1981         fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1982         ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1983         blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1984         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1985
1986         // Only display third-party cookies if API >= 21
1987         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1988
1989         // Only display the form data menu items if the API < 26.
1990         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1991         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1992
1993         // Only show Ad Consent if this is the free flavor.
1994         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1995
1996         // Get the shared preference values.
1997         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1998
1999         // Get the status of the additional AppBar icons.
2000         displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
2001
2002         // Set the status of the additional app bar icons.  Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
2003         if (displayAdditionalAppBarIcons) {
2004             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2005             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2006             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2007         } else { //Do not display the additional icons.
2008             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2009             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2010             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2011         }
2012
2013         // Replace Refresh with Stop if a URL is already loading.
2014         if (urlIsLoading) {
2015             // Set the title.
2016             refreshMenuItem.setTitle(R.string.stop);
2017
2018             // If the icon is displayed in the AppBar, set it according to the theme.
2019             if (displayAdditionalAppBarIcons) {
2020                 if (darkTheme) {
2021                     refreshMenuItem.setIcon(R.drawable.close_dark);
2022                 } else {
2023                     refreshMenuItem.setIcon(R.drawable.close_light);
2024                 }
2025             }
2026         }
2027
2028         return true;
2029     }
2030
2031     @Override
2032     public boolean onPrepareOptionsMenu(Menu menu) {
2033         // Get handles for the menu items.
2034         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2035         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2036         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2037         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2038         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
2039         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2040         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2041         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2042         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
2043         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2044         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2045         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2046         MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
2047
2048         // Set the text for the domain menu item.
2049         if (domainSettingsApplied) {
2050             addOrEditDomain.setTitle(R.string.edit_domain_settings);
2051         } else {
2052             addOrEditDomain.setTitle(R.string.add_domain_settings);
2053         }
2054
2055         // Set the status of the menu item checkboxes.
2056         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2057         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2058         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2059         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
2060         easyListMenuItem.setChecked(easyListEnabled);
2061         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2062         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2063         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2064         ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2065         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2066         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2067         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2068         nightModeMenuItem.setChecked(nightMode);
2069
2070         // Enable third-party cookies if first-party cookies are enabled.
2071         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2072
2073         // Enable DOM Storage if JavaScript is enabled.
2074         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2075
2076         // Enable Clear Cookies if there are any.
2077         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2078
2079         // Get a count of the number of files in the Local Storage directory.
2080         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2081         int localStorageDirectoryNumberOfFiles = 0;
2082         if (localStorageDirectory.exists()) {
2083             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2084         }
2085
2086         // Get a count of the number of files in the IndexedDB directory.
2087         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2088         int indexedDBDirectoryNumberOfFiles = 0;
2089         if (indexedDBDirectory.exists()) {
2090             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2091         }
2092
2093         // Enable Clear DOM Storage if there is any.
2094         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2095
2096         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
2097         if (Build.VERSION.SDK_INT < 26) {
2098             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2099             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2100         } else {
2101             // Disable clear form data because it is not supported on current version of Android.
2102             clearFormDataMenuItem.setEnabled(false);
2103         }
2104
2105         // Enable Clear Data if any of the submenu items are enabled.
2106         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2107
2108         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2109         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2110
2111         // Initialize the display names for the blocklists with the number of blocked requests.
2112         blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2113         easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2114         easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2115         fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2116         fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2117         ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2118         blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2119
2120         // Get the current user agent.
2121         String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2122
2123         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
2124         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
2125             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2126         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
2127             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2128         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
2129             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2130         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
2131             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2132         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
2133             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2134         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
2135             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2136         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
2137             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2138         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
2139             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2140         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
2141             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2142         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
2143             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2144         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
2145             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2146         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
2147             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2148         } else {  // Custom user agent.
2149             menu.findItem(R.id.user_agent_custom).setChecked(true);
2150         }
2151
2152         // Initialize font size variables.
2153         int fontSize = mainWebView.getSettings().getTextZoom();
2154         String fontSizeTitle;
2155         MenuItem selectedFontSizeMenuItem;
2156
2157         // Prepare the font size title and current size menu item.
2158         switch (fontSize) {
2159             case 25:
2160                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2161                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2162                 break;
2163
2164             case 50:
2165                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2166                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2167                 break;
2168
2169             case 75:
2170                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2171                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2172                 break;
2173
2174             case 100:
2175                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2176                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2177                 break;
2178
2179             case 125:
2180                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2181                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2182                 break;
2183
2184             case 150:
2185                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2186                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2187                 break;
2188
2189             case 175:
2190                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2191                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2192                 break;
2193
2194             case 200:
2195                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2196                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2197                 break;
2198
2199             default:
2200                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2201                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2202                 break;
2203         }
2204
2205         // Set the font size title and select the current size menu item.
2206         fontSizeMenuItem.setTitle(fontSizeTitle);
2207         selectedFontSizeMenuItem.setChecked(true);
2208
2209         // Run all the other default commands.
2210         super.onPrepareOptionsMenu(menu);
2211
2212         // Display the menu.
2213         return true;
2214     }
2215
2216     @Override
2217     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2218     @SuppressLint("SetJavaScriptEnabled")
2219     // removeAllCookies is deprecated, but it is required for API < 21.
2220     @SuppressWarnings("deprecation")
2221     public boolean onOptionsItemSelected(MenuItem menuItem) {
2222         // Get the selected menu item ID.
2223         int menuItemId = menuItem.getItemId();
2224
2225         // Set the commands that relate to the menu entries.
2226         switch (menuItemId) {
2227             case R.id.toggle_javascript:
2228                 // Switch the status of javaScriptEnabled.
2229                 javaScriptEnabled = !javaScriptEnabled;
2230
2231                 // Apply the new JavaScript status.
2232                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2233
2234                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2235                 updatePrivacyIcons(true);
2236
2237                 // Display a `Snackbar`.
2238                 if (javaScriptEnabled) {  // JavaScrip is enabled.
2239                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2240                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
2241                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2242                 } else {  // Privacy mode.
2243                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2244                 }
2245
2246                 // Reload the WebView.
2247                 mainWebView.reload();
2248                 return true;
2249
2250             case R.id.add_or_edit_domain:
2251                 if (domainSettingsApplied) {  // Edit the current domain settings.
2252                     // Reapply the domain settings on returning to `MainWebViewActivity`.
2253                     reapplyDomainSettingsOnRestart = true;
2254                     currentDomainName = "";
2255
2256                     // Create an intent to launch the domains activity.
2257                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2258
2259                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2260                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2261                     domainsIntent.putExtra("closeOnBack", true);
2262
2263                     // Make it so.
2264                     startActivity(domainsIntent);
2265                 } else {  // Add a new domain.
2266                     // Apply the new domain settings on returning to `MainWebViewActivity`.
2267                     reapplyDomainSettingsOnRestart = true;
2268                     currentDomainName = "";
2269
2270                     // Get the current domain
2271                     Uri currentUri = Uri.parse(formattedUrlString);
2272                     String currentDomain = currentUri.getHost();
2273
2274                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2275                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2276
2277                     // Create the domain and store the database ID.
2278                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2279
2280                     // Create an intent to launch the domains activity.
2281                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2282
2283                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2284                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2285                     domainsIntent.putExtra("closeOnBack", true);
2286
2287                     // Make it so.
2288                     startActivity(domainsIntent);
2289                 }
2290                 return true;
2291
2292             case R.id.toggle_first_party_cookies:
2293                 // Switch the status of firstPartyCookiesEnabled.
2294                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2295
2296                 // Update the menu checkbox.
2297                 menuItem.setChecked(firstPartyCookiesEnabled);
2298
2299                 // Apply the new cookie status.
2300                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2301
2302                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2303                 updatePrivacyIcons(true);
2304
2305                 // Display a `Snackbar`.
2306                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2307                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2308                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
2309                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2310                 } else {  // Privacy mode.
2311                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2312                 }
2313
2314                 // Reload the WebView.
2315                 mainWebView.reload();
2316                 return true;
2317
2318             case R.id.toggle_third_party_cookies:
2319                 if (Build.VERSION.SDK_INT >= 21) {
2320                     // Switch the status of thirdPartyCookiesEnabled.
2321                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2322
2323                     // Update the menu checkbox.
2324                     menuItem.setChecked(thirdPartyCookiesEnabled);
2325
2326                     // Apply the new cookie status.
2327                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2328
2329                     // Display a `Snackbar`.
2330                     if (thirdPartyCookiesEnabled) {
2331                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2332                     } else {
2333                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2334                     }
2335
2336                     // Reload the WebView.
2337                     mainWebView.reload();
2338                 } // Else do nothing because SDK < 21.
2339                 return true;
2340
2341             case R.id.toggle_dom_storage:
2342                 // Switch the status of domStorageEnabled.
2343                 domStorageEnabled = !domStorageEnabled;
2344
2345                 // Update the menu checkbox.
2346                 menuItem.setChecked(domStorageEnabled);
2347
2348                 // Apply the new DOM Storage status.
2349                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2350
2351                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2352                 updatePrivacyIcons(true);
2353
2354                 // Display a `Snackbar`.
2355                 if (domStorageEnabled) {
2356                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2357                 } else {
2358                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2359                 }
2360
2361                 // Reload the WebView.
2362                 mainWebView.reload();
2363                 return true;
2364
2365             // Form data can be removed once the minimum API >= 26.
2366             case R.id.toggle_save_form_data:
2367                 // Switch the status of saveFormDataEnabled.
2368                 saveFormDataEnabled = !saveFormDataEnabled;
2369
2370                 // Update the menu checkbox.
2371                 menuItem.setChecked(saveFormDataEnabled);
2372
2373                 // Apply the new form data status.
2374                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2375
2376                 // Display a `Snackbar`.
2377                 if (saveFormDataEnabled) {
2378                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2379                 } else {
2380                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2381                 }
2382
2383                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2384                 updatePrivacyIcons(true);
2385
2386                 // Reload the WebView.
2387                 mainWebView.reload();
2388                 return true;
2389
2390             case R.id.clear_cookies:
2391                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2392                         .setAction(R.string.undo, v -> {
2393                             // Do nothing because everything will be handled by `onDismissed()` below.
2394                         })
2395                         .addCallback(new Snackbar.Callback() {
2396                             @Override
2397                             public void onDismissed(Snackbar snackbar, int event) {
2398                                 switch (event) {
2399                                     // The user pushed the `Undo` button.
2400                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2401                                         // Do nothing.
2402                                         break;
2403
2404                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2405                                     default:
2406                                         // `cookieManager.removeAllCookie()` varies by SDK.
2407                                         if (Build.VERSION.SDK_INT < 21) {
2408                                             cookieManager.removeAllCookie();
2409                                         } else {
2410                                             // `null` indicates no callback.
2411                                             cookieManager.removeAllCookies(null);
2412                                         }
2413                                 }
2414                             }
2415                         })
2416                         .show();
2417                 return true;
2418
2419             case R.id.clear_dom_storage:
2420                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2421                         .setAction(R.string.undo, v -> {
2422                             // Do nothing because everything will be handled by `onDismissed()` below.
2423                         })
2424                         .addCallback(new Snackbar.Callback() {
2425                             @Override
2426                             public void onDismissed(Snackbar snackbar, int event) {
2427                                 switch (event) {
2428                                     // The user pushed the `Undo` button.
2429                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2430                                         // Do nothing.
2431                                         break;
2432
2433                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2434                                     default:
2435                                         // Delete the DOM Storage.
2436                                         WebStorage webStorage = WebStorage.getInstance();
2437                                         webStorage.deleteAllData();
2438
2439                                         // Manually delete the DOM storage files and directories.
2440                                         try {
2441                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2442                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2443
2444                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2445                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2446                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2447                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2448                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2449                                         } catch (IOException e) {
2450                                             // Do nothing if an error is thrown.
2451                                         }
2452                                 }
2453                             }
2454                         })
2455                         .show();
2456                 return true;
2457
2458             // Form data can be remove once the minimum API >= 26.
2459             case R.id.clear_form_data:
2460                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2461                         .setAction(R.string.undo, v -> {
2462                             // Do nothing because everything will be handled by `onDismissed()` below.
2463                         })
2464                         .addCallback(new Snackbar.Callback() {
2465                             @Override
2466                             public void onDismissed(Snackbar snackbar, int event) {
2467                                 switch (event) {
2468                                     // The user pushed the `Undo` button.
2469                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2470                                         // Do nothing.
2471                                         break;
2472
2473                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2474                                     default:
2475                                         // Delete the form data.
2476                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2477                                         mainWebViewDatabase.clearFormData();
2478                                 }
2479                             }
2480                         })
2481                         .show();
2482                 return true;
2483
2484             case R.id.easylist:
2485                 // Toggle the EasyList status.
2486                 easyListEnabled = !easyListEnabled;
2487
2488                 // Update the menu checkbox.
2489                 menuItem.setChecked(easyListEnabled);
2490
2491                 // Reload the main WebView.
2492                 mainWebView.reload();
2493                 return true;
2494
2495             case R.id.easyprivacy:
2496                 // Toggle the EasyPrivacy status.
2497                 easyPrivacyEnabled = !easyPrivacyEnabled;
2498
2499                 // Update the menu checkbox.
2500                 menuItem.setChecked(easyPrivacyEnabled);
2501
2502                 // Reload the main WebView.
2503                 mainWebView.reload();
2504                 return true;
2505
2506             case R.id.fanboys_annoyance_list:
2507                 // Toggle Fanboy's Annoyance List status.
2508                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2509
2510                 // Update the menu checkbox.
2511                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2512
2513                 // Update the staus of Fanboy's Social Blocking List.
2514                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2515                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2516
2517                 // Reload the main WebView.
2518                 mainWebView.reload();
2519                 return true;
2520
2521             case R.id.fanboys_social_blocking_list:
2522                 // Toggle Fanboy's Social Blocking List status.
2523                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2524
2525                 // Update the menu checkbox.
2526                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2527
2528                 // Reload the main WebView.
2529                 mainWebView.reload();
2530                 return true;
2531
2532             case R.id.ultraprivacy:
2533                 // Toggle the UltraPrivacy status.
2534                 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2535
2536                 // Update the menu checkbox.
2537                 menuItem.setChecked(ultraPrivacyEnabled);
2538
2539                 // Reload the main WebView.
2540                 mainWebView.reload();
2541                 return true;
2542
2543             case R.id.block_all_third_party_requests:
2544                 //Toggle the third-party requests blocker status.
2545                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2546
2547                 // Update the menu checkbox.
2548                 menuItem.setChecked(blockAllThirdPartyRequests);
2549
2550                 // Reload the main WebView.
2551                 mainWebView.reload();
2552                 return true;
2553
2554             case R.id.user_agent_privacy_browser:
2555                 // Update the user agent.
2556                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2557
2558                 // Reload the WebView.
2559                 mainWebView.reload();
2560                 return true;
2561
2562             case R.id.user_agent_webview_default:
2563                 // Update the user agent.
2564                 mainWebView.getSettings().setUserAgentString("");
2565
2566                 // Reload the WebView.
2567                 mainWebView.reload();
2568                 return true;
2569
2570             case R.id.user_agent_firefox_on_android:
2571                 // Update the user agent.
2572                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2573
2574                 // Reload the WebView.
2575                 mainWebView.reload();
2576                 return true;
2577
2578             case R.id.user_agent_chrome_on_android:
2579                 // Update the user agent.
2580                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2581
2582                 // Reload the WebView.
2583                 mainWebView.reload();
2584                 return true;
2585
2586             case R.id.user_agent_safari_on_ios:
2587                 // Update the user agent.
2588                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2589
2590                 // Reload the WebView.
2591                 mainWebView.reload();
2592                 return true;
2593
2594             case R.id.user_agent_firefox_on_linux:
2595                 // Update the user agent.
2596                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2597
2598                 // Reload the WebView.
2599                 mainWebView.reload();
2600                 return true;
2601
2602             case R.id.user_agent_chromium_on_linux:
2603                 // Update the user agent.
2604                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2605
2606                 // Reload the WebView.
2607                 mainWebView.reload();
2608                 return true;
2609
2610             case R.id.user_agent_firefox_on_windows:
2611                 // Update the user agent.
2612                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2613
2614                 // Reload the WebView.
2615                 mainWebView.reload();
2616                 return true;
2617
2618             case R.id.user_agent_chrome_on_windows:
2619                 // Update the user agent.
2620                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2621
2622                 // Reload the WebView.
2623                 mainWebView.reload();
2624                 return true;
2625
2626             case R.id.user_agent_edge_on_windows:
2627                 // Update the user agent.
2628                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2629
2630                 // Reload the WebView.
2631                 mainWebView.reload();
2632                 return true;
2633
2634             case R.id.user_agent_internet_explorer_on_windows:
2635                 // Update the user agent.
2636                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2637
2638                 // Reload the WebView.
2639                 mainWebView.reload();
2640                 return true;
2641
2642             case R.id.user_agent_safari_on_macos:
2643                 // Update the user agent.
2644                 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2645
2646                 // Reload the WebView.
2647                 mainWebView.reload();
2648                 return true;
2649
2650             case R.id.user_agent_custom:
2651                 // Update the user agent.
2652                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2653
2654                 // Reload the WebView.
2655                 mainWebView.reload();
2656                 return true;
2657
2658             case R.id.font_size_twenty_five_percent:
2659                 mainWebView.getSettings().setTextZoom(25);
2660                 return true;
2661
2662             case R.id.font_size_fifty_percent:
2663                 mainWebView.getSettings().setTextZoom(50);
2664                 return true;
2665
2666             case R.id.font_size_seventy_five_percent:
2667                 mainWebView.getSettings().setTextZoom(75);
2668                 return true;
2669
2670             case R.id.font_size_one_hundred_percent:
2671                 mainWebView.getSettings().setTextZoom(100);
2672                 return true;
2673
2674             case R.id.font_size_one_hundred_twenty_five_percent:
2675                 mainWebView.getSettings().setTextZoom(125);
2676                 return true;
2677
2678             case R.id.font_size_one_hundred_fifty_percent:
2679                 mainWebView.getSettings().setTextZoom(150);
2680                 return true;
2681
2682             case R.id.font_size_one_hundred_seventy_five_percent:
2683                 mainWebView.getSettings().setTextZoom(175);
2684                 return true;
2685
2686             case R.id.font_size_two_hundred_percent:
2687                 mainWebView.getSettings().setTextZoom(200);
2688                 return true;
2689
2690             case R.id.swipe_to_refresh:
2691                 // Toggle swipe to refresh.
2692                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2693                 return true;
2694
2695             case R.id.display_images:
2696                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2697                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2698                     mainWebView.reload();
2699                 } else {  // Images are not currently loaded automatically.
2700                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2701                 }
2702
2703                 // Set `onTheFlyDisplayImagesSet`.
2704                 onTheFlyDisplayImagesSet = true;
2705                 return true;
2706
2707             case R.id.night_mode:
2708                 // Toggle night mode.
2709                 nightMode = !nightMode;
2710
2711                 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2712                 if (nightMode) {  // Night mode is enabled.  Enable JavaScript.
2713                     // Update the global variable.
2714                     javaScriptEnabled = true;
2715                 } else if (domainSettingsApplied) {  // Night mode is disabled and domain settings are applied.  Set JavaScript according to the domain settings.
2716                     // Get the JavaScript preference that was stored the last time domain settings were loaded.
2717                     javaScriptEnabled = domainSettingsJavaScriptEnabled;
2718                 } else {  // Night mode is disabled and domain settings are not applied.  Set JavaScript according to the global preference.
2719                     // Get a handle for the shared preference.
2720                     SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2721
2722                     // Get the JavaScript preference.
2723                     javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2724                 }
2725
2726                 // Apply the JavaScript setting to the WebView.
2727                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2728
2729                 // Update the privacy icons.
2730                 updatePrivacyIcons(false);
2731
2732                 // Reload the website.
2733                 mainWebView.reload();
2734                 return true;
2735
2736             case R.id.view_source:
2737                 // Launch the View Source activity.
2738                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2739                 startActivity(viewSourceIntent);
2740                 return true;
2741
2742             case R.id.share:
2743                 // Setup the share string.
2744                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2745
2746                 // Create the share intent.
2747                 Intent shareIntent = new Intent();
2748                 shareIntent.setAction(Intent.ACTION_SEND);
2749                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2750                 shareIntent.setType("text/plain");
2751
2752                 // Make it so.
2753                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2754                 return true;
2755
2756             case R.id.find_on_page:
2757                 // Hide the URL app bar.
2758                 supportAppBar.setVisibility(View.GONE);
2759
2760                 // Show the Find on Page `RelativeLayout`.
2761                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2762
2763                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2764                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2765                 findOnPageEditText.postDelayed(() -> {
2766                     // Set the focus on `findOnPageEditText`.
2767                     findOnPageEditText.requestFocus();
2768
2769                     // Display the keyboard.  `0` sets no input flags.
2770                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2771                 }, 200);
2772                 return true;
2773
2774             case R.id.print:
2775                 // Get a `PrintManager` instance.
2776                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2777
2778                 // Convert `mainWebView` to `printDocumentAdapter`.
2779                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2780
2781                 // Remove the lint error below that `printManager` might be `null`.
2782                 assert printManager != null;
2783
2784                 // Print the document.  The print attributes are `null`.
2785                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2786                 return true;
2787
2788             case R.id.add_to_homescreen:
2789                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2790                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2791                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2792
2793                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2794                 return true;
2795
2796             case R.id.refresh:
2797                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2798                     // Reload the WebView.
2799                     mainWebView.reload();
2800                 } else {  // The stop button was pushed.
2801                     // Stop the loading of the WebView.
2802                     mainWebView.stopLoading();
2803                 }
2804                 return true;
2805
2806             case R.id.ad_consent:
2807                 // Display the ad consent dialog.
2808                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2809                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2810                 return true;
2811
2812             default:
2813                 // Don't consume the event.
2814                 return super.onOptionsItemSelected(menuItem);
2815         }
2816     }
2817
2818     // removeAllCookies is deprecated, but it is required for API < 21.
2819     @SuppressWarnings("deprecation")
2820     @Override
2821     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2822         int menuItemId = menuItem.getItemId();
2823
2824         switch (menuItemId) {
2825             case R.id.home:
2826                 loadUrl(homepage);
2827                 break;
2828
2829             case R.id.back:
2830                 if (mainWebView.canGoBack()) {
2831                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2832                     formattedUrlString = "";
2833
2834                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2835                     navigatingHistory = true;
2836
2837                     // Load the previous website in the history.
2838                     mainWebView.goBack();
2839                 }
2840                 break;
2841
2842             case R.id.forward:
2843                 if (mainWebView.canGoForward()) {
2844                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2845                     formattedUrlString = "";
2846
2847                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2848                     navigatingHistory = true;
2849
2850                     // Load the next website in the history.
2851                     mainWebView.goForward();
2852                 }
2853                 break;
2854
2855             case R.id.history:
2856                 // Get the `WebBackForwardList`.
2857                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2858
2859                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2860                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2861                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2862                 break;
2863
2864             case R.id.requests:
2865                 // Launch the requests activity.
2866                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2867                 startActivity(requestsIntent);
2868                 break;
2869
2870             case R.id.downloads:
2871                 // Launch the system Download Manager.
2872                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2873
2874                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2875                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2876
2877                 startActivity(downloadManagerIntent);
2878                 break;
2879
2880             case R.id.domains:
2881                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2882                 reapplyDomainSettingsOnRestart = true;
2883                 currentDomainName = "";
2884
2885                 // Launch the domains activity.
2886                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2887                 startActivity(domainsIntent);
2888                 break;
2889
2890             case R.id.settings:
2891                 // Set the flag to reapply app settings on restart when returning from Settings.
2892                 reapplyAppSettingsOnRestart = true;
2893
2894                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2895                 reapplyDomainSettingsOnRestart = true;
2896                 currentDomainName = "";
2897
2898                 // Launch the settings activity.
2899                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2900                 startActivity(settingsIntent);
2901                 break;
2902
2903             case R.id.guide:
2904                 // Launch `GuideActivity`.
2905                 Intent guideIntent = new Intent(this, GuideActivity.class);
2906                 startActivity(guideIntent);
2907                 break;
2908
2909             case R.id.about:
2910                 // Launch `AboutActivity`.
2911                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2912                 startActivity(aboutIntent);
2913                 break;
2914
2915             case R.id.clearAndExit:
2916                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2917                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2918
2919                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2920
2921                 // Clear cookies.
2922                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2923                     // The command to remove cookies changed slightly in API 21.
2924                     if (Build.VERSION.SDK_INT >= 21) {
2925                         cookieManager.removeAllCookies(null);
2926                     } else {
2927                         cookieManager.removeAllCookie();
2928                     }
2929
2930                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2931                     try {
2932                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2933                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2934                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2935                     } catch (IOException e) {
2936                         // Do nothing if an error is thrown.
2937                     }
2938                 }
2939
2940                 // Clear DOM storage.
2941                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2942                     // Ask `WebStorage` to clear the DOM storage.
2943                     WebStorage webStorage = WebStorage.getInstance();
2944                     webStorage.deleteAllData();
2945
2946                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2947                     try {
2948                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2949                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2950
2951                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2952                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2953                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2954                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2955                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2956                     } catch (IOException e) {
2957                         // Do nothing if an error is thrown.
2958                     }
2959                 }
2960
2961                 // Clear form data if the API < 26.
2962                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2963                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2964                     webViewDatabase.clearFormData();
2965
2966                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2967                     try {
2968                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2969                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2970                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2971                     } catch (IOException e) {
2972                         // Do nothing if an error is thrown.
2973                     }
2974                 }
2975
2976                 // Clear the cache.
2977                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2978                     // `true` includes disk files.
2979                     mainWebView.clearCache(true);
2980
2981                     // Manually delete the cache directories.
2982                     try {
2983                         // Delete the main cache directory.
2984                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2985
2986                         // Delete the secondary `Service Worker` cache directory.
2987                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2988                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2989                     } catch (IOException e) {
2990                         // Do nothing if an error is thrown.
2991                     }
2992                 }
2993
2994                 // Clear SSL certificate preferences.
2995                 mainWebView.clearSslPreferences();
2996
2997                 // Clear the back/forward history.
2998                 mainWebView.clearHistory();
2999
3000                 // Clear `formattedUrlString`.
3001                 formattedUrlString = null;
3002
3003                 // Clear `customHeaders`.
3004                 customHeaders.clear();
3005
3006                 // Detach all views from `mainWebViewRelativeLayout`.
3007                 mainWebViewRelativeLayout.removeAllViews();
3008
3009                 // Destroy the internal state of `mainWebView`.
3010                 mainWebView.destroy();
3011
3012                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3013                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3014                 if (clearEverything) {
3015                     try {
3016                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
3017                     } catch (IOException e) {
3018                         // Do nothing if an error is thrown.
3019                     }
3020                 }
3021
3022                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3023                 if (Build.VERSION.SDK_INT >= 21) {
3024                     finishAndRemoveTask();
3025                 } else {
3026                     finish();
3027                 }
3028
3029                 // Remove the terminated program from RAM.  The status code is `0`.
3030                 System.exit(0);
3031                 break;
3032         }
3033
3034         // Close the navigation drawer.
3035         drawerLayout.closeDrawer(GravityCompat.START);
3036         return true;
3037     }
3038
3039     @Override
3040     public void onPostCreate(Bundle savedInstanceState) {
3041         super.onPostCreate(savedInstanceState);
3042
3043         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3044         drawerToggle.syncState();
3045     }
3046
3047     @Override
3048     public void onConfigurationChanged(Configuration newConfig) {
3049         super.onConfigurationChanged(newConfig);
3050
3051         // Reload the ad for the free flavor if we not in full screen mode.
3052         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3053             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3054             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
3055         }
3056
3057         // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
3058         // https://code.google.com/p/android/issues/detail?id=20493#c8
3059         // ActivityCompat.invalidateOptionsMenu(this);
3060     }
3061
3062     @Override
3063     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3064         // Store the `HitTestResult`.
3065         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3066
3067         // Create strings.
3068         final String imageUrl;
3069         final String linkUrl;
3070
3071         // Get a handle for the `ClipboardManager`.
3072         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3073
3074         // Remove the lint errors below that `clipboardManager` might be `null`.
3075         assert clipboardManager != null;
3076
3077         switch (hitTestResult.getType()) {
3078             // `SRC_ANCHOR_TYPE` is a link.
3079             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3080                 // Get the target URL.
3081                 linkUrl = hitTestResult.getExtra();
3082
3083                 // Set the target URL as the title of the `ContextMenu`.
3084                 menu.setHeaderTitle(linkUrl);
3085
3086                 // Add a Load URL entry.
3087                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
3088                     loadUrl(linkUrl);
3089                     return false;
3090                 });
3091
3092                 // Add a Copy URL entry.
3093                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
3094                     // Save the link URL in a `ClipData`.
3095                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3096
3097                     // Set the `ClipData` as the clipboard's primary clip.
3098                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3099                     return false;
3100                 });
3101
3102                 // Add a Download URL entry.
3103                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
3104                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3105                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3106                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3107
3108                         // Store the variables for future use by `onRequestPermissionsResult()`.
3109                         downloadUrl = linkUrl;
3110                         downloadContentDisposition = "none";
3111                         downloadContentLength = -1;
3112
3113                         // Show a dialog if the user has previously denied the permission.
3114                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
3115                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
3116                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
3117
3118                             // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
3119                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3120                         } else {  // Show the permission request directly.
3121                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
3122                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3123                         }
3124                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3125                         // Get a handle for the download file alert dialog.
3126                         AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
3127
3128                         // Show the download file alert dialog.
3129                         downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3130                     }
3131                     return false;
3132                 });
3133
3134                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3135                 menu.add(R.string.cancel);
3136                 break;
3137
3138             case WebView.HitTestResult.EMAIL_TYPE:
3139                 // Get the target URL.
3140                 linkUrl = hitTestResult.getExtra();
3141
3142                 // Set the target URL as the title of the `ContextMenu`.
3143                 menu.setHeaderTitle(linkUrl);
3144
3145                 // Add a `Write Email` entry.
3146                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3147                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3148                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3149
3150                     // Parse the url and set it as the data for the `Intent`.
3151                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3152
3153                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3154                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3155
3156                     // Make it so.
3157                     startActivity(emailIntent);
3158                     return false;
3159                 });
3160
3161                 // Add a `Copy Email Address` entry.
3162                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3163                     // Save the email address in a `ClipData`.
3164                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3165
3166                     // Set the `ClipData` as the clipboard's primary clip.
3167                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3168                     return false;
3169                 });
3170
3171                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3172                 menu.add(R.string.cancel);
3173                 break;
3174
3175             // `IMAGE_TYPE` is an image.
3176             case WebView.HitTestResult.IMAGE_TYPE:
3177                 // Get the image URL.
3178                 imageUrl = hitTestResult.getExtra();
3179
3180                 // Set the image URL as the title of the `ContextMenu`.
3181                 menu.setHeaderTitle(imageUrl);
3182
3183                 // Add a `View Image` entry.
3184                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3185                     loadUrl(imageUrl);
3186                     return false;
3187                 });
3188
3189                 // Add a `Download Image` entry.
3190                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3191                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3192                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3193                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3194
3195                         // Store the image URL for use by `onRequestPermissionResult()`.
3196                         downloadImageUrl = imageUrl;
3197
3198                         // Show a dialog if the user has previously denied the permission.
3199                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
3200                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3201                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3202
3203                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
3204                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3205                         } else {  // Show the permission request directly.
3206                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
3207                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3208                         }
3209                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3210                         // Get a handle for the download image alert dialog.
3211                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3212
3213                         // Show the download image alert dialog.
3214                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3215                     }
3216                     return false;
3217                 });
3218
3219                 // Add a `Copy URL` entry.
3220                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3221                     // Save the image URL in a `ClipData`.
3222                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3223
3224                     // Set the `ClipData` as the clipboard's primary clip.
3225                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
3226                     return false;
3227                 });
3228
3229                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3230                 menu.add(R.string.cancel);
3231                 break;
3232
3233
3234             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3235             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3236                 // Get the image URL.
3237                 imageUrl = hitTestResult.getExtra();
3238
3239                 // Set the image URL as the title of the `ContextMenu`.
3240                 menu.setHeaderTitle(imageUrl);
3241
3242                 // Add a `View Image` entry.
3243                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3244                     loadUrl(imageUrl);
3245                     return false;
3246                 });
3247
3248                 // Add a `Download Image` entry.
3249                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3250                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3251                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3252                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3253
3254                         // Store the image URL for use by `onRequestPermissionResult()`.
3255                         downloadImageUrl = imageUrl;
3256
3257                         // Show a dialog if the user has previously denied the permission.
3258                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
3259                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3260                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3261
3262                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
3263                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3264                         } else {  // Show the permission request directly.
3265                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
3266                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3267                         }
3268                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3269                         // Get a handle for the download image alert dialog.
3270                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3271
3272                         // Show the download image alert dialog.
3273                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3274                     }
3275                     return false;
3276                 });
3277
3278                 // Add a `Copy URL` entry.
3279                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3280                     // Save the image URL in a `ClipData`.
3281                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3282
3283                     // Set the `ClipData` as the clipboard's primary clip.
3284                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3285                     return false;
3286                 });
3287
3288                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3289                 menu.add(R.string.cancel);
3290                 break;
3291         }
3292     }
3293
3294     @Override
3295     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3296         // Get the `EditTexts` from the `dialogFragment`.
3297         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3298         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3299
3300         // Extract the strings from the `EditTexts`.
3301         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3302         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3303
3304         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
3305         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3306         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3307         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3308
3309         // Display the new bookmark below the current items in the (0 indexed) list.
3310         int newBookmarkDisplayOrder = bookmarksListView.getCount();
3311
3312         // Create the bookmark.
3313         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3314
3315         // Update `bookmarksCursor` with the current contents of this folder.
3316         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3317
3318         // Update the `ListView`.
3319         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3320
3321         // Scroll to the new bookmark.
3322         bookmarksListView.setSelection(newBookmarkDisplayOrder);
3323     }
3324
3325     @Override
3326     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3327         // Get handles for the views in `dialogFragment`.
3328         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3329         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3330         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3331
3332         // Get new folder name string.
3333         String folderNameString = createFolderNameEditText.getText().toString();
3334
3335         // Get the new folder icon `Bitmap`.
3336         Bitmap folderIconBitmap;
3337         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
3338             // Get the default folder icon and convert it to a `Bitmap`.
3339             Drawable folderIconDrawable = folderIconImageView.getDrawable();
3340             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3341             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3342         } else {  // Use the `WebView` favorite icon.
3343             folderIconBitmap = favoriteIconBitmap;
3344         }
3345
3346         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3347         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3348         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3349         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3350
3351         // Move all the bookmarks down one in the display order.
3352         for (int i = 0; i < bookmarksListView.getCount(); i++) {
3353             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3354             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3355         }
3356
3357         // Create the folder, which will be placed at the top of the `ListView`.
3358         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3359
3360         // Update `bookmarksCursor` with the current contents of this folder.
3361         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3362
3363         // Update the `ListView`.
3364         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3365
3366         // Scroll to the new folder.
3367         bookmarksListView.setSelection(0);
3368     }
3369
3370     @Override
3371     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3372         // Get the shortcut name.
3373         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3374         String shortcutNameString = shortcutNameEditText.getText().toString();
3375
3376         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
3377         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3378
3379         // Setup the shortcut intent.
3380         Intent shortcutIntent = new Intent();
3381         shortcutIntent.setAction(Intent.ACTION_VIEW);
3382         shortcutIntent.setData(Uri.parse(formattedUrlString));
3383
3384         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
3385         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3386
3387         // Add the required fields to the shortcut info builder.
3388         shortcutInfoBuilder.setIcon(favoriteIcon);
3389         shortcutInfoBuilder.setIntent(shortcutIntent);
3390         shortcutInfoBuilder.setShortLabel(shortcutNameString);
3391
3392         // Request the pin.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3393         ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3394     }
3395
3396     @Override
3397     public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3398         switch (downloadType) {
3399             case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3400                 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3401                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3402                 break;
3403
3404             case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3405                 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3406                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3407                 break;
3408         }
3409     }
3410
3411     @Override
3412     public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3413         switch (requestCode) {
3414             case DOWNLOAD_FILE_REQUEST_CODE:
3415                 // Show the download file alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
3416                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3417
3418                 // On API 23, displaying the fragment must be delayed or the app will crash.
3419                 if (Build.VERSION.SDK_INT == 23) {
3420                     new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3421                 } else {
3422                     downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3423                 }
3424
3425                 // Reset the download variables.
3426                 downloadUrl = "";
3427                 downloadContentDisposition = "";
3428                 downloadContentLength = 0;
3429                 break;
3430
3431             case DOWNLOAD_IMAGE_REQUEST_CODE:
3432                 // Show the download image alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
3433                 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3434
3435                 // On API 23, displaying the fragment must be delayed or the app will crash.
3436                 if (Build.VERSION.SDK_INT == 23) {
3437                     new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3438                 } else {
3439                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3440                 }
3441
3442                 // Reset the image URL variable.
3443                 downloadImageUrl = "";
3444                 break;
3445         }
3446     }
3447
3448     @Override
3449     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3450         // Download the image if it has an HTTP or HTTPS URI.
3451         if (imageUrl.startsWith("http")) {
3452             // Get a handle for the system `DOWNLOAD_SERVICE`.
3453             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3454
3455             // Parse `imageUrl`.
3456             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3457
3458             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
3459             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3460             if (firstPartyCookiesEnabled) {
3461                 // Get the cookies for `imageUrl`.
3462                 String cookies = cookieManager.getCookie(imageUrl);
3463
3464                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3465                 downloadRequest.addRequestHeader("Cookie", cookies);
3466             }
3467
3468             // Get the file name from the dialog fragment.
3469             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3470             String imageName = downloadImageNameEditText.getText().toString();
3471
3472             // Specify the download location.
3473             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3474                 // Download to the public download directory.
3475                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3476             } else {  // External write permission denied.
3477                 // Download to the app's external download directory.
3478                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3479             }
3480
3481             // Allow `MediaScanner` to index the download if it is a media file.
3482             downloadRequest.allowScanningByMediaScanner();
3483
3484             // Add the URL as the description for the download.
3485             downloadRequest.setDescription(imageUrl);
3486
3487             // Show the download notification after the download is completed.
3488             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3489
3490             // Remove the lint warning below that `downloadManager` might be `null`.
3491             assert downloadManager != null;
3492
3493             // Initiate the download.
3494             downloadManager.enqueue(downloadRequest);
3495         } else {  // The image is not an HTTP or HTTPS URI.
3496             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3497         }
3498     }
3499
3500     @Override
3501     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3502         // Download the file if it has an HTTP or HTTPS URI.
3503         if (downloadUrl.startsWith("http")) {
3504             // Get a handle for the system `DOWNLOAD_SERVICE`.
3505             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3506
3507             // Parse `downloadUrl`.
3508             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3509
3510             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
3511             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3512             if (firstPartyCookiesEnabled) {
3513                 // Get the cookies for `downloadUrl`.
3514                 String cookies = cookieManager.getCookie(downloadUrl);
3515
3516                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3517                 downloadRequest.addRequestHeader("Cookie", cookies);
3518             }
3519
3520             // Get the file name from the dialog fragment.
3521             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3522             String fileName = downloadFileNameEditText.getText().toString();
3523
3524             // Specify the download location.
3525             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3526                 // Download to the public download directory.
3527                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3528             } else {  // External write permission denied.
3529                 // Download to the app's external download directory.
3530                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3531             }
3532
3533             // Allow `MediaScanner` to index the download if it is a media file.
3534             downloadRequest.allowScanningByMediaScanner();
3535
3536             // Add the URL as the description for the download.
3537             downloadRequest.setDescription(downloadUrl);
3538
3539             // Show the download notification after the download is completed.
3540             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3541
3542             // Remove the lint warning below that `downloadManager` might be `null`.
3543             assert downloadManager != null;
3544
3545             // Initiate the download.
3546             downloadManager.enqueue(downloadRequest);
3547         } else {  // The download is not an HTTP or HTTPS URI.
3548             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3549         }
3550     }
3551
3552     @Override
3553     public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3554         // Get handles for the views from `dialogFragment`.
3555         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3556         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3557         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3558
3559         // Store the bookmark strings.
3560         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3561         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3562
3563         // Update the bookmark.
3564         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
3565             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3566         } else {  // Update the bookmark using the `WebView` favorite icon.
3567             // Convert the favorite icon to a byte array.  `0` is for lossless compression (the only option for a PNG).
3568             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3569             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3570             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3571
3572             //  Update the bookmark and the favorite icon.
3573             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3574         }
3575
3576         // Update `bookmarksCursor` with the current contents of this folder.
3577         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3578
3579         // Update the `ListView`.
3580         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3581     }
3582
3583     @Override
3584     public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3585         // Get handles for the views from `dialogFragment`.
3586         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3587         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3588         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3589         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3590
3591         // Get the new folder name.
3592         String newFolderNameString = editFolderNameEditText.getText().toString();
3593
3594         // Check if the favorite icon has changed.
3595         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
3596             // Update the name in the database.
3597             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3598         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
3599             // Get the new folder icon `Bitmap`.
3600             Bitmap folderIconBitmap;
3601             if (defaultFolderIconRadioButton.isChecked()) {
3602                 // Get the default folder icon and convert it to a `Bitmap`.
3603                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3604                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3605                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3606             } else {  // Use the `WebView` favorite icon.
3607                 folderIconBitmap = favoriteIconBitmap;
3608             }
3609
3610             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3611             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3612             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3613             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3614
3615             // Update the folder icon in the database.
3616             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3617         } else {  // The folder icon and the name have changed.
3618             // Get the new folder icon `Bitmap`.
3619             Bitmap folderIconBitmap;
3620             if (defaultFolderIconRadioButton.isChecked()) {
3621                 // Get the default folder icon and convert it to a `Bitmap`.
3622                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3623                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3624                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3625             } else {  // Use the `WebView` favorite icon.
3626                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3627             }
3628
3629             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3630             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3631             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3632             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3633
3634             // Update the folder name and icon in the database.
3635             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3636         }
3637
3638         // Update `bookmarksCursor` with the current contents of this folder.
3639         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3640
3641         // Update the `ListView`.
3642         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3643     }
3644
3645     @Override
3646     public void onHttpAuthenticationCancel() {
3647         // Cancel the `HttpAuthHandler`.
3648         httpAuthHandler.cancel();
3649     }
3650
3651     @Override
3652     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3653         // Get handles for the `EditTexts`.
3654         EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3655         EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3656
3657         // Proceed with the HTTP authentication.
3658         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3659     }
3660
3661     public void viewSslCertificate(View view) {
3662         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3663         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3664         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3665     }
3666
3667     @Override
3668     public void onSslErrorCancel() {
3669         sslErrorHandler.cancel();
3670     }
3671
3672     @Override
3673     public void onSslErrorProceed() {
3674         sslErrorHandler.proceed();
3675     }
3676
3677     @Override
3678     public void onSslMismatchBack() {
3679         if (mainWebView.canGoBack()) {  // There is a back page in the history.
3680             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3681             formattedUrlString = "";
3682
3683             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3684             navigatingHistory = true;
3685
3686             // Go back.
3687             mainWebView.goBack();
3688         } else {  // There are no pages to go back to.
3689             // Load a blank page
3690             loadUrl("");
3691         }
3692     }
3693
3694     @Override
3695     public void onSslMismatchProceed() {
3696         // Do not check the pinned SSL certificate for this domain again until the domain changes.
3697         ignorePinnedSslCertificate = true;
3698     }
3699
3700     @Override
3701     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3702         // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3703         formattedUrlString = "";
3704
3705         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3706         navigatingHistory = true;
3707
3708         // Load the history entry.
3709         mainWebView.goBackOrForward(moveBackOrForwardSteps);
3710     }
3711
3712     @Override
3713     public void onClearHistory() {
3714         // Clear the history.
3715         mainWebView.clearHistory();
3716     }
3717
3718     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3719     @Override
3720     public void onBackPressed() {
3721         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
3722             // Close the navigation drawer.
3723             drawerLayout.closeDrawer(GravityCompat.START);
3724         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
3725             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
3726                 // close the bookmarks drawer.
3727                 drawerLayout.closeDrawer(GravityCompat.END);
3728             } else {  // A subfolder is displayed.
3729                 // Place the former parent folder in `currentFolder`.
3730                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3731
3732                 // Load the new folder.
3733                 loadBookmarksFolder();
3734             }
3735
3736         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
3737             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3738             formattedUrlString = "";
3739
3740             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3741             navigatingHistory = true;
3742
3743             // Go back.
3744             mainWebView.goBack();
3745         } else {  // There isn't anything to do in Privacy Browser.
3746             // Pass `onBackPressed()` to the system.
3747             super.onBackPressed();
3748         }
3749     }
3750
3751     // Process the results of an upload file chooser.  Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
3752     @Override
3753     public void onActivityResult(int requestCode, int resultCode, Intent data) {
3754         // File uploads only work on API >= 21.
3755         if (Build.VERSION.SDK_INT >= 21) {
3756             // Pass the file to the WebView.
3757             fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3758         }
3759     }
3760
3761     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3762         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
3763         String unformattedUrlString = urlTextBox.getText().toString().trim();
3764
3765         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
3766         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3767             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
3768             if (!unformattedUrlString.startsWith("http")) {
3769                 unformattedUrlString = "http://" + unformattedUrlString;
3770             }
3771
3772             // Initialize `unformattedUrl`.
3773             URL unformattedUrl = null;
3774
3775             // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
3776             try {
3777                 unformattedUrl = new URL(unformattedUrlString);
3778             } catch (MalformedURLException e) {
3779                 e.printStackTrace();
3780             }
3781
3782             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3783             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3784             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3785             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3786             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3787             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3788
3789             // Build the URI.
3790             Uri.Builder formattedUri = new Uri.Builder();
3791             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3792
3793             // Decode `formattedUri` as a `String` in `UTF-8`.
3794             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3795         } else if (unformattedUrlString.isEmpty()){  // Load a blank web site.
3796             // Load a blank string.
3797             formattedUrlString = "";
3798         } else {  // Search for the contents of the URL box.
3799             // Sanitize the search input and convert it to a search.
3800             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3801
3802             // Add the base search URL.
3803             formattedUrlString = searchURL + encodedUrlString;
3804         }
3805
3806         // Clear the focus from the URL text box.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3807         urlTextBox.clearFocus();
3808
3809         // Make it so.
3810         loadUrl(formattedUrlString);
3811     }
3812
3813     private void loadUrl(String url) {// Apply any custom domain settings.
3814         // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3815         formattedUrlString = url;
3816
3817         // Apply the domain settings.
3818         applyDomainSettings(url, true, false);
3819
3820         // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3821         urlIsLoading = !url.equals("");
3822
3823         // Load the URL.
3824         mainWebView.loadUrl(url, customHeaders);
3825     }
3826
3827     public void findPreviousOnPage(View view) {
3828         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
3829         mainWebView.findNext(false);
3830     }
3831
3832     public void findNextOnPage(View view) {
3833         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3834         mainWebView.findNext(true);
3835     }
3836
3837     public void closeFindOnPage(View view) {
3838         // Delete the contents of `find_on_page_edittext`.
3839         findOnPageEditText.setText(null);
3840
3841         // Clear the highlighted phrases.
3842         mainWebView.clearMatches();
3843
3844         // Hide the Find on Page `RelativeLayout`.
3845         findOnPageLinearLayout.setVisibility(View.GONE);
3846
3847         // Show the URL app bar.
3848         supportAppBar.setVisibility(View.VISIBLE);
3849
3850         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
3851         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3852     }
3853
3854     private void applyAppSettings() {
3855         // Get a handle for the shared preferences.
3856         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3857
3858         // Store the values from the shared preferences in variables.
3859         String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3860         String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3861         String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3862         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3863         String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3864         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3865         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3866         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3867         proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3868         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3869         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3870         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3871         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3872
3873         // Set the homepage, search, and proxy options.
3874         if (proxyThroughOrbot) {  // Set the Tor options.
3875             // Set `torHomepageString` as `homepage`.
3876             homepage = torHomepageString;
3877
3878             // If formattedUrlString is null assign the homepage to it.
3879             if (formattedUrlString == null) {
3880                 formattedUrlString = homepage;
3881             }
3882
3883             // Set the search URL.
3884             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
3885                 searchURL = torSearchCustomURLString;
3886             } else {  // Use the string from the pre-built list.
3887                 searchURL = torSearchString;
3888             }
3889
3890             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
3891             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3892
3893             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
3894             if (darkTheme) {
3895                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3896             } else {
3897                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3898             }
3899
3900             // Display a message to the user if waiting for Orbot.
3901             if (!orbotStatus.equals("ON")) {
3902                 // Set `waitingForOrbot`.
3903                 waitingForOrbot = true;
3904
3905                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
3906                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3907             }
3908         } else {  // Set the non-Tor options.
3909             // Set `homepageString` as `homepage`.
3910             homepage = homepageString;
3911
3912             // If formattedUrlString is null assign the homepage to it.
3913             if (formattedUrlString == null) {
3914                 formattedUrlString = homepage;
3915             }
3916
3917             // Set the search URL.
3918             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
3919                 searchURL = searchCustomURLString;
3920             } else {  // Use the string from the pre-built list.
3921                 searchURL = searchString;
3922             }
3923
3924             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
3925             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3926
3927             // Set the default `appBar` background.  `this` refers to the context.
3928             if (darkTheme) {
3929                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3930             } else {
3931                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3932             }
3933
3934             // Reset `waitingForOrbot.
3935             waitingForOrbot = false;
3936         }
3937
3938         // Set Do Not Track status.
3939         if (doNotTrackEnabled) {
3940             customHeaders.put("DNT", "1");
3941         } else {
3942             customHeaders.remove("DNT");
3943         }
3944
3945         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3946         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3947             if (hideSystemBarsOnFullscreen) {  // Hide everything.
3948                 // Remove the translucent navigation setting if it is currently flagged.
3949                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3950
3951                 // Remove the translucent status bar overlay.
3952                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3953
3954                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3955                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3956
3957                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3958                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3959                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3960                  */
3961                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3962             } else {  // Hide everything except the status and navigation bars.
3963                 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3964                 rootCoordinatorLayout.setSystemUiVisibility(0);
3965
3966                 // Add the translucent status flag if it is unset.
3967                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3968
3969                 if (translucentNavigationBarOnFullscreen) {
3970                     // Set the navigation bar to be translucent.
3971                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3972                 } else {
3973                     // Set the navigation bar to be black.
3974                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3975                 }
3976             }
3977         } else {  // Privacy Browser is not in full screen browsing mode.
3978             // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3979             inFullScreenBrowsingMode = false;
3980
3981             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3982             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3983                 appBar.show();
3984             }
3985
3986             // Show the `BannerAd` in the free flavor.
3987             if (BuildConfig.FLAVOR.contentEquals("free")) {
3988                 // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3989                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3990             }
3991
3992             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3993             rootCoordinatorLayout.setSystemUiVisibility(0);
3994
3995             // Remove the translucent navigation bar flag if it is set.
3996             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3997
3998             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3999             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4000
4001             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
4002             rootCoordinatorLayout.setFitsSystemWindows(true);
4003         }
4004     }
4005
4006     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
4007     // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4008     @SuppressWarnings("deprecation")
4009     private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
4010         // Parse the URL into a URI.
4011         Uri uri = Uri.parse(url);
4012
4013         // Extract the domain from `uri`.
4014         String hostName = uri.getHost();
4015
4016         // Initialize `loadingNewDomainName`.
4017         boolean loadingNewDomainName;
4018
4019         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
4020         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
4021         //noinspection SimplifiableIfStatement
4022         if ((hostName == null) || (currentDomainName == null)) {
4023             loadingNewDomainName = true;
4024         } else {  // Determine if `hostName` equals `currentDomainName`.
4025             loadingNewDomainName = !hostName.equals(currentDomainName);
4026         }
4027
4028         // Strings don't like to be null.
4029         if (hostName == null) {
4030             hostName = "";
4031         }
4032
4033         // Only apply the domain settings if a new domain is being loaded.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
4034         if (loadingNewDomainName) {
4035             // Set the new `hostname` as the `currentDomainName`.
4036             currentDomainName = hostName;
4037
4038             // Reset `ignorePinnedSslCertificate`.
4039             ignorePinnedSslCertificate = false;
4040
4041             // Reset the favorite icon if specified.
4042             if (resetFavoriteIcon) {
4043                 favoriteIconBitmap = favoriteIconDefaultBitmap;
4044                 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
4045             }
4046
4047             // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
4048             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
4049
4050             // Get a full cursor from `domainsDatabaseHelper`.
4051             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
4052
4053             // Initialize `domainSettingsSet`.
4054             Set<String> domainSettingsSet = new HashSet<>();
4055
4056             // Get the domain name column index.
4057             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
4058
4059             // Populate `domainSettingsSet`.
4060             for (int i = 0; i < domainNameCursor.getCount(); i++) {
4061                 // Move `domainsCursor` to the current row.
4062                 domainNameCursor.moveToPosition(i);
4063
4064                 // Store the domain name in `domainSettingsSet`.
4065                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
4066             }
4067
4068             // Close `domainNameCursor.
4069             domainNameCursor.close();
4070
4071             // Initialize variables to track if domain settings will be applied and, if so, under which name.
4072             domainSettingsApplied = false;
4073             String domainNameInDatabase = null;
4074
4075             // Check the hostname.
4076             if (domainSettingsSet.contains(hostName)) {
4077                 domainSettingsApplied = true;
4078                 domainNameInDatabase = hostName;
4079             }
4080
4081             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
4082             while (!domainSettingsApplied && hostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the host name.
4083                 if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
4084                     // Apply the domain settings.
4085                     domainSettingsApplied = true;
4086
4087                     // Store the applied domain names as it appears in the database.
4088                     domainNameInDatabase = "*." + hostName;
4089                 }
4090
4091                 // Strip out the lowest subdomain of of the host name.
4092                 hostName = hostName.substring(hostName.indexOf(".") + 1);
4093             }
4094
4095
4096             // Get a handle for the shared preference.
4097             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4098
4099             // Store the general preference information.
4100             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
4101             String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
4102             defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
4103             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
4104             nightMode = sharedPreferences.getBoolean("night_mode", false);
4105
4106             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
4107                 // Get a cursor for the current host and move it to the first position.
4108                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
4109                 currentHostDomainSettingsCursor.moveToFirst();
4110
4111                 // Get the settings from the cursor.
4112                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
4113                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
4114                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
4115                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
4116                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
4117                 // Form data can be removed once the minimum API >= 26.
4118                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
4119                 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
4120                 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
4121                 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
4122                 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
4123                 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
4124                 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
4125                 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
4126                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
4127                 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
4128                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
4129                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
4130                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
4131                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
4132                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
4133                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
4134                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
4135                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4136                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4137
4138                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
4139                 switch (nightModeInt) {
4140                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
4141                         nightMode = true;
4142                         break;
4143
4144                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
4145                         nightMode = false;
4146                         break;
4147                 }
4148
4149                 // Store the domain JavaScript status.  This is used by the options menu night mode toggle.
4150                 domainSettingsJavaScriptEnabled = javaScriptEnabled;
4151
4152                 // Enable JavaScript if night mode is enabled.
4153                 if (nightMode) {
4154                     javaScriptEnabled = true;
4155                 }
4156
4157                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
4158                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4159                     pinnedDomainSslStartDate = null;
4160                 } else {
4161                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4162                 }
4163
4164                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
4165                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4166                     pinnedDomainSslEndDate = null;
4167                 } else {
4168                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4169                 }
4170
4171                 // Close `currentHostDomainSettingsCursor`.
4172                 currentHostDomainSettingsCursor.close();
4173
4174                 // Apply the domain settings.
4175                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4176                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4177                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4178
4179                 // Apply the form data setting if the API < 26.
4180                 if (Build.VERSION.SDK_INT < 26) {
4181                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4182                 }
4183
4184                 // Apply the font size.
4185                 if (fontSize == 0) {  // Apply the default font size.
4186                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4187                 } else {  // Apply the specified font size.
4188                     mainWebView.getSettings().setTextZoom(fontSize);
4189                 }
4190
4191                 // Set third-party cookies status if API >= 21.
4192                 if (Build.VERSION.SDK_INT >= 21) {
4193                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4194                 }
4195
4196                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
4197                 // <https://redmine.stoutner.com/issues/160>
4198                 if (!urlIsLoading) {
4199                     // Set the user agent.
4200                     if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
4201                         // Get the array position of the default user agent name.
4202                         int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4203
4204                         // Set the user agent according to the system default.
4205                         switch (defaultUserAgentArrayPosition) {
4206                             case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4207                                 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4208                                 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4209                                 break;
4210
4211                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4212                                 // Set the user agent to `""`, which uses the default value.
4213                                 mainWebView.getSettings().setUserAgentString("");
4214                                 break;
4215
4216                             case SETTINGS_CUSTOM_USER_AGENT:
4217                                 // Set the custom user agent.
4218                                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4219                                 break;
4220
4221                             default:
4222                                 // Get the user agent string from the user agent data array
4223                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4224                         }
4225                     } else {  // Set the user agent according to the stored name.
4226                         // Get the array position of the user agent name.
4227                         int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4228
4229                         switch (userAgentArrayPosition) {
4230                             case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
4231                                 mainWebView.getSettings().setUserAgentString(userAgentName);
4232                                 break;
4233
4234                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4235                                 // Set the user agent to `""`, which uses the default value.
4236                                 mainWebView.getSettings().setUserAgentString("");
4237                                 break;
4238
4239                             default:
4240                                 // Get the user agent string from the user agent data array.
4241                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4242                         }
4243                     }
4244
4245                     // Set swipe to refresh.
4246                     switch (swipeToRefreshInt) {
4247                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4248                             // Set swipe to refresh according to the default.
4249                             swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4250                             break;
4251
4252                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4253                             // Enable swipe to refresh.
4254                             swipeRefreshLayout.setEnabled(true);
4255                             break;
4256
4257                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4258                             // Disable swipe to refresh.
4259                             swipeRefreshLayout.setEnabled(false);
4260                     }
4261
4262                     // Store the applied user agent string, which is used in the View Source activity.
4263                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4264                 }
4265
4266                 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4267                 if (darkTheme) {
4268                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4269                 } else {
4270                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4271                 }
4272             } else {  // The new URL does not have custom domain settings.  Load the defaults.
4273                 // Store the values from `sharedPreferences` in variables.
4274                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4275                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4276                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4277                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4278                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);  // Form data can be removed once the minimum API >= 26.
4279                 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4280                 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4281                 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4282                 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4283                 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4284                 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4285
4286                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4287                 if (nightMode) {
4288                     javaScriptEnabled = true;
4289                 }
4290
4291                 // Apply the default settings.
4292                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4293                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4294                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4295                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4296                 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4297
4298                 // Apply the form data setting if the API < 26.
4299                 if (Build.VERSION.SDK_INT < 26) {
4300                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4301                 }
4302
4303                 // Reset the pinned SSL certificate information.
4304                 domainSettingsDatabaseId = -1;
4305                 pinnedDomainSslCertificate = false;
4306                 pinnedDomainSslIssuedToCNameString = "";
4307                 pinnedDomainSslIssuedToONameString = "";
4308                 pinnedDomainSslIssuedToUNameString = "";
4309                 pinnedDomainSslIssuedByCNameString = "";
4310                 pinnedDomainSslIssuedByONameString = "";
4311                 pinnedDomainSslIssuedByUNameString = "";
4312                 pinnedDomainSslStartDate = null;
4313                 pinnedDomainSslEndDate = null;
4314
4315                 // Set third-party cookies status if API >= 21.
4316                 if (Build.VERSION.SDK_INT >= 21) {
4317                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4318                 }
4319
4320                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
4321                 // <https://redmine.stoutner.com/issues/160>
4322                 if (!urlIsLoading) {
4323                     // Get the array position of the user agent name.
4324                     int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4325
4326                     // Set the user agent.
4327                     switch (userAgentArrayPosition) {
4328                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4329                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4330                             mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4331                             break;
4332
4333                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4334                             // Set the user agent to `""`, which uses the default value.
4335                             mainWebView.getSettings().setUserAgentString("");
4336                             break;
4337
4338                         case SETTINGS_CUSTOM_USER_AGENT:
4339                             // Set the custom user agent.
4340                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4341                             break;
4342
4343                         default:
4344                             // Get the user agent string from the user agent data array
4345                             mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4346                     }
4347
4348                     // Store the applied user agent string, which is used in the View Source activity.
4349                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4350                 }
4351
4352                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4353                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4354             }
4355
4356             // Close `domainsDatabaseHelper`.
4357             domainsDatabaseHelper.close();
4358
4359             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
4360             onTheFlyDisplayImagesSet = false;
4361             setDisplayWebpageImages();
4362
4363             // Update the privacy icons, but only if `mainMenu` has already been populated.
4364             if (mainMenu != null) {
4365                 updatePrivacyIcons(true);
4366             }
4367         }
4368
4369         // Reload the website if returning from the Domains activity.
4370         if (reloadWebsite) {
4371             mainWebView.reload();
4372         }
4373     }
4374
4375     private void setDisplayWebpageImages() {
4376         if (!onTheFlyDisplayImagesSet) {
4377             if (domainSettingsApplied) {  // Custom domain settings are applied.
4378                 switch (displayWebpageImagesInt) {
4379                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4380                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4381                         break;
4382
4383                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4384                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
4385                         break;
4386
4387                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4388                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
4389                         break;
4390                 }
4391             } else {  // Default settings are applied.
4392                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4393             }
4394         }
4395     }
4396
4397     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4398         // Get handles for the menu items.
4399         MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4400         MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4401         MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4402         MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4403
4404         // Update the privacy icon.
4405         if (javaScriptEnabled) {  // JavaScript is enabled.
4406             privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4407         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
4408             privacyMenuItem.setIcon(R.drawable.warning);
4409         } else {  // All the dangerous features are disabled.
4410             privacyMenuItem.setIcon(R.drawable.privacy_mode);
4411         }
4412
4413         // Update the first-party cookies icon.
4414         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
4415             firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4416         } else {  // First-party cookies are disabled.
4417             if (darkTheme) {
4418                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4419             } else {
4420                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4421             }
4422         }
4423
4424         // Update the DOM storage icon.
4425         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
4426             domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4427         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
4428             if (darkTheme) {
4429                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4430             } else {
4431                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4432             }
4433         } else {  // JavaScript is disabled, so DOM storage is ghosted.
4434             if (darkTheme) {
4435                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4436             } else {
4437                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4438             }
4439         }
4440
4441         // Update the refresh icon.
4442         if (darkTheme) {
4443             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4444         } else {
4445             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4446         }
4447
4448         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4449         if (runInvalidateOptionsMenu) {
4450             invalidateOptionsMenu();
4451         }
4452     }
4453
4454     private void highlightUrlText() {
4455         String urlString = urlTextBox.getText().toString();
4456
4457         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4458             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4459         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4460             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4461         }
4462
4463         // Get the index of the `/` immediately after the domain name.
4464         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4465
4466         // De-emphasize the text after the domain name.
4467         if (endOfDomainName > 0) {
4468             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4469         }
4470     }
4471
4472     private void loadBookmarksFolder() {
4473         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4474         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4475
4476         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
4477         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4478             @Override
4479             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4480                 // Inflate the individual item layout.  `false` does not attach it to the root.
4481                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4482             }
4483
4484             @Override
4485             public void bindView(View view, Context context, Cursor cursor) {
4486                 // Get handles for the views.
4487                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4488                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4489
4490                 // Get the favorite icon byte array from the cursor.
4491                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4492
4493                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4494                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4495
4496                 // Display the bitmap in `bookmarkFavoriteIcon`.
4497                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4498
4499                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4500                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4501                 bookmarkNameTextView.setText(bookmarkNameString);
4502
4503                 // Make the font bold for folders.
4504                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4505                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4506                 } else {  // Reset the font to default for normal bookmarks.
4507                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4508                 }
4509             }
4510         };
4511
4512         // Populate the `ListView` with the adapter.
4513         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4514
4515         // Set the bookmarks drawer title.
4516         if (currentBookmarksFolder.isEmpty()) {
4517             bookmarksTitleTextView.setText(R.string.bookmarks);
4518         } else {
4519             bookmarksTitleTextView.setText(currentBookmarksFolder);
4520         }
4521     }
4522 }