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