7c13950a9334030c6d4d86a608046e4508975e96
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DialogFragment;
28 import android.app.DownloadManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.support.annotation.NonNull;
56 import android.support.design.widget.CoordinatorLayout;
57 import android.support.design.widget.FloatingActionButton;
58 import android.support.design.widget.NavigationView;
59 import android.support.design.widget.Snackbar;
60 import android.support.v4.app.ActivityCompat;
61 import android.support.v4.content.ContextCompat;
62 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
63 import android.support.v4.content.pm.ShortcutInfoCompat;
64 import android.support.v4.content.pm.ShortcutManagerCompat;
65 import android.support.v4.graphics.drawable.IconCompat;
66 import android.support.v4.view.GravityCompat;
67 import android.support.v4.widget.DrawerLayout;
68 import android.support.v4.widget.SwipeRefreshLayout;
69 import android.support.v7.app.ActionBar;
70 import android.support.v7.app.ActionBarDrawerToggle;
71 import android.support.v7.app.AppCompatActivity;
72 import android.support.v7.app.AppCompatDialogFragment;
73 import android.support.v7.widget.Toolbar;
74 import android.text.Editable;
75 import android.text.Spanned;
76 import android.text.TextWatcher;
77 import android.text.style.ForegroundColorSpan;
78 import android.util.Patterns;
79 import android.view.ContextMenu;
80 import android.view.GestureDetector;
81 import android.view.KeyEvent;
82 import android.view.Menu;
83 import android.view.MenuItem;
84 import android.view.MotionEvent;
85 import android.view.View;
86 import android.view.ViewGroup;
87 import android.view.WindowManager;
88 import android.view.inputmethod.InputMethodManager;
89 import android.webkit.CookieManager;
90 import android.webkit.HttpAuthHandler;
91 import android.webkit.SslErrorHandler;
92 import android.webkit.ValueCallback;
93 import android.webkit.WebBackForwardList;
94 import android.webkit.WebChromeClient;
95 import android.webkit.WebResourceResponse;
96 import android.webkit.WebStorage;
97 import android.webkit.WebView;
98 import android.webkit.WebViewClient;
99 import android.webkit.WebViewDatabase;
100 import android.widget.ArrayAdapter;
101 import android.widget.CursorAdapter;
102 import android.widget.EditText;
103 import android.widget.FrameLayout;
104 import android.widget.ImageView;
105 import android.widget.LinearLayout;
106 import android.widget.ListView;
107 import android.widget.ProgressBar;
108 import android.widget.RadioButton;
109 import android.widget.RelativeLayout;
110 import android.widget.TextView;
111
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
119 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
121 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
122 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
123 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
124 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
125 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
126 import com.stoutner.privacybrowser.helpers.AdHelper;
127 import com.stoutner.privacybrowser.helpers.BlockListHelper;
128 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
130 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
131 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
132 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
133
134 import java.io.ByteArrayInputStream;
135 import java.io.ByteArrayOutputStream;
136 import java.io.File;
137 import java.io.IOException;
138 import java.io.UnsupportedEncodingException;
139 import java.net.MalformedURLException;
140 import java.net.URL;
141 import java.net.URLDecoder;
142 import java.net.URLEncoder;
143 import java.util.ArrayList;
144 import java.util.Date;
145 import java.util.HashMap;
146 import java.util.HashSet;
147 import java.util.List;
148 import java.util.Map;
149 import java.util.Set;
150
151 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
152 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
153         CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
154         DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
155         HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
156         SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
157
158     // `darkTheme` is public static so it can be accessed from everywhere.
159     public static boolean darkTheme;
160
161     // `allowScreenshots` is public static so it can be accessed from everywhere.  It is also used in `onCreate()`.
162     public static boolean allowScreenshots;
163
164     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
165     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
166     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
167     public static Bitmap favoriteIconBitmap;
168
169     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
170     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
171     public static String formattedUrlString;
172
173     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
174     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
175     public static SslCertificate sslCertificate;
176
177     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()` and `onResume()`.
178     public static String orbotStatus;
179
180     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
181     public static String webViewTitle;
182
183     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
184     public static String appliedUserAgentString;
185
186     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
187     public static boolean reloadOnRestart;
188
189     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`.  It is also used in `onRestart()`.
190     public static boolean loadUrlOnRestart;
191
192     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
193     public static boolean restartFromBookmarksActivity;
194
195     // The block list versions are public static so they can be accessed from `AboutTabFragment`.  They are also used in `onCreate()`.
196     public static String easyListVersion;
197     public static String easyPrivacyVersion;
198     public static String fanboysAnnoyanceVersion;
199     public static String fanboysSocialVersion;
200     public static String ultraPrivacyVersion;
201
202     // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`.  They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
203     public static List<String[]> resourceRequests;
204     public static String[] whiteListResultStringArray;
205     private int blockedRequests;
206     private int easyListBlockedRequests;
207     private int easyPrivacyBlockedRequests;
208     private int fanboysAnnoyanceListBlockedRequests;
209     private int fanboysSocialBlockingListBlockedRequests;
210     private int ultraPrivacyBlockedRequests;
211     private int thirdPartyBlockedRequests;
212
213     public final static int REQUEST_DISPOSITION = 0;
214     public final static int REQUEST_URL = 1;
215     public final static int REQUEST_BLOCKLIST = 2;
216     public final static int REQUEST_SUBLIST = 3;
217     public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
218     public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
219
220     public final static int REQUEST_DEFAULT = 0;
221     public final static int REQUEST_ALLOWED = 1;
222     public final static int REQUEST_THIRD_PARTY = 2;
223     public final static int REQUEST_BLOCKED = 3;
224
225     public final static int MAIN_WHITELIST = 1;
226     public final static int FINAL_WHITELIST = 2;
227     public final static int DOMAIN_WHITELIST = 3;
228     public final static int DOMAIN_INITIAL_WHITELIST = 4;
229     public final static int DOMAIN_FINAL_WHITELIST = 5;
230     public final static int THIRD_PARTY_WHITELIST = 6;
231     public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
232     public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
233
234     public final static int MAIN_BLACKLIST = 9;
235     public final static int INITIAL_BLACKLIST = 10;
236     public final static int FINAL_BLACKLIST = 11;
237     public final static int DOMAIN_BLACKLIST = 12;
238     public final static int DOMAIN_INITIAL_BLACKLIST = 13;
239     public final static int DOMAIN_FINAL_BLACKLIST = 14;
240     public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
241     public final static int THIRD_PARTY_BLACKLIST = 16;
242     public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
243     public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
244     public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
245     public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
246     public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
247     public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
248
249     // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
250     // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
251     public static boolean blockAllThirdPartyRequests;
252
253     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
254     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
255     public static String currentBookmarksFolder;
256
257     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
258     public static int domainSettingsDatabaseId;
259
260     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
261     public static String pinnedDomainSslIssuedToCNameString;
262     public static String pinnedDomainSslIssuedToONameString;
263     public static String pinnedDomainSslIssuedToUNameString;
264     public static String pinnedDomainSslIssuedByCNameString;
265     public static String pinnedDomainSslIssuedByONameString;
266     public static String pinnedDomainSslIssuedByUNameString;
267     public static Date pinnedDomainSslStartDate;
268     public static Date pinnedDomainSslEndDate;
269
270     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
271     public final static int UNRECOGNIZED_USER_AGENT = -1;
272     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
273     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
274     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
275     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
276     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
277
278
279     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
280     private ActionBar appBar;
281
282     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
283     private boolean navigatingHistory;
284
285     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
286     private Bitmap favoriteIconDefaultBitmap;
287
288     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
289     private DrawerLayout drawerLayout;
290
291     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
292     private CoordinatorLayout rootCoordinatorLayout;
293
294     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
295     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
296     private WebView mainWebView;
297
298     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
299     private FrameLayout fullScreenVideoFrameLayout;
300
301     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
302     private SwipeRefreshLayout swipeRefreshLayout;
303
304     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
305     private RelativeLayout urlAppBarRelativeLayout;
306
307     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
308     private ImageView favoriteIconImageView;
309
310     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
311     private CookieManager cookieManager;
312
313     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
314     private final Map<String, String> customHeaders = new HashMap<>();
315
316     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
317     private boolean javaScriptEnabled;
318
319     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
320     private boolean firstPartyCookiesEnabled;
321
322     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
323     private boolean thirdPartyCookiesEnabled;
324
325     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
326     private boolean domStorageEnabled;
327
328     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.  It can be removed once the minimum API >= 26.
329     private boolean saveFormDataEnabled;
330
331     // `nightMode` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and  `applyDomainSettings()`.
332     private boolean nightMode;
333
334     // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
335     private boolean displayWebpageImagesBoolean;
336
337     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
338     private String homepage;
339
340     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
341     private String searchURL;
342
343     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
344     private Menu mainMenu;
345
346     // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
347     private MenuItem refreshMenuItem;
348
349     // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
350     private MenuItem blocklistsMenuItem;
351     private MenuItem easyListMenuItem;
352     private MenuItem easyPrivacyMenuItem;
353     private MenuItem fanboysAnnoyanceListMenuItem;
354     private MenuItem fanboysSocialBlockingListMenuItem;
355     private MenuItem ultraPrivacyMenuItem;
356     private MenuItem blockAllThirdPartyRequestsMenuItem;
357
358     // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
359     private boolean easyListEnabled;
360     private boolean easyPrivacyEnabled;
361     private boolean fanboysAnnoyanceListEnabled;
362     private boolean fanboysSocialBlockingListEnabled;
363     private boolean ultraPrivacyEnabled;
364
365     // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
366     private String webViewDefaultUserAgent;
367
368     // `defaultCustomUserAgentString` is used in `onPrepareOptionsMenu()` and `applyDomainSettings()`.
369     private String defaultCustomUserAgentString;
370
371     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
372     private Runtime privacyBrowserRuntime;
373
374     // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
375     private boolean proxyThroughOrbot;
376
377     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
378     private boolean incognitoModeEnabled;
379
380     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
381     private boolean fullScreenBrowsingModeEnabled;
382
383     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
384     private boolean inFullScreenBrowsingMode;
385
386     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
387     private boolean hideSystemBarsOnFullscreen;
388
389     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
390     private boolean translucentNavigationBarOnFullscreen;
391
392     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
393     private boolean reapplyDomainSettingsOnRestart;
394
395     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
396     private boolean reapplyAppSettingsOnRestart;
397
398     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
399     private boolean displayingFullScreenVideo;
400
401     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
402     private String currentDomainName;
403
404     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
405     private boolean ignorePinnedSslCertificate;
406
407     // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
408     private BroadcastReceiver orbotStatusBroadcastReceiver;
409
410     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
411     private boolean waitingForOrbot;
412
413     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
414     private boolean domainSettingsApplied;
415
416     // `domainSettingsJavaScriptEnabled` is used in `onOptionsItemSelected()` and `applyDomainSettings()`.
417     private Boolean domainSettingsJavaScriptEnabled;
418
419     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
420     private int displayWebpageImagesInt;
421
422     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
423     private boolean onTheFlyDisplayImagesSet;
424
425     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
426     private String waitingForOrbotHTMLString;
427
428     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
429     private String privateDataDirectoryString;
430
431     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
432     private LinearLayout findOnPageLinearLayout;
433
434     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
435     private EditText findOnPageEditText;
436
437     // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
438     private boolean displayAdditionalAppBarIcons;
439
440     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
441     private ActionBarDrawerToggle drawerToggle;
442
443     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
444     private Toolbar supportAppBar;
445
446     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
447     private EditText urlTextBox;
448
449     // The color spans are used in `onCreate()` and `highlightUrlText()`.
450     private ForegroundColorSpan redColorSpan;
451     private ForegroundColorSpan initialGrayColorSpan;
452     private ForegroundColorSpan finalGrayColorSpan;
453
454     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
455     private SslErrorHandler sslErrorHandler;
456
457     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
458     private static HttpAuthHandler httpAuthHandler;
459
460     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
461     private InputMethodManager inputMethodManager;
462
463     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
464     private RelativeLayout mainWebViewRelativeLayout;
465
466     // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
467     private boolean urlIsLoading;
468
469     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
470     private boolean pinnedDomainSslCertificate;
471
472     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
473     // and `loadBookmarksFolder()`.
474     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
475
476     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
477     private ListView bookmarksListView;
478
479     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
480     private TextView bookmarksTitleTextView;
481
482     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
483     private Cursor bookmarksCursor;
484
485     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
486     private CursorAdapter bookmarksCursorAdapter;
487
488     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
489     private String oldFolderNameString;
490
491     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
492     private ValueCallback<Uri[]> fileChooserCallback;
493
494     // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
495     private String downloadUrl;
496     private String downloadContentDisposition;
497     private long downloadContentLength;
498
499     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
500     private String downloadImageUrl;
501
502     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
503     private ArrayAdapter<CharSequence> userAgentNamesArray;
504     private String[] userAgentDataArray;
505
506     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
507     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
508     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
509
510     @Override
511     // 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.
512     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
513     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
514     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
515     @SuppressWarnings("deprecation")
516     protected void onCreate(Bundle savedInstanceState) {
517         // Get a handle for the shared preferences.
518         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
519
520         // Get the theme and screenshot preferences.
521         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
522         allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
523
524         // Disable screenshots if not allowed.
525         if (!allowScreenshots) {
526             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
527         }
528
529         // Set the activity theme.
530         if (darkTheme) {
531             setTheme(R.style.PrivacyBrowserDark);
532         } else {
533             setTheme(R.style.PrivacyBrowserLight);
534         }
535
536         // Run the default commands.
537         super.onCreate(savedInstanceState);
538
539         // Set the content view.
540         setContentView(R.layout.main_drawerlayout);
541
542         // Get a handle for `inputMethodManager`.
543         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
544
545         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
546         supportAppBar = findViewById(R.id.app_bar);
547         setSupportActionBar(supportAppBar);
548         appBar = getSupportActionBar();
549
550         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
551         assert appBar != null;
552
553         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
554         appBar.setCustomView(R.layout.url_app_bar);
555         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
556
557         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
558         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
559         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
560         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
561
562         // Get a handle for `urlTextBox`.
563         urlTextBox = findViewById(R.id.url_edittext);
564
565         // Remove the formatting from `urlTextBar` when the user is editing the text.
566         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
567             if (hasFocus) {  // The user is editing the URL text box.
568                 // Remove the highlighting.
569                 urlTextBox.getText().removeSpan(redColorSpan);
570                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
571                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
572             } else {  // The user has stopped editing the URL text box.
573                 // Move to the beginning of the string.
574                 urlTextBox.setSelection(0);
575
576                 // Reapply the highlighting.
577                 highlightUrlText();
578             }
579         });
580
581         // Set the go button on the keyboard to load the URL in `urlTextBox`.
582         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
583             // If the event is a key-down event on the `enter` button, load the URL.
584             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
585                 // Load the URL into the mainWebView and consume the event.
586                 try {
587                     loadUrlFromTextBox();
588                 } catch (UnsupportedEncodingException e) {
589                     e.printStackTrace();
590                 }
591                 // If the enter key was pressed, consume the event.
592                 return true;
593             } else {
594                 // If any other key was pressed, do not consume the event.
595                 return false;
596             }
597         });
598
599         // Set `waitingForOrbotHTMLString`.
600         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
601
602         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
603         currentDomainName = "";
604         orbotStatus = "unknown";
605         waitingForOrbot = false;
606
607         // Create an Orbot status `BroadcastReceiver`.
608         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
609             @Override
610             public void onReceive(Context context, Intent intent) {
611                 // Store the content of the status message in `orbotStatus`.
612                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
613
614                 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
615                 if (orbotStatus.equals("ON") && waitingForOrbot) {
616                     // Reset `waitingForOrbot`.
617                     waitingForOrbot = false;
618
619                     // Load `formattedUrlString
620                     loadUrl(formattedUrlString);
621                 }
622             }
623         };
624
625         // Register `orbotStatusBroadcastReceiver` on `this` context.
626         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
627
628         // Get handles for views that need to be accessed.
629         drawerLayout = findViewById(R.id.drawerlayout);
630         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
631         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
632         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
633         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
634         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
635         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
636         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
637         mainWebView = findViewById(R.id.main_webview);
638         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
639         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
640         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
641         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
642         favoriteIconImageView = findViewById(R.id.favorite_icon);
643
644         // 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.
645         if (darkTheme) {
646             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
647             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
648             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
649             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
650         } else {
651             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
652             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
653             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
654             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
655         }
656
657         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
658         launchBookmarksActivityFab.setOnClickListener(v -> {
659             // Create an intent to launch the bookmarks activity.
660             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
661
662             // Include the current folder with the `Intent`.
663             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
664
665             // Make it so.
666             startActivity(bookmarksIntent);
667         });
668
669         // Set the create new bookmark folder FAB to display an alert dialog.
670         createBookmarkFolderFab.setOnClickListener(v -> {
671             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
672             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
673             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
674         });
675
676         // Set the create new bookmark FAB to display an alert dialog.
677         createBookmarkFab.setOnClickListener(view -> {
678             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
679             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
680             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
681         });
682
683         // Create a double-tap listener to toggle full-screen mode.
684         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
685             // Override `onDoubleTap()`.  All other events are handled using the default settings.
686             @Override
687             public boolean onDoubleTap(MotionEvent event) {
688                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
689                     // Toggle `inFullScreenBrowsingMode`.
690                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
691
692                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
693                         // Hide the `appBar`.
694                         appBar.hide();
695
696                         // Hide the banner ad in the free flavor.
697                         if (BuildConfig.FLAVOR.contentEquals("free")) {
698                             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
699                             AdHelper.hideAd(findViewById(R.id.adview));
700                         }
701
702                         // Modify the system bars.
703                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
704                             // Remove the translucent overlays.
705                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
706
707                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
708                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
709
710                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
711                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
712                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
713                              */
714                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
715
716                             // Set `rootCoordinatorLayout` to fill the whole screen.
717                             rootCoordinatorLayout.setFitsSystemWindows(false);
718                         } else {  // Hide everything except the status and navigation bars.
719                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
720                             rootCoordinatorLayout.setFitsSystemWindows(false);
721
722                             // 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.
723                             if (translucentNavigationBarOnFullscreen) {
724                                 // Set the navigation bar to be translucent.
725                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
726                             }
727                         }
728                     } else {  // Switch to normal viewing mode.
729                         // Show the `appBar`.
730                         appBar.show();
731
732                         // Show the `BannerAd` in the free flavor.
733                         if (BuildConfig.FLAVOR.contentEquals("free")) {
734                             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
735                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
736                         }
737
738                         // Remove the translucent navigation bar flag if it is set.
739                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
740
741                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
742                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
743
744                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
745                         rootCoordinatorLayout.setSystemUiVisibility(0);
746
747                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
748                         rootCoordinatorLayout.setFitsSystemWindows(true);
749                     }
750
751                     // Consume the double-tap.
752                     return true;
753                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
754                     return false;
755                 }
756             }
757         });
758
759         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
760         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
761             // Call `performClick()` on the view, which is required for accessibility.
762             v.performClick();
763
764             // Send the `event` to `gestureDetector`.
765             return gestureDetector.onTouchEvent(event);
766         });
767
768         // Update `findOnPageCountTextView`.
769         mainWebView.setFindListener(new WebView.FindListener() {
770             // Get a handle for `findOnPageCountTextView`.
771             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
772
773             @Override
774             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
775                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
776                     // Set `findOnPageCountTextView` to `0/0`.
777                     findOnPageCountTextView.setText(R.string.zero_of_zero);
778                 } else if (isDoneCounting) {  // There are matches.
779                     // `activeMatchOrdinal` is zero-based.
780                     int activeMatch = activeMatchOrdinal + 1;
781
782                     // Build the match string.
783                     String matchString = activeMatch + "/" + numberOfMatches;
784
785                     // Set `findOnPageCountTextView`.
786                     findOnPageCountTextView.setText(matchString);
787                 }
788             }
789         });
790
791         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
792         findOnPageEditText.addTextChangedListener(new TextWatcher() {
793             @Override
794             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
795                 // Do nothing.
796             }
797
798             @Override
799             public void onTextChanged(CharSequence s, int start, int before, int count) {
800                 // Do nothing.
801             }
802
803             @Override
804             public void afterTextChanged(Editable s) {
805                 // Search for the text in `mainWebView`.
806                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
807             }
808         });
809
810         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
811         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
812             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
813                 // Hide the soft keyboard.  `0` indicates no additional flags.
814                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
815
816                 // Consume the event.
817                 return true;
818             } else {  // A different key was pressed.
819                 // Do not consume the event.
820                 return false;
821             }
822         });
823
824         // Implement swipe to refresh
825         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
826         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
827         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
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.
932                     urlTextBox.clearFocus();
933                 }
934             }
935         });
936
937         // drawerToggle creates the hamburger icon at the start of the AppBar.
938         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
939
940         // Get a handle for the progress bar.
941         final ProgressBar progressBar = findViewById(R.id.progress_bar);
942
943         mainWebView.setWebChromeClient(new WebChromeClient() {
944             // Update the progress bar when a page is loading.
945             @Override
946             public void onProgressChanged(WebView view, int progress) {
947                 // Inject the night mode CSS if night mode is enabled.
948                 if (nightMode) {
949                     // `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
950                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
951                     // `border: none` removes all borders, which can also be used to underline text.
952                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
953                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
954                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
955                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
956                                 // Initialize a handler to display `mainWebView`.
957                                 Handler displayWebViewHandler = new Handler();
958
959                                 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
960                                 Runnable displayWebViewRunnable = () -> {
961                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
962                                     if (progressBar.getVisibility() == View.GONE) {
963                                         mainWebView.setVisibility(View.VISIBLE);
964                                     }
965                                 };