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