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