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