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