]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Add UltraPrivacy. https://redmine.stoutner.com/issues/310
[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 `whiteListResultStringArray`.
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                         // The resource request was blocked.  Return an empty web resource response.
1397                         return emptyWebResourceResponse;
1398                     }
1399                 }
1400
1401                 // Check EasyPrivacy if it is enabled.
1402                 if (easyPrivacyEnabled) {
1403                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1404                         // The resource request was blocked.  Return an empty web resource response.
1405                         return emptyWebResourceResponse;
1406                     }
1407                 }
1408
1409                 // Check Fanboy’s Annoyance List if it is enabled.
1410                 if (fanboysAnnoyanceListEnabled) {
1411                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1412                         // The resource request was blocked.  Return an empty web resource response.
1413                         return emptyWebResourceResponse;
1414                     }
1415                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1416                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1417                         // The resource request was blocked.  Return an empty web resource response.
1418                         return emptyWebResourceResponse;
1419                     }
1420                 }
1421
1422                 // Add the request to the log because it hasn't been processed by any of the previous checks.
1423                 if (whiteListResultStringArray != null ) {  // The request was processed by a whitelist.
1424                     resourceRequests.add(whiteListResultStringArray);
1425                 } else {  // The request didn't match any blocklist entry.  Log it as a defult request.
1426                     resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1427                 }
1428
1429                 // The resource request has not been blocked.  `return null` loads the requested resource.
1430                 return null;
1431             }
1432
1433             // Handle HTTP authentication requests.
1434             @Override
1435             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1436                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1437                 httpAuthHandler = handler;
1438
1439                 // Display the HTTP authentication dialog.
1440                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1441                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1442             }
1443
1444             // Update the URL in urlTextBox when the page starts to load.
1445             @Override
1446             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1447                 // Reset the list of resource requests.
1448                 resourceRequests.clear();
1449
1450                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1451                 if (nightMode) {
1452                     mainWebView.setVisibility(View.INVISIBLE);
1453                 }
1454
1455                 // Hide the keyboard.  `0` indicates no additional flags.
1456                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1457
1458                 // Check to see if Privacy Browser is waiting on Orbot.
1459                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1460                     // 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.
1461                     formattedUrlString = url;
1462
1463                     // Display the formatted URL text.
1464                     urlTextBox.setText(formattedUrlString);
1465
1466                     // Apply text highlighting to `urlTextBox`.
1467                     highlightUrlText();
1468
1469                     // Apply any custom domain settings if the URL was loaded by navigating history.
1470                     if (navigatingHistory) {
1471                         // Reset `navigatingHistory`.
1472                         navigatingHistory = false;
1473
1474                         // Apply the domain settings.
1475                         applyDomainSettings(url, true, false);
1476                     }
1477
1478                     // 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.
1479                     urlIsLoading = true;
1480                 }
1481             }
1482
1483             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1484             @Override
1485             public void onPageFinished(WebView view, String url) {
1486                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1487                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1488                     cookieManager.flush();
1489                 }
1490
1491                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1492                 urlIsLoading = false;
1493
1494                 // Clear the cache and history if Incognito Mode is enabled.
1495                 if (incognitoModeEnabled) {
1496                     // Clear the cache.  `true` includes disk files.
1497                     mainWebView.clearCache(true);
1498
1499                     // Clear the back/forward history.
1500                     mainWebView.clearHistory();
1501
1502                     // Manually delete cache folders.
1503                     try {
1504                         // Delete the main cache directory.
1505                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1506
1507                         // Delete the secondary `Service Worker` cache directory.
1508                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1509                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1510                     } catch (IOException e) {
1511                         // Do nothing if an error is thrown.
1512                     }
1513                 }
1514
1515                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1516                 if (!waitingForOrbot) {
1517                     // Check to see if `WebView` has set `url` to be `about:blank`.
1518                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1519                         // Set `formattedUrlString` to `""`.
1520                         formattedUrlString = "";
1521
1522                         urlTextBox.setText(formattedUrlString);
1523
1524                         // Request focus for `urlTextBox`.
1525                         urlTextBox.requestFocus();
1526
1527                         // Display the keyboard.
1528                         inputMethodManager.showSoftInput(urlTextBox, 0);
1529
1530                         // Apply the domain settings.  This clears any settings from the previous domain.
1531                         applyDomainSettings(formattedUrlString, true, false);
1532                     } else {  // `WebView` has loaded a webpage.
1533                         // Set `formattedUrlString`.
1534                         formattedUrlString = url;
1535
1536                         // Only update `urlTextBox` if the user is not typing in it.
1537                         if (!urlTextBox.hasFocus()) {
1538                             // Display the formatted URL text.
1539                             urlTextBox.setText(formattedUrlString);
1540
1541                             // Apply text highlighting to `urlTextBox`.
1542                             highlightUrlText();
1543                         }
1544                     }
1545
1546                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1547                     sslCertificate = mainWebView.getCertificate();
1548
1549                     // 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.
1550                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1551                         // Initialize the current SSL certificate variables.
1552                         String currentWebsiteIssuedToCName = "";
1553                         String currentWebsiteIssuedToOName = "";
1554                         String currentWebsiteIssuedToUName = "";
1555                         String currentWebsiteIssuedByCName = "";
1556                         String currentWebsiteIssuedByOName = "";
1557                         String currentWebsiteIssuedByUName = "";
1558                         Date currentWebsiteSslStartDate = null;
1559                         Date currentWebsiteSslEndDate = null;
1560
1561
1562                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1563                         if (sslCertificate != null) {
1564                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1565                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1566                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1567                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1568                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1569                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1570                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1571                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1572                         }
1573
1574                         // 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`.
1575                         String currentWebsiteSslStartDateString = "";
1576                         String currentWebsiteSslEndDateString = "";
1577                         String pinnedDomainSslStartDateString = "";
1578                         String pinnedDomainSslEndDateString = "";
1579
1580                         // Convert the `Dates` to `Strings` if they are not `null`.
1581                         if (currentWebsiteSslStartDate != null) {
1582                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1583                         }
1584
1585                         if (currentWebsiteSslEndDate != null) {
1586                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1587                         }
1588
1589                         if (pinnedDomainSslStartDate != null) {
1590                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1591                         }
1592
1593                         if (pinnedDomainSslEndDate != null) {
1594                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1595                         }
1596
1597                         // Check to see if the pinned SSL certificate matches the current website certificate.
1598                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1599                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1600                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1601                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1602                             // The pinned SSL certificate doesn't match the current domain certificate.
1603                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1604                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1605                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1606                         }
1607                     }
1608                 }
1609             }
1610
1611             // Handle SSL Certificate errors.
1612             @Override
1613             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1614                 // Get the current website SSL certificate.
1615                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1616
1617                 // Extract the individual pieces of information from the current website SSL certificate.
1618                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1619                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1620                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1621                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1622                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1623                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1624                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1625                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1626
1627                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1628                 if (pinnedDomainSslCertificate &&
1629                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1630                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1631                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1632                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1633                     // An SSL certificate is pinned and matches the current domain certificate.
1634                     // Proceed to the website without displaying an error.
1635                     handler.proceed();
1636                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1637                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1638                     sslErrorHandler = handler;
1639
1640                     // Display the SSL error `AlertDialog`.
1641                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1642                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1643                 }
1644             }
1645         });
1646
1647         // Load the website if not waiting for Orbot to connect.
1648         if (!waitingForOrbot) {
1649             loadUrl(formattedUrlString);
1650         }
1651     }
1652
1653     @Override
1654     protected void onNewIntent(Intent intent) {
1655         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1656         setIntent(intent);
1657
1658         // Check to see if the intent contains a new URL.
1659         if (intent.getData() != null) {
1660             // Get the intent data.
1661             final Uri intentUriData = intent.getData();
1662
1663             // Load the website.
1664             loadUrl(intentUriData.toString());
1665
1666             // Close the navigation drawer if it is open.
1667             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1668                 drawerLayout.closeDrawer(GravityCompat.START);
1669             }
1670
1671             // Close the bookmarks drawer if it is open.
1672             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1673                 drawerLayout.closeDrawer(GravityCompat.END);
1674             }
1675
1676             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1677             mainWebView.requestFocus();
1678         }
1679     }
1680
1681     @Override
1682     public void onRestart() {
1683         // Run the default commands.
1684         super.onRestart();
1685
1686         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1687         if (proxyThroughOrbot) {
1688             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1689             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1690
1691             // Send the intent to the Orbot package.
1692             orbotIntent.setPackage("org.torproject.android");
1693
1694             // Make it so.
1695             sendBroadcast(orbotIntent);
1696         }
1697
1698         // Apply the app settings if returning from the Settings activity..
1699         if (reapplyAppSettingsOnRestart) {
1700             // Apply the app settings.
1701             applyAppSettings();
1702
1703             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1704             if (reloadOnRestart) {
1705                 // Reload `mainWebView`.
1706                 mainWebView.reload();
1707
1708                 // Reset `reloadOnRestartBoolean`.
1709                 reloadOnRestart = false;
1710             }
1711
1712             // Reset the return from settings flag.
1713             reapplyAppSettingsOnRestart = false;
1714         }
1715
1716         // Apply the domain settings if returning from the Domains activity.
1717         if (reapplyDomainSettingsOnRestart) {
1718             // Reapply the domain settings.
1719             applyDomainSettings(formattedUrlString, false, true);
1720
1721             // Reset `reapplyDomainSettingsOnRestart`.
1722             reapplyDomainSettingsOnRestart = false;
1723         }
1724
1725         // Load the URL on restart to apply changes to night mode.
1726         if (loadUrlOnRestart) {
1727             // Load the current `formattedUrlString`.
1728             loadUrl(formattedUrlString);
1729
1730             // Reset `loadUrlOnRestart.
1731             loadUrlOnRestart = false;
1732         }
1733
1734         // Update the bookmarks drawer if returning from the Bookmarks activity.
1735         if (restartFromBookmarksActivity) {
1736             // Close the bookmarks drawer.
1737             drawerLayout.closeDrawer(GravityCompat.END);
1738
1739             // Reload the bookmarks drawer.
1740             loadBookmarksFolder();
1741
1742             // Reset `restartFromBookmarksActivity`.
1743             restartFromBookmarksActivity = false;
1744         }
1745
1746         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1747         updatePrivacyIcons(true);
1748     }
1749
1750     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1751     @Override
1752     public void onResume() {
1753         // Run the default commands.
1754         super.onResume();
1755
1756         // Resume JavaScript (if enabled).
1757         mainWebView.resumeTimers();
1758
1759         // Resume `mainWebView`.
1760         mainWebView.onResume();
1761
1762         // Resume the adView for the free flavor.
1763         if (BuildConfig.FLAVOR.contentEquals("free")) {
1764             // Resume the ad.
1765             AdHelper.resumeAd(findViewById(R.id.adview));
1766         }
1767
1768         // Display a message to the user if waiting for Orbot.
1769         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1770             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1771             mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1772         }
1773
1774         if (displayingFullScreenVideo) {
1775             // Remove the translucent overlays.
1776             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1777
1778             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1779             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1780
1781             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1782              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1783              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1784              */
1785             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1786         }
1787     }
1788
1789     @Override
1790     public void onPause() {
1791         super.onPause();
1792
1793         // Pause `mainWebView`.
1794         mainWebView.onPause();
1795
1796         // Stop all JavaScript.
1797         mainWebView.pauseTimers();
1798
1799         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1800         if (BuildConfig.FLAVOR.contentEquals("free")) {
1801             // Pause the ad.
1802             AdHelper.pauseAd(findViewById(R.id.adview));
1803         }
1804     }
1805
1806     @Override
1807     public boolean onCreateOptionsMenu(Menu menu) {
1808         // Inflate the menu; this adds items to the action bar if it is present.
1809         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1810
1811         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1812         mainMenu = menu;
1813
1814         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1815         updatePrivacyIcons(false);
1816
1817         // Get handles for the menu items.
1818         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1819         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1820         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1821         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1822         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1823         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1824         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1825
1826         // Only display third-party cookies if API >= 21
1827         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1828
1829         // Only display the form data menu items if the API < 26.
1830         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1831         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1832
1833         // Only show Ad Consent if this is the free flavor.
1834         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1835
1836         // Get the shared preference values.  `this` references the current context.
1837         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1838
1839         // 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.
1840         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1841             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1842             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1843             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1844         } else { //Do not display the additional icons.
1845             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1846             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1847             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1848         }
1849
1850         return true;
1851     }
1852
1853     @Override
1854     public boolean onPrepareOptionsMenu(Menu menu) {
1855         // Get handles for the menu items.
1856         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1857         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1858         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1859         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1860         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1861         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1862         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1863         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1864         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1865         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1866         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1867         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1868         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1869         MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1870         MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1871         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1872         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1873         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1874
1875         // Set the text for the domain menu item.
1876         if (domainSettingsApplied) {
1877             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1878         } else {
1879             addOrEditDomain.setTitle(R.string.add_domain_settings);
1880         }
1881
1882         // Set the status of the menu item checkboxes.
1883         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1884         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1885         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1886         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1887         easyListMenuItem.setChecked(easyListEnabled);
1888         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1889         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1890         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1891         ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1892         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1893         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1894         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1895
1896         // Enable third-party cookies if first-party cookies are enabled.
1897         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1898
1899         // Enable DOM Storage if JavaScript is enabled.
1900         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1901
1902         // Enable Clear Cookies if there are any.
1903         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1904
1905         // Get a count of the number of files in the Local Storage directory.
1906         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1907         int localStorageDirectoryNumberOfFiles = 0;
1908         if (localStorageDirectory.exists()) {
1909             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1910         }
1911
1912         // Get a count of the number of files in the IndexedDB directory.
1913         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1914         int indexedDBDirectoryNumberOfFiles = 0;
1915         if (indexedDBDirectory.exists()) {
1916             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1917         }
1918
1919         // Enable Clear DOM Storage if there is any.
1920         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1921
1922         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1923         if (Build.VERSION.SDK_INT < 26) {
1924             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1925             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1926         }
1927
1928         // Enable Clear Data if any of the submenu items are enabled.
1929         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1930
1931         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1932         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1933
1934         // Initialize font size variables.
1935         int fontSize = mainWebView.getSettings().getTextZoom();
1936         String fontSizeTitle;
1937         MenuItem selectedFontSizeMenuItem;
1938
1939         // Prepare the font size title and current size menu item.
1940         switch (fontSize) {
1941             case 25:
1942                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1943                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1944                 break;
1945
1946             case 50:
1947                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1948                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1949                 break;
1950
1951             case 75:
1952                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1953                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1954                 break;
1955
1956             case 100:
1957                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1958                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1959                 break;
1960
1961             case 125:
1962                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1963                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1964                 break;
1965
1966             case 150:
1967                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1968                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1969                 break;
1970
1971             case 175:
1972                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1973                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1974                 break;
1975
1976             case 200:
1977                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1978                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1979                 break;
1980
1981             default:
1982                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1983                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1984                 break;
1985         }
1986
1987         // Set the font size title and select the current size menu item.
1988         fontSizeMenuItem.setTitle(fontSizeTitle);
1989         selectedFontSizeMenuItem.setChecked(true);
1990
1991         // Run all the other default commands.
1992         super.onPrepareOptionsMenu(menu);
1993
1994         // Display the menu.
1995         return true;
1996     }
1997
1998     @Override
1999     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2000     @SuppressLint("SetJavaScriptEnabled")
2001     // removeAllCookies is deprecated, but it is required for API < 21.
2002     @SuppressWarnings("deprecation")
2003     public boolean onOptionsItemSelected(MenuItem menuItem) {
2004         // Get the selected menu item ID.
2005         int menuItemId = menuItem.getItemId();
2006
2007         // Set the commands that relate to the menu entries.
2008         switch (menuItemId) {
2009             case R.id.toggle_javascript:
2010                 // Switch the status of javaScriptEnabled.
2011                 javaScriptEnabled = !javaScriptEnabled;
2012
2013                 // Apply the new JavaScript status.
2014                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2015
2016                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2017                 updatePrivacyIcons(true);
2018
2019                 // Display a `Snackbar`.
2020                 if (javaScriptEnabled) {  // JavaScrip is enabled.
2021                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2022                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
2023                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2024                 } else {  // Privacy mode.
2025                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2026                 }
2027
2028                 // Reload the WebView.
2029                 mainWebView.reload();
2030                 return true;
2031
2032             case R.id.add_or_edit_domain:
2033                 if (domainSettingsApplied) {  // Edit the current domain settings.
2034                     // Reapply the domain settings on returning to `MainWebViewActivity`.
2035                     reapplyDomainSettingsOnRestart = true;
2036                     currentDomainName = "";
2037
2038                     // Create an intent to launch the domains activity.
2039                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2040
2041                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2042                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2043                     domainsIntent.putExtra("closeOnBack", true);
2044
2045                     // Make it so.
2046                     startActivity(domainsIntent);
2047                 } else {  // Add a new domain.
2048                     // Apply the new domain settings on returning to `MainWebViewActivity`.
2049                     reapplyDomainSettingsOnRestart = true;
2050                     currentDomainName = "";
2051
2052                     // Get the current domain
2053                     Uri currentUri = Uri.parse(formattedUrlString);
2054                     String currentDomain = currentUri.getHost();
2055
2056                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2057                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2058
2059                     // Create the domain and store the database ID.
2060                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2061
2062                     // Create an intent to launch the domains activity.
2063                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2064
2065                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2066                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2067                     domainsIntent.putExtra("closeOnBack", true);
2068
2069                     // Make it so.
2070                     startActivity(domainsIntent);
2071                 }
2072                 return true;
2073
2074             case R.id.toggle_first_party_cookies:
2075                 // Switch the status of firstPartyCookiesEnabled.
2076                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2077
2078                 // Update the menu checkbox.
2079                 menuItem.setChecked(firstPartyCookiesEnabled);
2080
2081                 // Apply the new cookie status.
2082                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2083
2084                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2085                 updatePrivacyIcons(true);
2086
2087                 // Display a `Snackbar`.
2088                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2089                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2090                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
2091                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2092                 } else {  // Privacy mode.
2093                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2094                 }
2095
2096                 // Reload the WebView.
2097                 mainWebView.reload();
2098                 return true;
2099
2100             case R.id.toggle_third_party_cookies:
2101                 if (Build.VERSION.SDK_INT >= 21) {
2102                     // Switch the status of thirdPartyCookiesEnabled.
2103                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2104
2105                     // Update the menu checkbox.
2106                     menuItem.setChecked(thirdPartyCookiesEnabled);
2107
2108                     // Apply the new cookie status.
2109                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2110
2111                     // Display a `Snackbar`.
2112                     if (thirdPartyCookiesEnabled) {
2113                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2114                     } else {
2115                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2116                     }
2117
2118                     // Reload the WebView.
2119                     mainWebView.reload();
2120                 } // Else do nothing because SDK < 21.
2121                 return true;
2122
2123             case R.id.toggle_dom_storage:
2124                 // Switch the status of domStorageEnabled.
2125                 domStorageEnabled = !domStorageEnabled;
2126
2127                 // Update the menu checkbox.
2128                 menuItem.setChecked(domStorageEnabled);
2129
2130                 // Apply the new DOM Storage status.
2131                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2132
2133                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2134                 updatePrivacyIcons(true);
2135
2136                 // Display a `Snackbar`.
2137                 if (domStorageEnabled) {
2138                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2139                 } else {
2140                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2141                 }
2142
2143                 // Reload the WebView.
2144                 mainWebView.reload();
2145                 return true;
2146
2147             // Form data can be removed once the minimum API >= 26.
2148             case R.id.toggle_save_form_data:
2149                 // Switch the status of saveFormDataEnabled.
2150                 saveFormDataEnabled = !saveFormDataEnabled;
2151
2152                 // Update the menu checkbox.
2153                 menuItem.setChecked(saveFormDataEnabled);
2154
2155                 // Apply the new form data status.
2156                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2157
2158                 // Display a `Snackbar`.
2159                 if (saveFormDataEnabled) {
2160                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2161                 } else {
2162                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2163                 }
2164
2165                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2166                 updatePrivacyIcons(true);
2167
2168                 // Reload the WebView.
2169                 mainWebView.reload();
2170                 return true;
2171
2172             case R.id.clear_cookies:
2173                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2174                         .setAction(R.string.undo, v -> {
2175                             // Do nothing because everything will be handled by `onDismissed()` below.
2176                         })
2177                         .addCallback(new Snackbar.Callback() {
2178                             @Override
2179                             public void onDismissed(Snackbar snackbar, int event) {
2180                                 switch (event) {
2181                                     // The user pushed the `Undo` button.
2182                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2183                                         // Do nothing.
2184                                         break;
2185
2186                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2187                                     default:
2188                                         // `cookieManager.removeAllCookie()` varies by SDK.
2189                                         if (Build.VERSION.SDK_INT < 21) {
2190                                             cookieManager.removeAllCookie();
2191                                         } else {
2192                                             // `null` indicates no callback.
2193                                             cookieManager.removeAllCookies(null);
2194                                         }
2195                                 }
2196                             }
2197                         })
2198                         .show();
2199                 return true;
2200
2201             case R.id.clear_dom_storage:
2202                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2203                         .setAction(R.string.undo, v -> {
2204                             // Do nothing because everything will be handled by `onDismissed()` below.
2205                         })
2206                         .addCallback(new Snackbar.Callback() {
2207                             @Override
2208                             public void onDismissed(Snackbar snackbar, int event) {
2209                                 switch (event) {
2210                                     // The user pushed the `Undo` button.
2211                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2212                                         // Do nothing.
2213                                         break;
2214
2215                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2216                                     default:
2217                                         // Delete the DOM Storage.
2218                                         WebStorage webStorage = WebStorage.getInstance();
2219                                         webStorage.deleteAllData();
2220
2221                                         // Manually delete the DOM storage files and directories.
2222                                         try {
2223                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2224                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2225
2226                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2227                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2228                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2229                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2230                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2231                                         } catch (IOException e) {
2232                                             // Do nothing if an error is thrown.
2233                                         }
2234                                 }
2235                             }
2236                         })
2237                         .show();
2238                 return true;
2239
2240             // Form data can be remove once the minimum API >= 26.
2241             case R.id.clear_form_data:
2242                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2243                         .setAction(R.string.undo, v -> {
2244                             // Do nothing because everything will be handled by `onDismissed()` below.
2245                         })
2246                         .addCallback(new Snackbar.Callback() {
2247                             @Override
2248                             public void onDismissed(Snackbar snackbar, int event) {
2249                                 switch (event) {
2250                                     // The user pushed the `Undo` button.
2251                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2252                                         // Do nothing.
2253                                         break;
2254
2255                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2256                                     default:
2257                                         // Delete the form data.
2258                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2259                                         mainWebViewDatabase.clearFormData();
2260                                 }
2261                             }
2262                         })
2263                         .show();
2264                 return true;
2265
2266             case R.id.font_size_twenty_five_percent:
2267                 mainWebView.getSettings().setTextZoom(25);
2268                 return true;
2269
2270             case R.id.font_size_fifty_percent:
2271                 mainWebView.getSettings().setTextZoom(50);
2272                 return true;
2273
2274             case R.id.font_size_seventy_five_percent:
2275                 mainWebView.getSettings().setTextZoom(75);
2276                 return true;
2277
2278             case R.id.font_size_one_hundred_percent:
2279                 mainWebView.getSettings().setTextZoom(100);
2280                 return true;
2281
2282             case R.id.font_size_one_hundred_twenty_five_percent:
2283                 mainWebView.getSettings().setTextZoom(125);
2284                 return true;
2285
2286             case R.id.font_size_one_hundred_fifty_percent:
2287                 mainWebView.getSettings().setTextZoom(150);
2288                 return true;
2289
2290             case R.id.font_size_one_hundred_seventy_five_percent:
2291                 mainWebView.getSettings().setTextZoom(175);
2292                 return true;
2293
2294             case R.id.font_size_two_hundred_percent:
2295                 mainWebView.getSettings().setTextZoom(200);
2296                 return true;
2297
2298             case R.id.swipe_to_refresh:
2299                 // Toggle swipe to refresh.
2300                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2301                 return true;
2302
2303             case R.id.display_images:
2304                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2305                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2306                     mainWebView.reload();
2307                 } else {  // Images are not currently loaded automatically.
2308                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2309                 }
2310
2311                 // Set `onTheFlyDisplayImagesSet`.
2312                 onTheFlyDisplayImagesSet = true;
2313                 return true;
2314
2315             case R.id.view_source:
2316                 // Launch the View Source activity.
2317                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2318                 startActivity(viewSourceIntent);
2319                 return true;
2320
2321             case R.id.easylist:
2322                 // Toggle the EasyList status.
2323                 easyListEnabled = !easyListEnabled;
2324
2325                 // Update the menu checkbox.
2326                 menuItem.setChecked(easyListEnabled);
2327
2328                 // Reload the main WebView.
2329                 mainWebView.reload();
2330                 return true;
2331
2332             case R.id.easyprivacy:
2333                 // Toggle the EasyPrivacy status.
2334                 easyPrivacyEnabled = !easyPrivacyEnabled;
2335
2336                 // Update the menu checkbox.
2337                 menuItem.setChecked(easyPrivacyEnabled);
2338
2339                 // Reload the main WebView.
2340                 mainWebView.reload();
2341                 return true;
2342
2343             case R.id.fanboys_annoyance_list:
2344                 // Toggle Fanboy's Annoyance List status.
2345                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2346
2347                 // Update the menu checkbox.
2348                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2349
2350                 // Update the staus of Fanboy's Social Blocking List.
2351                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2352                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2353
2354                 // Reload the main WebView.
2355                 mainWebView.reload();
2356                 return true;
2357
2358             case R.id.fanboys_social_blocking_list:
2359                 // Toggle Fanboy's Social Blocking List status.
2360                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2361
2362                 // Update the menu checkbox.
2363                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2364
2365                 // Reload the main WebView.
2366                 mainWebView.reload();
2367                 return true;
2368
2369             case R.id.ultraprivacy:
2370                 // Toggle the UltraPrivacy status.
2371                 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2372
2373                 // Update the menu checkbox.
2374                 menuItem.setChecked(ultraPrivacyEnabled);
2375
2376                 // Reload the main WebView.
2377                 mainWebView.reload();
2378                 return true;
2379
2380             case R.id.block_all_third_party_requests:
2381                 //Toggle the third-party requests blocker status.
2382                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2383
2384                 // Update the menu checkbox.
2385                 menuItem.setChecked(blockAllThirdPartyRequests);
2386
2387                 // Reload the main WebView.
2388                 mainWebView.reload();
2389                 return true;
2390
2391             case R.id.share:
2392                 // Setup the share string.
2393                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2394
2395                 // Create the share intent.
2396                 Intent shareIntent = new Intent();
2397                 shareIntent.setAction(Intent.ACTION_SEND);
2398                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2399                 shareIntent.setType("text/plain");
2400
2401                 // Make it so.
2402                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2403                 return true;
2404
2405             case R.id.find_on_page:
2406                 // Hide the URL app bar.
2407                 supportAppBar.setVisibility(View.GONE);
2408
2409                 // Show the Find on Page `RelativeLayout`.
2410                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2411
2412                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2413                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2414                 findOnPageEditText.postDelayed(() -> {
2415                     // Set the focus on `findOnPageEditText`.
2416                     findOnPageEditText.requestFocus();
2417
2418                     // Display the keyboard.  `0` sets no input flags.
2419                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2420                 }, 200);
2421                 return true;
2422
2423             case R.id.print:
2424                 // Get a `PrintManager` instance.
2425                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2426
2427                 // Convert `mainWebView` to `printDocumentAdapter`.
2428                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2429
2430                 // Remove the lint error below that `printManager` might be `null`.
2431                 assert printManager != null;
2432
2433                 // Print the document.  The print attributes are `null`.
2434                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2435                 return true;
2436
2437             case R.id.add_to_homescreen:
2438                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2439                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2440                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2441
2442                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2443                 return true;
2444
2445             case R.id.refresh:
2446                 mainWebView.reload();
2447                 return true;
2448
2449             case R.id.ad_consent:
2450                 // Display the ad consent dialog.
2451                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2452                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2453                 return true;
2454
2455             default:
2456                 // Don't consume the event.
2457                 return super.onOptionsItemSelected(menuItem);
2458         }
2459     }
2460
2461     // removeAllCookies is deprecated, but it is required for API < 21.
2462     @SuppressWarnings("deprecation")
2463     @Override
2464     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2465         int menuItemId = menuItem.getItemId();
2466
2467         switch (menuItemId) {
2468             case R.id.home:
2469                 loadUrl(homepage);
2470                 break;
2471
2472             case R.id.back:
2473                 if (mainWebView.canGoBack()) {
2474                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2475                     formattedUrlString = "";
2476
2477                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2478                     navigatingHistory = true;
2479
2480                     // Load the previous website in the history.
2481                     mainWebView.goBack();
2482                 }
2483                 break;
2484
2485             case R.id.forward:
2486                 if (mainWebView.canGoForward()) {
2487                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2488                     formattedUrlString = "";
2489
2490                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2491                     navigatingHistory = true;
2492
2493                     // Load the next website in the history.
2494                     mainWebView.goForward();
2495                 }
2496                 break;
2497
2498             case R.id.history:
2499                 // Get the `WebBackForwardList`.
2500                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2501
2502                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2503                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2504                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2505                 break;
2506
2507             case R.id.requests:
2508                 // Launch the requests activity.
2509                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2510                 startActivity(requestsIntent);
2511                 break;
2512
2513             case R.id.downloads:
2514                 // Launch the system Download Manager.
2515                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2516
2517                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2518                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2519
2520                 startActivity(downloadManagerIntent);
2521                 break;
2522
2523             case R.id.domains:
2524                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2525                 reapplyDomainSettingsOnRestart = true;
2526                 currentDomainName = "";
2527
2528                 // Launch the domains activity.
2529                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2530                 startActivity(domainsIntent);
2531                 break;
2532
2533             case R.id.settings:
2534                 // Set the flag to reapply app settings on restart when returning from Settings.
2535                 reapplyAppSettingsOnRestart = true;
2536
2537                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2538                 reapplyDomainSettingsOnRestart = true;
2539                 currentDomainName = "";
2540
2541                 // Launch the settings activity.
2542                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2543                 startActivity(settingsIntent);
2544                 break;
2545
2546             case R.id.guide:
2547                 // Launch `GuideActivity`.
2548                 Intent guideIntent = new Intent(this, GuideActivity.class);
2549                 startActivity(guideIntent);
2550                 break;
2551
2552             case R.id.about:
2553                 // Launch `AboutActivity`.
2554                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2555                 startActivity(aboutIntent);
2556                 break;
2557
2558             case R.id.clearAndExit:
2559                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2560                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2561
2562                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2563
2564                 // Clear cookies.
2565                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2566                     // The command to remove cookies changed slightly in API 21.
2567                     if (Build.VERSION.SDK_INT >= 21) {
2568                         cookieManager.removeAllCookies(null);
2569                     } else {
2570                         cookieManager.removeAllCookie();
2571                     }
2572
2573                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2574                     try {
2575                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2576                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2577                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2578                     } catch (IOException e) {
2579                         // Do nothing if an error is thrown.
2580                     }
2581                 }
2582
2583                 // Clear DOM storage.
2584                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2585                     // Ask `WebStorage` to clear the DOM storage.
2586                     WebStorage webStorage = WebStorage.getInstance();
2587                     webStorage.deleteAllData();
2588
2589                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2590                     try {
2591                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2592                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2593
2594                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2595                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2596                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2597                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2598                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2599                     } catch (IOException e) {
2600                         // Do nothing if an error is thrown.
2601                     }
2602                 }
2603
2604                 // Clear form data if the API < 26.
2605                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2606                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2607                     webViewDatabase.clearFormData();
2608
2609                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2610                     try {
2611                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2612                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2613                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2614                     } catch (IOException e) {
2615                         // Do nothing if an error is thrown.
2616                     }
2617                 }
2618
2619                 // Clear the cache.
2620                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2621                     // `true` includes disk files.
2622                     mainWebView.clearCache(true);
2623
2624                     // Manually delete the cache directories.
2625                     try {
2626                         // Delete the main cache directory.
2627                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2628
2629                         // Delete the secondary `Service Worker` cache directory.
2630                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2631                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2632                     } catch (IOException e) {
2633                         // Do nothing if an error is thrown.
2634                     }
2635                 }
2636
2637                 // Clear SSL certificate preferences.
2638                 mainWebView.clearSslPreferences();
2639
2640                 // Clear the back/forward history.
2641                 mainWebView.clearHistory();
2642
2643                 // Clear `formattedUrlString`.
2644                 formattedUrlString = null;
2645
2646                 // Clear `customHeaders`.
2647                 customHeaders.clear();
2648
2649                 // Detach all views from `mainWebViewRelativeLayout`.
2650                 mainWebViewRelativeLayout.removeAllViews();
2651
2652                 // Destroy the internal state of `mainWebView`.
2653                 mainWebView.destroy();
2654
2655                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2656                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2657                 if (clearEverything) {
2658                     try {
2659                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2660                     } catch (IOException e) {
2661                         // Do nothing if an error is thrown.
2662                     }
2663                 }
2664
2665                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2666                 if (Build.VERSION.SDK_INT >= 21) {
2667                     finishAndRemoveTask();
2668                 } else {
2669                     finish();
2670                 }
2671
2672                 // Remove the terminated program from RAM.  The status code is `0`.
2673                 System.exit(0);
2674                 break;
2675         }
2676
2677         // Close the navigation drawer.
2678         drawerLayout.closeDrawer(GravityCompat.START);
2679         return true;
2680     }
2681
2682     @Override
2683     public void onPostCreate(Bundle savedInstanceState) {
2684         super.onPostCreate(savedInstanceState);
2685
2686         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2687         drawerToggle.syncState();
2688     }
2689
2690     @Override
2691     public void onConfigurationChanged(Configuration newConfig) {
2692         super.onConfigurationChanged(newConfig);
2693
2694         // Reload the ad for the free flavor if we not in full screen mode.
2695         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2696             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2697             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2698         }
2699
2700         // `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:
2701         // https://code.google.com/p/android/issues/detail?id=20493#c8
2702         // ActivityCompat.invalidateOptionsMenu(this);
2703     }
2704
2705     @Override
2706     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2707         // Store the `HitTestResult`.
2708         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2709
2710         // Create strings.
2711         final String imageUrl;
2712         final String linkUrl;
2713
2714         // Get a handle for the `ClipboardManager`.
2715         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2716
2717         // Remove the lint errors below that `clipboardManager` might be `null`.
2718         assert clipboardManager != null;
2719
2720         switch (hitTestResult.getType()) {
2721             // `SRC_ANCHOR_TYPE` is a link.
2722             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2723                 // Get the target URL.
2724                 linkUrl = hitTestResult.getExtra();
2725
2726                 // Set the target URL as the title of the `ContextMenu`.
2727                 menu.setHeaderTitle(linkUrl);
2728
2729                 // Add a Load URL entry.
2730                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2731                     loadUrl(linkUrl);
2732                     return false;
2733                 });
2734
2735                 // Add a Copy URL entry.
2736                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2737                     // Save the link URL in a `ClipData`.
2738                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2739
2740                     // Set the `ClipData` as the clipboard's primary clip.
2741                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2742                     return false;
2743                 });
2744
2745                 // Add a Download URL entry.
2746                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2747                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2748                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2749                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2750
2751                         // Store the variables for future use by `onRequestPermissionsResult()`.
2752                         downloadUrl = linkUrl;
2753                         downloadContentDisposition = "none";
2754                         downloadContentLength = -1;
2755
2756                         // Show a dialog if the user has previously denied the permission.
2757                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2758                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2759                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2760
2761                             // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2762                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2763                         } else {  // Show the permission request directly.
2764                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2765                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2766                         }
2767                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2768                         // Get a handle for the download file alert dialog.
2769                         AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2770
2771                         // Show the download file alert dialog.
2772                         downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2773                     }
2774                     return false;
2775                 });
2776
2777                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2778                 menu.add(R.string.cancel);
2779                 break;
2780
2781             case WebView.HitTestResult.EMAIL_TYPE:
2782                 // Get the target URL.
2783                 linkUrl = hitTestResult.getExtra();
2784
2785                 // Set the target URL as the title of the `ContextMenu`.
2786                 menu.setHeaderTitle(linkUrl);
2787
2788                 // Add a `Write Email` entry.
2789                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2790                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2791                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2792
2793                     // Parse the url and set it as the data for the `Intent`.
2794                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2795
2796                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2797                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2798
2799                     // Make it so.
2800                     startActivity(emailIntent);
2801                     return false;
2802                 });
2803
2804                 // Add a `Copy Email Address` entry.
2805                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2806                     // Save the email address in a `ClipData`.
2807                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2808
2809                     // Set the `ClipData` as the clipboard's primary clip.
2810                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2811                     return false;
2812                 });
2813
2814                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2815                 menu.add(R.string.cancel);
2816                 break;
2817
2818             // `IMAGE_TYPE` is an image.
2819             case WebView.HitTestResult.IMAGE_TYPE:
2820                 // Get the image URL.
2821                 imageUrl = hitTestResult.getExtra();
2822
2823                 // Set the image URL as the title of the `ContextMenu`.
2824                 menu.setHeaderTitle(imageUrl);
2825
2826                 // Add a `View Image` entry.
2827                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2828                     loadUrl(imageUrl);
2829                     return false;
2830                 });
2831
2832                 // Add a `Download Image` entry.
2833                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2834                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2835                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2836                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2837
2838                         // Store the image URL for use by `onRequestPermissionResult()`.
2839                         downloadImageUrl = imageUrl;
2840
2841                         // Show a dialog if the user has previously denied the permission.
2842                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2843                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2844                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2845
2846                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2847                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2848                         } else {  // Show the permission request directly.
2849                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2850                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2851                         }
2852                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2853                         // Get a handle for the download image alert dialog.
2854                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2855
2856                         // Show the download image alert dialog.
2857                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2858                     }
2859                     return false;
2860                 });
2861
2862                 // Add a `Copy URL` entry.
2863                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2864                     // Save the image URL in a `ClipData`.
2865                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2866
2867                     // Set the `ClipData` as the clipboard's primary clip.
2868                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
2869                     return false;
2870                 });
2871
2872                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2873                 menu.add(R.string.cancel);
2874                 break;
2875
2876
2877             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2878             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2879                 // Get the image URL.
2880                 imageUrl = hitTestResult.getExtra();
2881
2882                 // Set the image URL as the title of the `ContextMenu`.
2883                 menu.setHeaderTitle(imageUrl);
2884
2885                 // Add a `View Image` entry.
2886                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2887                     loadUrl(imageUrl);
2888                     return false;
2889                 });
2890
2891                 // Add a `Download Image` entry.
2892                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2893                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2894                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2895                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2896
2897                         // Store the image URL for use by `onRequestPermissionResult()`.
2898                         downloadImageUrl = imageUrl;
2899
2900                         // Show a dialog if the user has previously denied the permission.
2901                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2902                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2903                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2904
2905                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2906                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2907                         } else {  // Show the permission request directly.
2908                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2909                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2910                         }
2911                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2912                         // Get a handle for the download image alert dialog.
2913                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2914
2915                         // Show the download image alert dialog.
2916                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2917                     }
2918                     return false;
2919                 });
2920
2921                 // Add a `Copy URL` entry.
2922                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2923                     // Save the image URL in a `ClipData`.
2924                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2925
2926                     // Set the `ClipData` as the clipboard's primary clip.
2927                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2928                     return false;
2929                 });
2930
2931                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2932                 menu.add(R.string.cancel);
2933                 break;
2934         }
2935     }
2936
2937     @Override
2938     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2939         // Get the `EditTexts` from the `dialogFragment`.
2940         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2941         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2942
2943         // Extract the strings from the `EditTexts`.
2944         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2945         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2946
2947         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2948         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2949         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2950         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2951
2952         // Display the new bookmark below the current items in the (0 indexed) list.
2953         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2954
2955         // Create the bookmark.
2956         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2957
2958         // Update `bookmarksCursor` with the current contents of this folder.
2959         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2960
2961         // Update the `ListView`.
2962         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2963
2964         // Scroll to the new bookmark.
2965         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2966     }
2967
2968     @Override
2969     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2970         // Get handles for the views in `dialogFragment`.
2971         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2972         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2973         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2974
2975         // Get new folder name string.
2976         String folderNameString = createFolderNameEditText.getText().toString();
2977
2978         // Get the new folder icon `Bitmap`.
2979         Bitmap folderIconBitmap;
2980         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2981             // Get the default folder icon and convert it to a `Bitmap`.
2982             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2983             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2984             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2985         } else {  // Use the `WebView` favorite icon.
2986             folderIconBitmap = favoriteIconBitmap;
2987         }
2988
2989         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2990         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2991         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2992         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2993
2994         // Move all the bookmarks down one in the display order.
2995         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2996             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2997             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2998         }
2999
3000         // Create the folder, which will be placed at the top of the `ListView`.
3001         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3002
3003         // Update `bookmarksCursor` with the current contents of this folder.
3004         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3005
3006         // Update the `ListView`.
3007         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3008
3009         // Scroll to the new folder.
3010         bookmarksListView.setSelection(0);
3011     }
3012
3013     @Override
3014     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3015         // Get the shortcut name.
3016         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3017         String shortcutNameString = shortcutNameEditText.getText().toString();
3018
3019         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
3020         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3021
3022         // Setup the shortcut intent.
3023         Intent shortcutIntent = new Intent();
3024         shortcutIntent.setAction(Intent.ACTION_VIEW);
3025         shortcutIntent.setData(Uri.parse(formattedUrlString));
3026
3027         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
3028         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3029
3030         // Add the required fields to the shortcut info builder.
3031         shortcutInfoBuilder.setIcon(favoriteIcon);
3032         shortcutInfoBuilder.setIntent(shortcutIntent);
3033         shortcutInfoBuilder.setShortLabel(shortcutNameString);
3034
3035         // Request the pin.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3036         ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3037     }
3038
3039     @Override
3040     public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3041         switch (downloadType) {
3042             case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3043                 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3044                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3045                 break;
3046
3047             case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3048                 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3049                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3050                 break;
3051         }
3052     }
3053
3054     @Override
3055     public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3056         switch (requestCode) {
3057             case DOWNLOAD_FILE_REQUEST_CODE:
3058                 // Show the download file alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
3059                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3060
3061                 // On API 23, displaying the fragment must be delayed or the app will crash.
3062                 if (Build.VERSION.SDK_INT == 23) {
3063                     new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3064                 } else {
3065                     downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3066                 }
3067
3068                 // Reset the download variables.
3069                 downloadUrl = "";
3070                 downloadContentDisposition = "";
3071                 downloadContentLength = 0;
3072                 break;
3073
3074             case DOWNLOAD_IMAGE_REQUEST_CODE:
3075                 // Show the download image alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
3076                 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3077
3078                 // On API 23, displaying the fragment must be delayed or the app will crash.
3079                 if (Build.VERSION.SDK_INT == 23) {
3080                     new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3081                 } else {
3082                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3083                 }
3084
3085                 // Reset the image URL variable.
3086                 downloadImageUrl = "";
3087                 break;
3088         }
3089     }
3090
3091     @Override
3092     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3093         // Download the image if it has an HTTP or HTTPS URI.
3094         if (imageUrl.startsWith("http")) {
3095             // Get a handle for the system `DOWNLOAD_SERVICE`.
3096             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3097
3098             // Parse `imageUrl`.
3099             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3100
3101             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
3102             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3103             if (firstPartyCookiesEnabled) {
3104                 // Get the cookies for `imageUrl`.
3105                 String cookies = cookieManager.getCookie(imageUrl);
3106
3107                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3108                 downloadRequest.addRequestHeader("Cookie", cookies);
3109             }
3110
3111             // Get the file name from the dialog fragment.
3112             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3113             String imageName = downloadImageNameEditText.getText().toString();
3114
3115             // Specify the download location.
3116             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3117                 // Download to the public download directory.
3118                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3119             } else {  // External write permission denied.
3120                 // Download to the app's external download directory.
3121                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3122             }
3123
3124             // Allow `MediaScanner` to index the download if it is a media file.
3125             downloadRequest.allowScanningByMediaScanner();
3126
3127             // Add the URL as the description for the download.
3128             downloadRequest.setDescription(imageUrl);
3129
3130             // Show the download notification after the download is completed.
3131             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3132
3133             // Remove the lint warning below that `downloadManager` might be `null`.
3134             assert downloadManager != null;
3135
3136             // Initiate the download.
3137             downloadManager.enqueue(downloadRequest);
3138         } else {  // The image is not an HTTP or HTTPS URI.
3139             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3140         }
3141     }
3142
3143     @Override
3144     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3145         // Download the file if it has an HTTP or HTTPS URI.
3146         if (downloadUrl.startsWith("http")) {
3147             // Get a handle for the system `DOWNLOAD_SERVICE`.
3148             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3149
3150             // Parse `downloadUrl`.
3151             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3152
3153             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
3154             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3155             if (firstPartyCookiesEnabled) {
3156                 // Get the cookies for `downloadUrl`.
3157                 String cookies = cookieManager.getCookie(downloadUrl);
3158
3159                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3160                 downloadRequest.addRequestHeader("Cookie", cookies);
3161             }
3162
3163             // Get the file name from the dialog fragment.
3164             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3165             String fileName = downloadFileNameEditText.getText().toString();
3166
3167             // Specify the download location.
3168             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3169                 // Download to the public download directory.
3170                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3171             } else {  // External write permission denied.
3172                 // Download to the app's external download directory.
3173                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3174             }
3175
3176             // Allow `MediaScanner` to index the download if it is a media file.
3177             downloadRequest.allowScanningByMediaScanner();
3178
3179             // Add the URL as the description for the download.
3180             downloadRequest.setDescription(downloadUrl);
3181
3182             // Show the download notification after the download is completed.
3183             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3184
3185             // Remove the lint warning below that `downloadManager` might be `null`.
3186             assert downloadManager != null;
3187
3188             // Initiate the download.
3189             downloadManager.enqueue(downloadRequest);
3190         } else {  // The download is not an HTTP or HTTPS URI.
3191             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3192         }
3193     }
3194
3195     @Override
3196     public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3197         // Get handles for the views from `dialogFragment`.
3198         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3199         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3200         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3201
3202         // Store the bookmark strings.
3203         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3204         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3205
3206         // Update the bookmark.
3207         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
3208             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3209         } else {  // Update the bookmark using the `WebView` favorite icon.
3210             // Convert the favorite icon to a byte array.  `0` is for lossless compression (the only option for a PNG).
3211             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3212             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3213             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3214
3215             //  Update the bookmark and the favorite icon.
3216             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3217         }
3218
3219         // Update `bookmarksCursor` with the current contents of this folder.
3220         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3221
3222         // Update the `ListView`.
3223         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3224     }
3225
3226     @Override
3227     public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3228         // Get handles for the views from `dialogFragment`.
3229         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3230         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3231         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3232         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3233
3234         // Get the new folder name.
3235         String newFolderNameString = editFolderNameEditText.getText().toString();
3236
3237         // Check if the favorite icon has changed.
3238         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
3239             // Update the name in the database.
3240             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3241         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
3242             // Get the new folder icon `Bitmap`.
3243             Bitmap folderIconBitmap;
3244             if (defaultFolderIconRadioButton.isChecked()) {
3245                 // Get the default folder icon and convert it to a `Bitmap`.
3246                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3247                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3248                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3249             } else {  // Use the `WebView` favorite icon.
3250                 folderIconBitmap = favoriteIconBitmap;
3251             }
3252
3253             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3254             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3255             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3256             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3257
3258             // Update the folder icon in the database.
3259             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3260         } else {  // The folder icon and the name have changed.
3261             // Get the new folder icon `Bitmap`.
3262             Bitmap folderIconBitmap;
3263             if (defaultFolderIconRadioButton.isChecked()) {
3264                 // Get the default folder icon and convert it to a `Bitmap`.
3265                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3266                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3267                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3268             } else {  // Use the `WebView` favorite icon.
3269                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3270             }
3271
3272             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3273             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3274             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3275             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3276
3277             // Update the folder name and icon in the database.
3278             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3279         }
3280
3281         // Update `bookmarksCursor` with the current contents of this folder.
3282         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3283
3284         // Update the `ListView`.
3285         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3286     }
3287
3288     @Override
3289     public void onHttpAuthenticationCancel() {
3290         // Cancel the `HttpAuthHandler`.
3291         httpAuthHandler.cancel();
3292     }
3293
3294     @Override
3295     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3296         // Get handles for the `EditTexts`.
3297         EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3298         EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3299
3300         // Proceed with the HTTP authentication.
3301         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3302     }
3303
3304     public void viewSslCertificate(View view) {
3305         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3306         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3307         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3308     }
3309
3310     @Override
3311     public void onSslErrorCancel() {
3312         sslErrorHandler.cancel();
3313     }
3314
3315     @Override
3316     public void onSslErrorProceed() {
3317         sslErrorHandler.proceed();
3318     }
3319
3320     @Override
3321     public void onSslMismatchBack() {
3322         if (mainWebView.canGoBack()) {  // There is a back page in the history.
3323             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3324             formattedUrlString = "";
3325
3326             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3327             navigatingHistory = true;
3328
3329             // Go back.
3330             mainWebView.goBack();
3331         } else {  // There are no pages to go back to.
3332             // Load a blank page
3333             loadUrl("");
3334         }
3335     }
3336
3337     @Override
3338     public void onSslMismatchProceed() {
3339         // Do not check the pinned SSL certificate for this domain again until the domain changes.
3340         ignorePinnedSslCertificate = true;
3341     }
3342
3343     @Override
3344     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3345         // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3346         formattedUrlString = "";
3347
3348         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3349         navigatingHistory = true;
3350
3351         // Load the history entry.
3352         mainWebView.goBackOrForward(moveBackOrForwardSteps);
3353     }
3354
3355     @Override
3356     public void onClearHistory() {
3357         // Clear the history.
3358         mainWebView.clearHistory();
3359     }
3360
3361     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3362     @Override
3363     public void onBackPressed() {
3364         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
3365             // Close the navigation drawer.
3366             drawerLayout.closeDrawer(GravityCompat.START);
3367         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
3368             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
3369                 // close the bookmarks drawer.
3370                 drawerLayout.closeDrawer(GravityCompat.END);
3371             } else {  // A subfolder is displayed.
3372                 // Place the former parent folder in `currentFolder`.
3373                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3374
3375                 // Load the new folder.
3376                 loadBookmarksFolder();
3377             }
3378
3379         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
3380             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3381             formattedUrlString = "";
3382
3383             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3384             navigatingHistory = true;
3385
3386             // Go back.
3387             mainWebView.goBack();
3388         } else {  // There isn't anything to do in Privacy Browser.
3389             // Pass `onBackPressed()` to the system.
3390             super.onBackPressed();
3391         }
3392     }
3393
3394     // 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.
3395     @Override
3396     public void onActivityResult(int requestCode, int resultCode, Intent data) {
3397         // File uploads only work on API >= 21.
3398         if (Build.VERSION.SDK_INT >= 21) {
3399             // Pass the file to the WebView.
3400             fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3401         }
3402     }
3403
3404     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3405         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
3406         String unformattedUrlString = urlTextBox.getText().toString().trim();
3407
3408         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
3409         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3410             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
3411             if (!unformattedUrlString.startsWith("http")) {
3412                 unformattedUrlString = "http://" + unformattedUrlString;
3413             }
3414
3415             // Initialize `unformattedUrl`.
3416             URL unformattedUrl = null;
3417
3418             // 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.
3419             try {
3420                 unformattedUrl = new URL(unformattedUrlString);
3421             } catch (MalformedURLException e) {
3422                 e.printStackTrace();
3423             }
3424
3425             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3426             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3427             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3428             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3429             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3430             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3431
3432             // Build the URI.
3433             Uri.Builder formattedUri = new Uri.Builder();
3434             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3435
3436             // Decode `formattedUri` as a `String` in `UTF-8`.
3437             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3438         } else if (unformattedUrlString.isEmpty()){  // Load a blank web site.
3439             // Load a blank string.
3440             formattedUrlString = "";
3441         } else {  // Search for the contents of the URL box.
3442             // Sanitize the search input and convert it to a search.
3443             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3444
3445             // Add the base search URL.
3446             formattedUrlString = searchURL + encodedUrlString;
3447         }
3448
3449         // 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.
3450         urlTextBox.clearFocus();
3451
3452         // Make it so.
3453         loadUrl(formattedUrlString);
3454     }
3455
3456     private void loadUrl(String url) {// Apply any custom domain settings.
3457         // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3458         formattedUrlString = url;
3459
3460         // Apply the domain settings.
3461         applyDomainSettings(url, true, false);
3462
3463         // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3464         urlIsLoading = true;
3465
3466         // Load the URL.
3467         mainWebView.loadUrl(url, customHeaders);
3468     }
3469
3470     public void findPreviousOnPage(View view) {
3471         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
3472         mainWebView.findNext(false);
3473     }
3474
3475     public void findNextOnPage(View view) {
3476         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3477         mainWebView.findNext(true);
3478     }
3479
3480     public void closeFindOnPage(View view) {
3481         // Delete the contents of `find_on_page_edittext`.
3482         findOnPageEditText.setText(null);
3483
3484         // Clear the highlighted phrases.
3485         mainWebView.clearMatches();
3486
3487         // Hide the Find on Page `RelativeLayout`.
3488         findOnPageLinearLayout.setVisibility(View.GONE);
3489
3490         // Show the URL app bar.
3491         supportAppBar.setVisibility(View.VISIBLE);
3492
3493         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
3494         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3495     }
3496
3497     private void applyAppSettings() {
3498         // Get a handle for the shared preferences.
3499         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3500
3501         // Store the values from the shared preferences in variables.
3502         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3503         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3504         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3505         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3506         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3507         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3508         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3509         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3510         proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3511         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3512         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3513         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3514         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3515
3516         // Set the homepage, search, and proxy options.
3517         if (proxyThroughOrbot) {  // Set the Tor options.
3518             // Set `torHomepageString` as `homepage`.
3519             homepage = torHomepageString;
3520
3521             // If formattedUrlString is null assign the homepage to it.
3522             if (formattedUrlString == null) {
3523                 formattedUrlString = homepage;
3524             }
3525
3526             // Set the search URL.
3527             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
3528                 searchURL = torSearchCustomURLString;
3529             } else {  // Use the string from the pre-built list.
3530                 searchURL = torSearchString;
3531             }
3532
3533             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
3534             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3535
3536             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
3537             if (darkTheme) {
3538                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3539             } else {
3540                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3541             }
3542
3543             // Display a message to the user if waiting for Orbot.
3544             if (!orbotStatus.equals("ON")) {
3545                 // Set `waitingForOrbot`.
3546                 waitingForOrbot = true;
3547
3548                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
3549                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3550             }
3551         } else {  // Set the non-Tor options.
3552             // Set `homepageString` as `homepage`.
3553             homepage = homepageString;
3554
3555             // If formattedUrlString is null assign the homepage to it.
3556             if (formattedUrlString == null) {
3557                 formattedUrlString = homepage;
3558             }
3559
3560             // Set the search URL.
3561             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
3562                 searchURL = searchCustomURLString;
3563             } else {  // Use the string from the pre-built list.
3564                 searchURL = searchString;
3565             }
3566
3567             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
3568             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3569
3570             // Set the default `appBar` background.  `this` refers to the context.
3571             if (darkTheme) {
3572                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3573             } else {
3574                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3575             }
3576
3577             // Reset `waitingForOrbot.
3578             waitingForOrbot = false;
3579         }
3580
3581         // Set Do Not Track status.
3582         if (doNotTrackEnabled) {
3583             customHeaders.put("DNT", "1");
3584         } else {
3585             customHeaders.remove("DNT");
3586         }
3587
3588         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3589         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3590             if (hideSystemBarsOnFullscreen) {  // Hide everything.
3591                 // Remove the translucent navigation setting if it is currently flagged.
3592                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3593
3594                 // Remove the translucent status bar overlay.
3595                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3596
3597                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3598                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3599
3600                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3601                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3602                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3603                  */
3604                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3605             } else {  // Hide everything except the status and navigation bars.
3606                 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3607                 rootCoordinatorLayout.setSystemUiVisibility(0);
3608
3609                 // Add the translucent status flag if it is unset.
3610                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3611
3612                 if (translucentNavigationBarOnFullscreen) {
3613                     // Set the navigation bar to be translucent.
3614                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3615                 } else {
3616                     // Set the navigation bar to be black.
3617                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3618                 }
3619             }
3620         } else {  // Privacy Browser is not in full screen browsing mode.
3621             // 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.
3622             inFullScreenBrowsingMode = false;
3623
3624             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3625             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3626                 appBar.show();
3627             }
3628
3629             // Show the `BannerAd` in the free flavor.
3630             if (BuildConfig.FLAVOR.contentEquals("free")) {
3631                 // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3632                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3633             }
3634
3635             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3636             rootCoordinatorLayout.setSystemUiVisibility(0);
3637
3638             // Remove the translucent navigation bar flag if it is set.
3639             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3640
3641             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3642             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3643
3644             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3645             rootCoordinatorLayout.setFitsSystemWindows(true);
3646         }
3647     }
3648
3649     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3650     // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3651     @SuppressWarnings("deprecation")
3652     private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3653         // Parse the URL into a URI.
3654         Uri uri = Uri.parse(url);
3655
3656         // Extract the domain from `uri`.
3657         String hostName = uri.getHost();
3658
3659         // Initialize `loadingNewDomainName`.
3660         boolean loadingNewDomainName;
3661
3662         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3663         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3664         //noinspection SimplifiableIfStatement
3665         if ((hostName == null) || (currentDomainName == null)) {
3666             loadingNewDomainName = true;
3667         } else {  // Determine if `hostName` equals `currentDomainName`.
3668             loadingNewDomainName = !hostName.equals(currentDomainName);
3669         }
3670
3671         // Strings don't like to be null.
3672         if (hostName == null) {
3673             hostName = "";
3674         }
3675
3676         // 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.
3677         if (loadingNewDomainName) {
3678             // Set the new `hostname` as the `currentDomainName`.
3679             currentDomainName = hostName;
3680
3681             // Reset `ignorePinnedSslCertificate`.
3682             ignorePinnedSslCertificate = false;
3683
3684             // Reset the favorite icon if specified.
3685             if (resetFavoriteIcon) {
3686                 favoriteIconBitmap = favoriteIconDefaultBitmap;
3687                 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3688             }
3689
3690             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3691             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3692             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3693
3694             // Get a full cursor from `domainsDatabaseHelper`.
3695             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3696
3697             // Initialize `domainSettingsSet`.
3698             Set<String> domainSettingsSet = new HashSet<>();
3699
3700             // Get the domain name column index.
3701             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3702
3703             // Populate `domainSettingsSet`.
3704             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3705                 // Move `domainsCursor` to the current row.
3706                 domainNameCursor.moveToPosition(i);
3707
3708                 // Store the domain name in `domainSettingsSet`.
3709                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3710             }
3711
3712             // Close `domainNameCursor.
3713             domainNameCursor.close();
3714
3715             // Initialize variables to track if domain settings will be applied and, if so, under which name.
3716             domainSettingsApplied = false;
3717             String domainNameInDatabase = null;
3718
3719             // Check the hostname.
3720             if (domainSettingsSet.contains(hostName)) {
3721                 domainSettingsApplied = true;
3722                 domainNameInDatabase = hostName;
3723             }
3724
3725             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3726             while (!domainSettingsApplied && hostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3727                 if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
3728                     // Apply the domain settings.
3729                     domainSettingsApplied = true;
3730
3731                     // Store the applied domain names as it appears in the database.
3732                     domainNameInDatabase = "*." + hostName;
3733                 }
3734
3735                 // Strip out the lowest subdomain of of the host name.
3736                 hostName = hostName.substring(hostName.indexOf(".") + 1);
3737             }
3738
3739
3740             // Get a handle for the shared preference.
3741             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3742
3743             // Store the general preference information.
3744             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3745             String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3746             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3747             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3748             nightMode = sharedPreferences.getBoolean("night_mode", false);
3749
3750             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
3751                 // Get a cursor for the current host and move it to the first position.
3752                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3753                 currentHostDomainSettingsCursor.moveToFirst();
3754
3755                 // Get the settings from the cursor.
3756                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3757                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3758                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3759                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3760                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3761                 // Form data can be removed once the minimum API >= 26.
3762                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3763                 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3764                 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3765                 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3766                 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3767                 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3768                 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3769                 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3770                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3771                 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3772                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3773                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3774                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3775                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3776                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3777                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3778                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3779                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3780                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3781
3782                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3783                 switch (nightModeInt) {
3784                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3785                         nightMode = true;
3786                         break;
3787
3788                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3789                         nightMode = false;
3790                         break;
3791                 }
3792
3793                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3794                 if (nightMode) {
3795                     javaScriptEnabled = true;
3796                 }
3797
3798                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3799                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3800                     pinnedDomainSslStartDate = null;
3801                 } else {
3802                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3803                 }
3804
3805                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3806                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3807                     pinnedDomainSslEndDate = null;
3808                 } else {
3809                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3810                 }
3811
3812                 // Close `currentHostDomainSettingsCursor`.
3813                 currentHostDomainSettingsCursor.close();
3814
3815                 // Apply the domain settings.
3816                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3817                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3818                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3819
3820                 // Apply the form data setting if the API < 26.
3821                 if (Build.VERSION.SDK_INT < 26) {
3822                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3823                 }
3824
3825                 // Apply the font size.
3826                 if (fontSize == 0) {  // Apply the default font size.
3827                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3828                 } else {  // Apply the specified font size.
3829                     mainWebView.getSettings().setTextZoom(fontSize);
3830                 }
3831
3832                 // Set third-party cookies status if API >= 21.
3833                 if (Build.VERSION.SDK_INT >= 21) {
3834                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3835                 }
3836
3837                 // 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.
3838                 // <https://redmine.stoutner.com/issues/160>
3839                 if (!urlIsLoading) {
3840                     // Set the user agent.
3841                     if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3842                         // Get the array position of the default user agent name.
3843                         int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3844
3845                         // Set the user agent according to the system default.
3846                         switch (defaultUserAgentArrayPosition) {
3847                             case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3848                                 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3849                                 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3850                                 break;
3851
3852                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3853                                 // Set the user agent to `""`, which uses the default value.
3854                                 mainWebView.getSettings().setUserAgentString("");
3855                                 break;
3856
3857                             case SETTINGS_CUSTOM_USER_AGENT:
3858                                 // Set the custom user agent.
3859                                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3860                                 break;
3861
3862                             default:
3863                                 // Get the user agent string from the user agent data array
3864                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3865                         }
3866                     } else {  // Set the user agent according to the stored name.
3867                         // Get the array position of the user agent name.
3868                         int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3869
3870                         switch (userAgentArrayPosition) {
3871                             case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3872                                 mainWebView.getSettings().setUserAgentString(userAgentName);
3873                                 break;
3874
3875                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3876                                 // Set the user agent to `""`, which uses the default value.
3877                                 mainWebView.getSettings().setUserAgentString("");
3878                                 break;
3879
3880                             default:
3881                                 // Get the user agent string from the user agent data array.
3882                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3883                         }
3884                     }
3885
3886                     // Set swipe to refresh.
3887                     switch (swipeToRefreshInt) {
3888                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3889                             // Set swipe to refresh according to the default.
3890                             swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3891                             break;
3892
3893                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3894                             // Enable swipe to refresh.
3895                             swipeRefreshLayout.setEnabled(true);
3896                             break;
3897
3898                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3899                             // Disable swipe to refresh.
3900                             swipeRefreshLayout.setEnabled(false);
3901                     }
3902
3903                     // Store the applied user agent string, which is used in the View Source activity.
3904                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3905                 }
3906
3907                 // 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.
3908                 if (darkTheme) {
3909                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3910                 } else {
3911                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3912                 }
3913             } else {  // The new URL does not have custom domain settings.  Load the defaults.
3914                 // Store the values from `sharedPreferences` in variables.
3915                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3916                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3917                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3918                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3919                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);  // Form data can be removed once the minimum API >= 26.
3920                 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3921                 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3922                 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3923                 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3924                 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
3925                 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3926
3927                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3928                 if (nightMode) {
3929                     javaScriptEnabled = true;
3930                 }
3931
3932                 // Apply the default settings.
3933                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3934                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3935                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3936                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3937                 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3938
3939                 // Apply the form data setting if the API < 26.
3940                 if (Build.VERSION.SDK_INT < 26) {
3941                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3942                 }
3943
3944                 // Reset the pinned SSL certificate information.
3945                 domainSettingsDatabaseId = -1;
3946                 pinnedDomainSslCertificate = false;
3947                 pinnedDomainSslIssuedToCNameString = "";
3948                 pinnedDomainSslIssuedToONameString = "";
3949                 pinnedDomainSslIssuedToUNameString = "";
3950                 pinnedDomainSslIssuedByCNameString = "";
3951                 pinnedDomainSslIssuedByONameString = "";
3952                 pinnedDomainSslIssuedByUNameString = "";
3953                 pinnedDomainSslStartDate = null;
3954                 pinnedDomainSslEndDate = null;
3955
3956                 // Set third-party cookies status if API >= 21.
3957                 if (Build.VERSION.SDK_INT >= 21) {
3958                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3959                 }
3960
3961                 // 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.
3962                 // <https://redmine.stoutner.com/issues/160>
3963                 if (!urlIsLoading) {
3964                     // Get the array position of the user agent name.
3965                     int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3966
3967                     // Set the user agent.
3968                     switch (userAgentArrayPosition) {
3969                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3970                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3971                             mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3972                             break;
3973
3974                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3975                             // Set the user agent to `""`, which uses the default value.
3976                             mainWebView.getSettings().setUserAgentString("");
3977                             break;
3978
3979                         case SETTINGS_CUSTOM_USER_AGENT:
3980                             // Set the custom user agent.
3981                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3982                             break;
3983
3984                         default:
3985                             // Get the user agent string from the user agent data array
3986                             mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3987                     }
3988
3989                     // Store the applied user agent string, which is used in the View Source activity.
3990                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3991                 }
3992
3993                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3994                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3995             }
3996
3997             // Close `domainsDatabaseHelper`.
3998             domainsDatabaseHelper.close();
3999
4000             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
4001             onTheFlyDisplayImagesSet = false;
4002             setDisplayWebpageImages();
4003
4004             // Update the privacy icons, but only if `mainMenu` has already been populated.
4005             if (mainMenu != null) {
4006                 updatePrivacyIcons(true);
4007             }
4008         }
4009
4010         // Reload the website if returning from the Domains activity.
4011         if (reloadWebsite) {
4012             mainWebView.reload();
4013         }
4014     }
4015
4016     private void setDisplayWebpageImages() {
4017         if (!onTheFlyDisplayImagesSet) {
4018             if (domainSettingsApplied) {  // Custom domain settings are applied.
4019                 switch (displayWebpageImagesInt) {
4020                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4021                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4022                         break;
4023
4024                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4025                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
4026                         break;
4027
4028                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4029                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
4030                         break;
4031                 }
4032             } else {  // Default settings are applied.
4033                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4034             }
4035         }
4036     }
4037
4038     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4039         // Get handles for the menu items.
4040         MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4041         MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4042         MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4043         MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4044
4045         // Update the privacy icon.
4046         if (javaScriptEnabled) {  // JavaScript is enabled.
4047             privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4048         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
4049             privacyMenuItem.setIcon(R.drawable.warning);
4050         } else {  // All the dangerous features are disabled.
4051             privacyMenuItem.setIcon(R.drawable.privacy_mode);
4052         }
4053
4054         // Update the first-party cookies icon.
4055         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
4056             firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4057         } else {  // First-party cookies are disabled.
4058             if (darkTheme) {
4059                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4060             } else {
4061                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4062             }
4063         }
4064
4065         // Update the DOM storage icon.
4066         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
4067             domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4068         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
4069             if (darkTheme) {
4070                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4071             } else {
4072                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4073             }
4074         } else {  // JavaScript is disabled, so DOM storage is ghosted.
4075             if (darkTheme) {
4076                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4077             } else {
4078                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4079             }
4080         }
4081
4082         // Update the refresh icon.
4083         if (darkTheme) {
4084             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4085         } else {
4086             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4087         }
4088
4089         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4090         if (runInvalidateOptionsMenu) {
4091             invalidateOptionsMenu();
4092         }
4093     }
4094
4095     private void highlightUrlText() {
4096         String urlString = urlTextBox.getText().toString();
4097
4098         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4099             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4100         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4101             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4102         }
4103
4104         // Get the index of the `/` immediately after the domain name.
4105         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4106
4107         // De-emphasize the text after the domain name.
4108         if (endOfDomainName > 0) {
4109             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4110         }
4111     }
4112
4113     private void loadBookmarksFolder() {
4114         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4115         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4116
4117         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
4118         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4119             @Override
4120             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4121                 // Inflate the individual item layout.  `false` does not attach it to the root.
4122                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4123             }
4124
4125             @Override
4126             public void bindView(View view, Context context, Cursor cursor) {
4127                 // Get handles for the views.
4128                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4129                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4130
4131                 // Get the favorite icon byte array from the cursor.
4132                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4133
4134                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4135                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4136
4137                 // Display the bitmap in `bookmarkFavoriteIcon`.
4138                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4139
4140                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4141                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4142                 bookmarkNameTextView.setText(bookmarkNameString);
4143
4144                 // Make the font bold for folders.
4145                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4146                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4147                 } else {  // Reset the font to default for normal bookmarks.
4148                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4149                 }
4150             }
4151         };
4152
4153         // Populate the `ListView` with the adapter.
4154         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4155
4156         // Set the bookmarks drawer title.
4157         if (currentBookmarksFolder.isEmpty()) {
4158             bookmarksTitleTextView.setText(R.string.bookmarks);
4159         } else {
4160             bookmarksTitleTextView.setText(currentBookmarksFolder);
4161         }
4162     }
4163 }