Add a Guide → Requests tab. https://redmine.stoutner.com/issues/301
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.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()`.
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
200     // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`.  They are also used in `onCreate()`.
201     public static List<String[]> resourceRequests;
202     public static String[] whiteListResultStringArray;
203     public final static int REQUEST_DISPOSITION = 0;
204     public final static int REQUEST_URL = 1;
205     public final static int REQUEST_BLOCKLIST = 2;
206     public final static int REQUEST_SUBLIST = 3;
207     public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
208     public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
209
210     public final static int REQUEST_DEFAULT = 0;
211     public final static int REQUEST_ALLOWED = 1;
212     public final static int REQUEST_THIRD_PARTY = 2;
213     public final static int REQUEST_BLOCKED = 3;
214
215     public final static int MAIN_WHITELIST = 1;
216     public final static int FINAL_WHITELIST = 2;
217     public final static int DOMAIN_WHITELIST = 3;
218     public final static int DOMAIN_INITIAL_WHITELIST = 4;
219     public final static int DOMAIN_FINAL_WHITELIST = 5;
220     public final static int THIRD_PARTY_WHITELIST = 6;
221     public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
222     public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
223
224     public final static int MAIN_BLACKLIST = 9;
225     public final static int INITIAL_BLACKLIST = 10;
226     public final static int FINAL_BLACKLIST = 11;
227     public final static int DOMAIN_BLACKLIST = 12;
228     public final static int DOMAIN_INITIAL_BLACKLIST = 13;
229     public final static int DOMAIN_FINAL_BLACKLIST = 14;
230     public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
231     public final static int THIRD_PARTY_BLACKLIST = 16;
232     public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
233     public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
234     public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
235     public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
236     public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
237     public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
238
239     // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
240     // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
241     public static boolean blockAllThirdPartyRequests;
242
243     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
244     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
245     public static String currentBookmarksFolder;
246
247     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
248     public static int domainSettingsDatabaseId;
249
250     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
251     public static String pinnedDomainSslIssuedToCNameString;
252     public static String pinnedDomainSslIssuedToONameString;
253     public static String pinnedDomainSslIssuedToUNameString;
254     public static String pinnedDomainSslIssuedByCNameString;
255     public static String pinnedDomainSslIssuedByONameString;
256     public static String pinnedDomainSslIssuedByUNameString;
257     public static Date pinnedDomainSslStartDate;
258     public static Date pinnedDomainSslEndDate;
259
260     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
261     public final static int UNRECOGNIZED_USER_AGENT = -1;
262     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
263     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
264     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
265     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
266     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
267
268
269     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
270     private ActionBar appBar;
271
272     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
273     private boolean navigatingHistory;
274
275     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
276     private Bitmap favoriteIconDefaultBitmap;
277
278     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
279     private DrawerLayout drawerLayout;
280
281     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
282     private CoordinatorLayout rootCoordinatorLayout;
283
284     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
285     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
286     private WebView mainWebView;
287
288     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
289     private FrameLayout fullScreenVideoFrameLayout;
290
291     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
292     private SwipeRefreshLayout swipeRefreshLayout;
293
294     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
295     private RelativeLayout urlAppBarRelativeLayout;
296
297     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
298     private ImageView favoriteIconImageView;
299
300     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
301     private CookieManager cookieManager;
302
303     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
304     private final Map<String, String> customHeaders = new HashMap<>();
305
306     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
307     private boolean javaScriptEnabled;
308
309     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
310     private boolean firstPartyCookiesEnabled;
311
312     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
313     private boolean thirdPartyCookiesEnabled;
314
315     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
316     private boolean domStorageEnabled;
317
318     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.  It can be removed once the minimum API >= 26.
319     private boolean saveFormDataEnabled;
320
321     // `nightMode` is used in `onCreate()` and  `applyDomainSettings()`.
322     private boolean nightMode;
323
324     // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
325     private boolean displayWebpageImagesBoolean;
326
327     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
328     private String homepage;
329
330     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
331     private String searchURL;
332
333     // The block list variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
334     private boolean easyListEnabled;
335     private boolean easyPrivacyEnabled;
336     private boolean fanboysAnnoyanceListEnabled;
337     private boolean fanboysSocialBlockingListEnabled;
338
339     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
340     private Runtime privacyBrowserRuntime;
341
342     // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
343     private boolean proxyThroughOrbot;
344
345     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
346     private boolean incognitoModeEnabled;
347
348     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
349     private boolean fullScreenBrowsingModeEnabled;
350
351     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
352     private boolean inFullScreenBrowsingMode;
353
354     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
355     private boolean hideSystemBarsOnFullscreen;
356
357     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
358     private boolean translucentNavigationBarOnFullscreen;
359
360     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
361     private boolean reapplyDomainSettingsOnRestart;
362
363     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
364     private boolean reapplyAppSettingsOnRestart;
365
366     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
367     private String currentDomainName;
368
369     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
370     private boolean ignorePinnedSslCertificate;
371
372     // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
373     private boolean waitingForOrbot;
374
375     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
376     private boolean domainSettingsApplied;
377
378     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
379     private int displayWebpageImagesInt;
380
381     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
382     private boolean onTheFlyDisplayImagesSet;
383
384     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
385     private String waitingForOrbotHTMLString;
386
387     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
388     private String privateDataDirectoryString;
389
390     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
391     private LinearLayout findOnPageLinearLayout;
392
393     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
394     private EditText findOnPageEditText;
395
396     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
397     private Menu mainMenu;
398
399     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
400     private ActionBarDrawerToggle drawerToggle;
401
402     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
403     private Toolbar supportAppBar;
404
405     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
406     private EditText urlTextBox;
407
408     // The color spans are used in `onCreate()` and `highlightUrlText()`.
409     private ForegroundColorSpan redColorSpan;
410     private ForegroundColorSpan initialGrayColorSpan;
411     private ForegroundColorSpan finalGrayColorSpan;
412
413     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
414     private SslErrorHandler sslErrorHandler;
415
416     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
417     private static HttpAuthHandler httpAuthHandler;
418
419     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
420     private InputMethodManager inputMethodManager;
421
422     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
423     private RelativeLayout mainWebViewRelativeLayout;
424
425     // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
426     private boolean urlIsLoading;
427
428     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
429     private boolean pinnedDomainSslCertificate;
430
431     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
432     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
433
434     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
435     private ListView bookmarksListView;
436
437     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
438     private TextView bookmarksTitleTextView;
439
440     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
441     private Cursor bookmarksCursor;
442
443     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
444     private CursorAdapter bookmarksCursorAdapter;
445
446     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
447     private String oldFolderNameString;
448
449     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
450     private ValueCallback<Uri[]> fileChooserCallback;
451
452     // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
453     private String downloadUrl;
454     private String downloadContentDisposition;
455     private long downloadContentLength;
456
457     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
458     private String downloadImageUrl;
459
460     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
461     private ArrayAdapter<CharSequence> userAgentNamesArray;
462     private String[] userAgentDataArray;
463
464     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
465     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
466     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
467
468     @Override
469     // 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.
470     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
471     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
472     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
473     @SuppressWarnings("deprecation")
474     protected void onCreate(Bundle savedInstanceState) {
475         // Get a handle for the shared preferences.
476         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
477
478         // Get the theme and screenshot preferences.
479         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
480         allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
481
482         // Disable screenshots if not allowed.
483         if (!allowScreenshots) {
484             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
485         }
486
487         // Set the activity theme.
488         if (darkTheme) {
489             setTheme(R.style.PrivacyBrowserDark);
490         } else {
491             setTheme(R.style.PrivacyBrowserLight);
492         }
493
494         // Run the default commands.
495         super.onCreate(savedInstanceState);
496
497         // Set the content view.
498         setContentView(R.layout.main_drawerlayout);
499
500         // Get a handle for `inputMethodManager`.
501         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
502
503         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
504         supportAppBar = findViewById(R.id.app_bar);
505         setSupportActionBar(supportAppBar);
506         appBar = getSupportActionBar();
507
508         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
509         assert appBar != null;
510
511         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
512         appBar.setCustomView(R.layout.url_app_bar);
513         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
514
515         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
516         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
517         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
518         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
519
520         // Get a handle for `urlTextBox`.
521         urlTextBox = findViewById(R.id.url_edittext);
522
523         // Remove the formatting from `urlTextBar` when the user is editing the text.
524         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
525             if (hasFocus) {  // The user is editing `urlTextBox`.
526                 // Remove the highlighting.
527                 urlTextBox.getText().removeSpan(redColorSpan);
528                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
529                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
530             } else {  // The user has stopped editing `urlTextBox`.
531                 // Reapply the highlighting.
532                 highlightUrlText();
533             }
534         });
535
536         // Set the go button on the keyboard to load the URL in `urlTextBox`.
537         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
538             // If the event is a key-down event on the `enter` button, load the URL.
539             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
540                 // Load the URL into the mainWebView and consume the event.
541                 try {
542                     loadUrlFromTextBox();
543                 } catch (UnsupportedEncodingException e) {
544                     e.printStackTrace();
545                 }
546                 // If the enter key was pressed, consume the event.
547                 return true;
548             } else {
549                 // If any other key was pressed, do not consume the event.
550                 return false;
551             }
552         });
553
554         // Set `waitingForOrbotHTMLString`.
555         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
556
557         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
558         currentDomainName = "";
559         orbotStatus = "unknown";
560         waitingForOrbot = false;
561
562         // Create an Orbot status `BroadcastReceiver`.
563         BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
564             @Override
565             public void onReceive(Context context, Intent intent) {
566                 // Store the content of the status message in `orbotStatus`.
567                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
568
569                 // If we are waiting on Orbot, load the website now that Orbot is connected.
570                 if (orbotStatus.equals("ON") && waitingForOrbot) {
571                     // Reset `waitingForOrbot`.
572                     waitingForOrbot = false;
573
574                     // Load `formattedUrlString
575                     loadUrl(formattedUrlString);
576                 }
577             }
578         };
579
580         // Register `orbotStatusBroadcastReceiver` on `this` context.
581         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
582
583         // Get handles for views that need to be accessed.
584         drawerLayout = findViewById(R.id.drawerlayout);
585         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
586         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
587         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
588         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
589         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
590         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
591         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
592         mainWebView = findViewById(R.id.main_webview);
593         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
594         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
595         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
596         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
597         favoriteIconImageView = findViewById(R.id.favorite_icon);
598
599         // 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.
600         if (darkTheme) {
601             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
602             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
603             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
604             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
605         } else {
606             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
607             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
608             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
609             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
610         }
611
612         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
613         launchBookmarksActivityFab.setOnClickListener(v -> {
614             // Create an intent to launch the bookmarks activity.
615             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
616
617             // Include the current folder with the `Intent`.
618             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
619
620             // Make it so.
621             startActivity(bookmarksIntent);
622         });
623
624         // Set the create new bookmark folder FAB to display an alert dialog.
625         createBookmarkFolderFab.setOnClickListener(v -> {
626             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
627             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
628             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
629         });
630
631         // Set the create new bookmark FAB to display an alert dialog.
632         createBookmarkFab.setOnClickListener(view -> {
633             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
634             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
635             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
636         });
637
638         // Create a double-tap listener to toggle full-screen mode.
639         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
640             // Override `onDoubleTap()`.  All other events are handled using the default settings.
641             @Override
642             public boolean onDoubleTap(MotionEvent event) {
643                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
644                     // Toggle `inFullScreenBrowsingMode`.
645                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
646
647                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
648                         // Hide the `appBar`.
649                         appBar.hide();
650
651                         // Hide the banner ad in the free flavor.
652                         if (BuildConfig.FLAVOR.contentEquals("free")) {
653                             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
654                             AdHelper.hideAd(findViewById(R.id.adview));
655                         }
656
657                         // Modify the system bars.
658                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
659                             // Remove the translucent overlays.
660                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
661
662                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
663                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
664
665                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
666                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
667                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
668                              */
669                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
670
671                             // Set `rootCoordinatorLayout` to fill the whole screen.
672                             rootCoordinatorLayout.setFitsSystemWindows(false);
673                         } else {  // Hide everything except the status and navigation bars.
674                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
675                             rootCoordinatorLayout.setFitsSystemWindows(false);
676
677                             // 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.
678                             if (translucentNavigationBarOnFullscreen) {
679                                 // Set the navigation bar to be translucent.
680                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
681                             }
682                         }
683                     } else {  // Switch to normal viewing mode.
684                         // Show the `appBar`.
685                         appBar.show();
686
687                         // Show the `BannerAd` in the free flavor.
688                         if (BuildConfig.FLAVOR.contentEquals("free")) {
689                             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
690                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
691                         }
692
693                         // Remove the translucent navigation bar flag if it is set.
694                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
695
696                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
697                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
698
699                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
700                         rootCoordinatorLayout.setSystemUiVisibility(0);
701
702                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
703                         rootCoordinatorLayout.setFitsSystemWindows(true);
704                     }
705
706                     // Consume the double-tap.
707                     return true;
708                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
709                     return false;
710                 }
711             }
712         });
713
714         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
715         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
716             // Call `performClick()` on the view, which is required for accessibility.
717             v.performClick();
718
719             // Send the `event` to `gestureDetector`.
720             return gestureDetector.onTouchEvent(event);
721         });
722
723         // Update `findOnPageCountTextView`.
724         mainWebView.setFindListener(new WebView.FindListener() {
725             // Get a handle for `findOnPageCountTextView`.
726             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
727
728             @Override
729             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
730                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
731                     // Set `findOnPageCountTextView` to `0/0`.
732                     findOnPageCountTextView.setText(R.string.zero_of_zero);
733                 } else if (isDoneCounting) {  // There are matches.
734                     // `activeMatchOrdinal` is zero-based.
735                     int activeMatch = activeMatchOrdinal + 1;
736
737                     // Build the match string.
738                     String matchString = activeMatch + "/" + numberOfMatches;
739
740                     // Set `findOnPageCountTextView`.
741                     findOnPageCountTextView.setText(matchString);
742                 }
743             }
744         });
745
746         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
747         findOnPageEditText.addTextChangedListener(new TextWatcher() {
748             @Override
749             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
750                 // Do nothing.
751             }
752
753             @Override
754             public void onTextChanged(CharSequence s, int start, int before, int count) {
755                 // Do nothing.
756             }
757
758             @Override
759             public void afterTextChanged(Editable s) {
760                 // Search for the text in `mainWebView`.
761                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
762             }
763         });
764
765         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
766         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
767             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
768                 // Hide the soft keyboard.  `0` indicates no additional flags.
769                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
770
771                 // Consume the event.
772                 return true;
773             } else {  // A different key was pressed.
774                 // Do not consume the event.
775                 return false;
776             }
777         });
778
779         // Implement swipe to refresh
780         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
781         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
782         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
783
784         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
785         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
786         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
787
788         // Listen for touches on the navigation menu.
789         final NavigationView navigationView = findViewById(R.id.navigationview);
790         navigationView.setNavigationItemSelectedListener(this);
791
792         // 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.
793         final Menu navigationMenu = navigationView.getMenu();
794         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
795         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
796         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
797         final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
798
799         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
800         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
801         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
802
803         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
804         currentBookmarksFolder = "";
805
806         // Load the home folder, which is `""` in the database.
807         loadBookmarksFolder();
808
809         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
810             // Convert the id from long to int to match the format of the bookmarks database.
811             int databaseID = (int) id;
812
813             // Get the bookmark cursor for this ID and move it to the first row.
814             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
815             bookmarkCursor.moveToFirst();
816
817             // Act upon the bookmark according to the type.
818             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
819                 // Store the new folder name in `currentBookmarksFolder`.
820                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
821
822                 // Load the new folder.
823                 loadBookmarksFolder();
824             } else {  // The selected bookmark is not a folder.
825                 // Load the bookmark URL.
826                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
827
828                 // Close the bookmarks drawer.
829                 drawerLayout.closeDrawer(GravityCompat.END);
830             }
831
832             // Close the `Cursor`.
833             bookmarkCursor.close();
834         });
835
836         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
837             // Convert the database ID from `long` to `int`.
838             int databaseId = (int) id;
839
840             // Find out if the selected bookmark is a folder.
841             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
842
843             if (isFolder) {
844                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
845                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
846
847                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
848                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
849                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
850             } else {
851                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
852                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
853                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
854             }
855
856             // Consume the event.
857             return true;
858         });
859
860         // The `DrawerListener` is used to update the Navigation Menu.
861         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
862             @Override
863             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
864             }
865
866             @Override
867             public void onDrawerOpened(@NonNull View drawerView) {
868             }
869
870             @Override
871             public void onDrawerClosed(@NonNull View drawerView) {
872             }
873
874             @Override
875             public void onDrawerStateChanged(int newState) {
876                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // The drawer is opening or closing.
877                     // Initialize a the blocked requests counter.
878                     int blockedRequests = 0;
879
880                     // Count the number of blocked requests.
881                     for (int i = 0; i < resourceRequests.size(); i++) {
882                         // Add the blocked requests.
883                         if (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_BLOCKED) {
884                             blockedRequests++;
885                         }
886
887                         // Add the third-party requests if they are blocked.
888                         if (blockAllThirdPartyRequests && (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_THIRD_PARTY)) {
889                             blockedRequests++;
890                         }
891                     }
892
893                     // Update the back, forward, history, and requests menu items.
894                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
895                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
896                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
897                     navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + blockedRequests);
898
899                     // Hide the keyboard (if displayed) so we can see the navigation menu.  `0` indicates no additional flags.
900                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
901
902                     // Clear the focus from `urlTextBox` if it has it.
903                     urlTextBox.clearFocus();
904                 }
905             }
906         });
907
908         // drawerToggle creates the hamburger icon at the start of the AppBar.
909         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
910
911         // Get a handle for the progress bar.
912         final ProgressBar progressBar = findViewById(R.id.progress_bar);
913
914         mainWebView.setWebChromeClient(new WebChromeClient() {
915             // Update the progress bar when a page is loading.
916             @Override
917             public void onProgressChanged(WebView view, int progress) {
918                 // Inject the night mode CSS if night mode is enabled.
919                 if (nightMode) {
920                     // `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
921                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
922                     // `border: none` removes all borders, which can also be used to underline text.
923                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
924                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
925                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
926                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
927                                 // Initialize a `Handler` to display `mainWebView`.
928                                 Handler displayWebViewHandler = new Handler();
929
930                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
931                                 Runnable displayWebViewRunnable = () -> {
932                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
933                                     if (progressBar.getVisibility() == View.GONE) {
934                                         mainWebView.setVisibility(View.VISIBLE);
935                                     }
936                                 };
937
938                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
939                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
940                             });
941                 }
942
943                 // Update the progress bar.
944                 progressBar.setProgress(progress);
945
946                 // Set the visibility of the progress bar.
947                 if (progress < 100) {
948                     // Show the progress bar.
949                     progressBar.setVisibility(View.VISIBLE);
950                 } else {
951                     // Hide the progress bar.
952                     progressBar.setVisibility(View.GONE);
953
954                     // Display `mainWebView` if night mode is disabled.
955                     // 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
956                     // currently enabled.
957                     if (!nightMode) {
958                         mainWebView.setVisibility(View.VISIBLE);
959                     }
960
961                     //Stop the swipe to refresh indicator if it is running
962                     swipeRefreshLayout.setRefreshing(false);
963                 }
964             }
965
966             // Set the favorite icon when it changes.
967             @Override
968             public void onReceivedIcon(WebView view, Bitmap icon) {
969                 // Only update the favorite icon if the website has finished loading.
970                 if (progressBar.getVisibility() == View.GONE) {
971                     // Save a copy of the favorite icon.
972                     favoriteIconBitmap = icon;
973
974                     // Place the favorite icon in the appBar.
975                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
976                 }
977             }
978
979             // Save a copy of the title when it changes.
980             @Override
981             public void onReceivedTitle(WebView view, String title) {
982                 // Save a copy of the title.
983                 webViewTitle = title;
984             }
985
986             // Enter full screen video.
987             @Override
988             public void onShowCustomView(View view, CustomViewCallback callback) {
989                 // Pause the ad if this is the free flavor.
990                 if (BuildConfig.FLAVOR.contentEquals("free")) {
991                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
992                     AdHelper.pauseAd(findViewById(R.id.adview));
993                 }
994
995                 // Remove the translucent overlays.
996                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
997
998                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
999                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1000
1001                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1002                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1003                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1004                  */
1005                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1006
1007                 // Set `rootCoordinatorLayout` to fill the entire screen.
1008                 rootCoordinatorLayout.setFitsSystemWindows(false);
1009
1010                 // Disable the sliding drawers.
1011                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1012
1013                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1014                 fullScreenVideoFrameLayout.addView(view);
1015                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1016             }
1017
1018             // Exit full screen video.
1019             @Override
1020             public void onHideCustomView() {
1021                 // Hide `fullScreenVideoFrameLayout`.
1022                 fullScreenVideoFrameLayout.removeAllViews();
1023                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1024
1025                 // Enable the sliding drawers.
1026                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1027
1028                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1029                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1030
1031                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
1032                 rootCoordinatorLayout.setFitsSystemWindows(true);
1033
1034                 // Show the ad if this is the free flavor.
1035                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1036                     // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1037                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1038                 }
1039             }
1040
1041             // Upload files.
1042             @Override
1043             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1044                 // Show the file chooser if the device is running API >= 21.
1045                 if (Build.VERSION.SDK_INT >= 21) {
1046                     // Store the file path callback.
1047                     fileChooserCallback = filePathCallback;
1048
1049                     // Create an intent to open a chooser based ont the file chooser parameters.
1050                     Intent fileChooserIntent = fileChooserParams.createIntent();
1051
1052                     // Open the file chooser.  Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1053                     startActivityForResult(fileChooserIntent, 0);
1054                 }
1055                 return true;
1056             }
1057         });
1058
1059         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
1060         registerForContextMenu(mainWebView);
1061
1062         // Allow the downloading of files.
1063         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1064             // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1065             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1066                 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1067
1068                 // Store the variables for future use by `onRequestPermissionsResult()`.
1069                 downloadUrl = url;
1070                 downloadContentDisposition = contentDisposition;
1071                 downloadContentLength = contentLength;
1072
1073                 // Show a dialog if the user has previously denied the permission.
1074                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
1075                     // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1076                     DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1077
1078                     // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
1079                     downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1080                 } else {  // Show the permission request directly.
1081                     // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
1082                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1083                 }
1084             } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1085                 // Get a handle for the download file alert dialog.
1086                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1087
1088                 // Show the download file alert dialog.
1089                 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1090             }
1091         });
1092
1093         // Allow pinch to zoom.
1094         mainWebView.getSettings().setBuiltInZoomControls(true);
1095
1096         // Hide zoom controls.
1097         mainWebView.getSettings().setDisplayZoomControls(false);
1098
1099         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
1100         mainWebView.getSettings().setUseWideViewPort(true);
1101
1102         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1103         mainWebView.getSettings().setLoadWithOverviewMode(true);
1104
1105         // Explicitly disable geolocation.
1106         mainWebView.getSettings().setGeolocationEnabled(false);
1107
1108         // Initialize cookieManager.
1109         cookieManager = CookieManager.getInstance();
1110
1111         // 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).
1112         customHeaders.put("X-Requested-With", "");
1113
1114         // Initialize the default preference values the first time the program is run.  `this` is the context.  `false` keeps this command from resetting any current preferences back to default.
1115         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1116
1117         // Get the intent that started the app.
1118         final Intent launchingIntent = getIntent();
1119
1120         // Extract the launching intent data as `launchingIntentUriData`.
1121         final Uri launchingIntentUriData = launchingIntent.getData();
1122
1123         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1124         if (launchingIntentUriData != null) {
1125             formattedUrlString = launchingIntentUriData.toString();
1126         }
1127
1128         // Get a handle for the `Runtime`.
1129         privacyBrowserRuntime = Runtime.getRuntime();
1130
1131         // Store the application's private data directory.
1132         privateDataDirectoryString = getApplicationInfo().dataDir;
1133         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1134
1135         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1136         inFullScreenBrowsingMode = false;
1137
1138         // Initialize the privacy settings variables.
1139         javaScriptEnabled = false;
1140         firstPartyCookiesEnabled = false;
1141         thirdPartyCookiesEnabled = false;
1142         domStorageEnabled = false;
1143         saveFormDataEnabled = false;  // Form data can be removed once the minimum API >= 26.
1144         nightMode = false;
1145
1146         // Initialize the WebView title.
1147         webViewTitle = getString(R.string.no_title);
1148
1149         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1150         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1151         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1152         assert favoriteIconBitmapDrawable != null;
1153         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1154
1155         // If the favorite icon is null, load the default.
1156         if (favoriteIconBitmap == null) {
1157             favoriteIconBitmap = favoriteIconDefaultBitmap;
1158         }
1159
1160         // Initialize the user agent array adapter and string array.
1161         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1162         userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1163
1164         // Apply the app settings from the shared preferences.
1165         applyAppSettings();
1166
1167         // Instantiate the block list helper.
1168         BlockListHelper blockListHelper = new BlockListHelper();
1169
1170         // Initialize the list of resource requests.
1171         resourceRequests = new ArrayList<>();
1172
1173         // Parse the block lists.
1174         final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1175         final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1176         final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1177         final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1178
1179         // Store the list versions.
1180         easyListVersion = easyList.get(0).get(0)[0];
1181         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1182         fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1183         fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1184
1185         mainWebView.setWebViewClient(new WebViewClient() {
1186             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1187             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1188             @SuppressWarnings("deprecation")
1189             @Override
1190             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1191                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
1192                     // Apply the domain settings for the new URL.  `applyDomainSettings` doesn't do anything if the domain has not changed.
1193                     applyDomainSettings(url, true, false);
1194
1195                     // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1196                     return false;
1197                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1198                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1199                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1200
1201                     // Parse the url and set it as the data for the intent.
1202                     emailIntent.setData(Uri.parse(url));
1203
1204                     // Open the email program in a new task instead of as part of Privacy Browser.
1205                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1206
1207                     // Make it so.
1208                     startActivity(emailIntent);
1209
1210                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1211                     return true;
1212                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1213                     // Open the dialer and load the phone number, but wait for the user to place the call.
1214                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1215
1216                     // Add the phone number to the intent.
1217                     dialIntent.setData(Uri.parse(url));
1218
1219                     // Open the dialer in a new task instead of as part of Privacy Browser.
1220                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1221
1222                     // Make it so.
1223                     startActivity(dialIntent);
1224
1225                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1226                     return true;
1227                 } else {  // Load a system chooser to select an app that can handle the URL.
1228                     // Open an app that can handle the URL.
1229                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1230
1231                     // Add the URL to the intent.
1232                     genericIntent.setData(Uri.parse(url));
1233
1234                     // List all apps that can handle the URL instead of just opening the first one.
1235                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1236
1237                     // Open the app in a new task instead of as part of Privacy Browser.
1238                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1239
1240                     // Start the app or display a snackbar if no app is available to handle the URL.
1241                     try {
1242                         startActivity(genericIntent);
1243                     } catch (ActivityNotFoundException exception) {
1244                         Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
1245                     }
1246
1247                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1248                     return true;
1249                 }
1250             }
1251
1252             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1253             @SuppressWarnings("deprecation")
1254             @Override
1255             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1256                 // Create an empty web resource response to be used if the resource request is blocked.
1257                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1258
1259                 // Reset `whiteListResultStringArray`.
1260                 whiteListResultStringArray = null;
1261
1262                 // Initialize the third party request tracker.
1263                 boolean isThirdPartyRequest = false;
1264
1265                 //
1266                 String currentDomain = "";
1267
1268                 // Nobody is happy when comparing null strings.
1269                 if (!(formattedUrlString == null) && !(url == null)) {
1270                     // Get the domain strings to URIs.
1271                     Uri currentDomainUri = Uri.parse(formattedUrlString);
1272                     Uri requestDomainUri = Uri.parse(url);
1273
1274                     // Get the domain host names.
1275                     String currentBaseDomain = currentDomainUri.getHost();
1276                     String requestBaseDomain = requestDomainUri.getHost();
1277
1278                     // Update the current domain variable.
1279                     currentDomain = currentBaseDomain;
1280
1281                     // Only compare the current base domain and the request base domain if neither is null.
1282                     if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1283                         // Determine the current base domain.
1284                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1285                             // Remove the first subdomain.
1286                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1287                         }
1288
1289                         // Determine the request base domain.
1290                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1291                             // Remove the first subdomain.
1292                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1293                         }
1294
1295                         // Update the third party request tracker.
1296                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1297                     }
1298                 }
1299
1300                 // Block third-party requests if enabled.
1301                 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1302                     // Add the request to the log.
1303                     resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1304
1305                     // Return an empty web resource response.
1306                     return emptyWebResourceResponse;
1307                 }
1308
1309                 // Check EasyList if it is enabled.
1310                 if (easyListEnabled) {
1311                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1312                         // The resource request was blocked.  Return an empty web resource response.
1313                         return emptyWebResourceResponse;
1314                     }
1315                 }
1316
1317                 // Check EasyPrivacy if it is enabled.
1318                 if (easyPrivacyEnabled) {
1319                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1320                         // The resource request was blocked.  Return an empty web resource response.
1321                         return emptyWebResourceResponse;
1322                     }
1323                 }
1324
1325                 // Check Fanboy’s Annoyance List if it is enabled.
1326                 if (fanboysAnnoyanceListEnabled) {
1327                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1328                         // The resource request was blocked.  Return an empty web resource response.
1329                         return emptyWebResourceResponse;
1330                     }
1331                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1332                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1333                         // The resource request was blocked.  Return an empty web resource response.
1334                         return emptyWebResourceResponse;
1335                     }
1336                 }
1337
1338                 // Add the request to the log because it hasn't been processed by any of the previous checks.
1339                 if (whiteListResultStringArray != null ) {  // The request was processed by a whitelist.
1340                     resourceRequests.add(whiteListResultStringArray);
1341                 } else {  // The request didn't match any blocklist entry.  Log it as a defult request.
1342                     resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1343                 }
1344
1345                 // The resource request has not been blocked.  `return null` loads the requested resource.
1346                 return null;
1347             }
1348
1349             // Handle HTTP authentication requests.
1350             @Override
1351             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1352                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1353                 httpAuthHandler = handler;
1354
1355                 // Display the HTTP authentication dialog.
1356                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1357                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1358             }
1359
1360             // Update the URL in urlTextBox when the page starts to load.
1361             @Override
1362             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1363                 // Reset the list of resource requests.
1364                 resourceRequests.clear();
1365
1366                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1367                 if (nightMode) {
1368                     mainWebView.setVisibility(View.INVISIBLE);
1369                 }
1370
1371                 // Hide the keyboard.  `0` indicates no additional flags.
1372                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1373
1374                 // Check to see if Privacy Browser is waiting on Orbot.
1375                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1376                     // 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.
1377                     formattedUrlString = url;
1378
1379                     // Display the formatted URL text.
1380                     urlTextBox.setText(formattedUrlString);
1381
1382                     // Apply text highlighting to `urlTextBox`.
1383                     highlightUrlText();
1384
1385                     // Apply any custom domain settings if the URL was loaded by navigating history.
1386                     if (navigatingHistory) {
1387                         // Reset `navigatingHistory`.
1388                         navigatingHistory = false;
1389
1390                         // Apply the domain settings.
1391                         applyDomainSettings(url, true, false);
1392                     }
1393
1394                     // 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.
1395                     urlIsLoading = true;
1396                 }
1397             }
1398
1399             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1400             @Override
1401             public void onPageFinished(WebView view, String url) {
1402                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1403                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1404                     cookieManager.flush();
1405                 }
1406
1407                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1408                 urlIsLoading = false;
1409
1410                 // Clear the cache and history if Incognito Mode is enabled.
1411                 if (incognitoModeEnabled) {
1412                     // Clear the cache.  `true` includes disk files.
1413                     mainWebView.clearCache(true);
1414
1415                     // Clear the back/forward history.
1416                     mainWebView.clearHistory();
1417
1418                     // Manually delete cache folders.
1419                     try {
1420                         // Delete the main cache directory.
1421                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1422
1423                         // Delete the secondary `Service Worker` cache directory.
1424                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1425                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1426                     } catch (IOException e) {
1427                         // Do nothing if an error is thrown.
1428                     }
1429                 }
1430
1431                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1432                 if (!waitingForOrbot) {
1433                     // Check to see if `WebView` has set `url` to be `about:blank`.
1434                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1435                         // Set `formattedUrlString` to `""`.
1436                         formattedUrlString = "";
1437
1438                         urlTextBox.setText(formattedUrlString);
1439
1440                         // Request focus for `urlTextBox`.
1441                         urlTextBox.requestFocus();
1442
1443                         // Display the keyboard.
1444                         inputMethodManager.showSoftInput(urlTextBox, 0);
1445
1446                         // Apply the domain settings.  This clears any settings from the previous domain.
1447                         applyDomainSettings(formattedUrlString, true, false);
1448                     } else {  // `WebView` has loaded a webpage.
1449                         // Set `formattedUrlString`.
1450                         formattedUrlString = url;
1451
1452                         // Only update `urlTextBox` if the user is not typing in it.
1453                         if (!urlTextBox.hasFocus()) {
1454                             // Display the formatted URL text.
1455                             urlTextBox.setText(formattedUrlString);
1456
1457                             // Apply text highlighting to `urlTextBox`.
1458                             highlightUrlText();
1459                         }
1460                     }
1461
1462                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1463                     sslCertificate = mainWebView.getCertificate();
1464
1465                     // 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.
1466                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1467                         // Initialize the current SSL certificate variables.
1468                         String currentWebsiteIssuedToCName = "";
1469                         String currentWebsiteIssuedToOName = "";
1470                         String currentWebsiteIssuedToUName = "";
1471                         String currentWebsiteIssuedByCName = "";
1472                         String currentWebsiteIssuedByOName = "";
1473                         String currentWebsiteIssuedByUName = "";
1474                         Date currentWebsiteSslStartDate = null;
1475                         Date currentWebsiteSslEndDate = null;
1476
1477
1478                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1479                         if (sslCertificate != null) {
1480                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1481                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1482                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1483                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1484                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1485                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1486                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1487                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1488                         }
1489
1490                         // 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`.
1491                         String currentWebsiteSslStartDateString = "";
1492                         String currentWebsiteSslEndDateString = "";
1493                         String pinnedDomainSslStartDateString = "";
1494                         String pinnedDomainSslEndDateString = "";
1495
1496                         // Convert the `Dates` to `Strings` if they are not `null`.
1497                         if (currentWebsiteSslStartDate != null) {
1498                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1499                         }
1500
1501                         if (currentWebsiteSslEndDate != null) {
1502                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1503                         }
1504
1505                         if (pinnedDomainSslStartDate != null) {
1506                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1507                         }
1508
1509                         if (pinnedDomainSslEndDate != null) {
1510                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1511                         }
1512
1513                         // Check to see if the pinned SSL certificate matches the current website certificate.
1514                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1515                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1516                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1517                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1518                             // The pinned SSL certificate doesn't match the current domain certificate.
1519                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1520                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1521                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1522                         }
1523                     }
1524                 }
1525             }
1526
1527             // Handle SSL Certificate errors.
1528             @Override
1529             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1530                 // Get the current website SSL certificate.
1531                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1532
1533                 // Extract the individual pieces of information from the current website SSL certificate.
1534                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1535                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1536                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1537                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1538                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1539                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1540                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1541                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1542
1543                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1544                 if (pinnedDomainSslCertificate &&
1545                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1546                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1547                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1548                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1549                     // An SSL certificate is pinned and matches the current domain certificate.
1550                     // Proceed to the website without displaying an error.
1551                     handler.proceed();
1552                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1553                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1554                     sslErrorHandler = handler;
1555
1556                     // Display the SSL error `AlertDialog`.
1557                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1558                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1559                 }
1560             }
1561         });
1562
1563         // Load the website if not waiting for Orbot to connect.
1564         if (!waitingForOrbot) {
1565             loadUrl(formattedUrlString);
1566         }
1567     }
1568
1569     @Override
1570     protected void onNewIntent(Intent intent) {
1571         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1572         setIntent(intent);
1573
1574         // Check to see if the intent contains a new URL.
1575         if (intent.getData() != null) {
1576             // Get the intent data.
1577             final Uri intentUriData = intent.getData();
1578
1579             // Load the website.
1580             loadUrl(intentUriData.toString());
1581
1582             // Close the navigation drawer if it is open.
1583             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1584                 drawerLayout.closeDrawer(GravityCompat.START);
1585             }
1586
1587             // Close the bookmarks drawer if it is open.
1588             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1589                 drawerLayout.closeDrawer(GravityCompat.END);
1590             }
1591
1592             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1593             mainWebView.requestFocus();
1594         }
1595     }
1596
1597     @Override
1598     public void onRestart() {
1599         // Run the default commands.
1600         super.onRestart();
1601
1602         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1603         if (proxyThroughOrbot) {
1604             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1605             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1606
1607             // Send the intent to the Orbot package.
1608             orbotIntent.setPackage("org.torproject.android");
1609
1610             // Make it so.
1611             sendBroadcast(orbotIntent);
1612         }
1613
1614         // Apply the app settings if returning from the Settings activity..
1615         if (reapplyAppSettingsOnRestart) {
1616             // Apply the app settings.
1617             applyAppSettings();
1618
1619             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1620             if (reloadOnRestart) {
1621                 // Reload `mainWebView`.
1622                 mainWebView.reload();
1623
1624                 // Reset `reloadOnRestartBoolean`.
1625                 reloadOnRestart = false;
1626             }
1627
1628             // Reset the return from settings flag.
1629             reapplyAppSettingsOnRestart = false;
1630         }
1631
1632         // Apply the domain settings if returning from the Domains activity.
1633         if (reapplyDomainSettingsOnRestart) {
1634             // Reapply the domain settings.
1635             applyDomainSettings(formattedUrlString, false, true);
1636
1637             // Reset `reapplyDomainSettingsOnRestart`.
1638             reapplyDomainSettingsOnRestart = false;
1639         }
1640
1641         // Load the URL on restart to apply changes to night mode.
1642         if (loadUrlOnRestart) {
1643             // Load the current `formattedUrlString`.
1644             loadUrl(formattedUrlString);
1645
1646             // Reset `loadUrlOnRestart.
1647             loadUrlOnRestart = false;
1648         }
1649
1650         // Update the bookmarks drawer if returning from the Bookmarks activity.
1651         if (restartFromBookmarksActivity) {
1652             // Close the bookmarks drawer.
1653             drawerLayout.closeDrawer(GravityCompat.END);
1654
1655             // Reload the bookmarks drawer.
1656             loadBookmarksFolder();
1657
1658             // Reset `restartFromBookmarksActivity`.
1659             restartFromBookmarksActivity = false;
1660         }
1661
1662         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1663         updatePrivacyIcons(true);
1664     }
1665
1666     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1667     @Override
1668     public void onResume() {
1669         // Run the default commands.
1670         super.onResume();
1671
1672         // Resume JavaScript (if enabled).
1673         mainWebView.resumeTimers();
1674
1675         // Resume `mainWebView`.
1676         mainWebView.onResume();
1677
1678         // Resume the adView for the free flavor.
1679         if (BuildConfig.FLAVOR.contentEquals("free")) {
1680             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1681             AdHelper.resumeAd(findViewById(R.id.adview));
1682         }
1683     }
1684
1685     @Override
1686     public void onPause() {
1687         // Pause `mainWebView`.
1688         mainWebView.onPause();
1689
1690         // Stop all JavaScript.
1691         mainWebView.pauseTimers();
1692
1693         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1694         if (BuildConfig.FLAVOR.contentEquals("free")) {
1695             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1696             AdHelper.pauseAd(findViewById(R.id.adview));
1697         }
1698
1699         super.onPause();
1700     }
1701
1702     @Override
1703     public boolean onCreateOptionsMenu(Menu menu) {
1704         // Inflate the menu; this adds items to the action bar if it is present.
1705         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1706
1707         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1708         mainMenu = menu;
1709
1710         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1711         updatePrivacyIcons(false);
1712
1713         // Get handles for the menu items.
1714         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1715         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1716         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1717         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1718         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1719         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1720         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1721
1722         // Only display third-party cookies if API >= 21
1723         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1724
1725         // Only display the form data menu items if the API < 26.
1726         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1727         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1728
1729         // Only show Ad Consent if this is the free flavor.
1730         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1731
1732         // Get the shared preference values.  `this` references the current context.
1733         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1734
1735         // 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.
1736         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1737             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1738             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1739             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1740         } else { //Do not display the additional icons.
1741             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1742             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1743             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1744         }
1745
1746         return true;
1747     }
1748
1749     @Override
1750     public boolean onPrepareOptionsMenu(Menu menu) {
1751         // Get handles for the menu items.
1752         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1753         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1754         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1755         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1756         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1757         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1758         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1759         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1760         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1761         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1762         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1763         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1764         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1765         MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1766         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1767         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1768         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1769
1770         // Set the text for the domain menu item.
1771         if (domainSettingsApplied) {
1772             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1773         } else {
1774             addOrEditDomain.setTitle(R.string.add_domain_settings);
1775         }
1776
1777         // Set the status of the menu item checkboxes.
1778         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1779         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1780         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1781         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1782         easyListMenuItem.setChecked(easyListEnabled);
1783         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1784         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1785         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1786         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1787         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1788         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1789
1790         // Enable third-party cookies if first-party cookies are enabled.
1791         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1792
1793         // Enable DOM Storage if JavaScript is enabled.
1794         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1795
1796         // Enable Clear Cookies if there are any.
1797         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1798
1799         // Get a count of the number of files in the Local Storage directory.
1800         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1801         int localStorageDirectoryNumberOfFiles = 0;
1802         if (localStorageDirectory.exists()) {
1803             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1804         }
1805
1806         // Get a count of the number of files in the IndexedDB directory.
1807         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1808         int indexedDBDirectoryNumberOfFiles = 0;
1809         if (indexedDBDirectory.exists()) {
1810             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1811         }
1812
1813         // Enable Clear DOM Storage if there is any.
1814         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1815
1816         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1817         if (Build.VERSION.SDK_INT < 26) {
1818             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1819             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1820         }
1821
1822         // Enable Clear Data if any of the submenu items are enabled.
1823         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1824
1825         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1826         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1827
1828         // Initialize font size variables.
1829         int fontSize = mainWebView.getSettings().getTextZoom();
1830         String fontSizeTitle;
1831         MenuItem selectedFontSizeMenuItem;
1832
1833         // Prepare the font size title and current size menu item.
1834         switch (fontSize) {
1835             case 25:
1836                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1837                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1838                 break;
1839
1840             case 50:
1841                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1842                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1843                 break;
1844
1845             case 75:
1846                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1847                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1848                 break;
1849
1850             case 100:
1851                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1852                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1853                 break;
1854
1855             case 125:
1856                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1857                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1858                 break;
1859
1860             case 150:
1861                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1862                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1863                 break;
1864
1865             case 175:
1866                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1867                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1868                 break;
1869
1870             case 200:
1871                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1872                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1873                 break;
1874
1875             default:
1876                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1877                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1878                 break;
1879         }
1880
1881         // Set the font size title and select the current size menu item.
1882         fontSizeMenuItem.setTitle(fontSizeTitle);
1883         selectedFontSizeMenuItem.setChecked(true);
1884
1885         // Run all the other default commands.
1886         super.onPrepareOptionsMenu(menu);
1887
1888         // Display the menu.
1889         return true;
1890     }
1891
1892     @Override
1893     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1894     @SuppressLint("SetJavaScriptEnabled")
1895     // removeAllCookies is deprecated, but it is required for API < 21.
1896     @SuppressWarnings("deprecation")
1897     public boolean onOptionsItemSelected(MenuItem menuItem) {
1898         // Get the selected menu item ID.
1899         int menuItemId = menuItem.getItemId();
1900
1901         // Set the commands that relate to the menu entries.
1902         switch (menuItemId) {
1903             case R.id.toggle_javascript:
1904                 // Switch the status of javaScriptEnabled.
1905                 javaScriptEnabled = !javaScriptEnabled;
1906
1907                 // Apply the new JavaScript status.
1908                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1909
1910                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1911                 updatePrivacyIcons(true);
1912
1913                 // Display a `Snackbar`.
1914                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1915                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1916                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1917                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1918                 } else {  // Privacy mode.
1919                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1920                 }
1921
1922                 // Reload the WebView.
1923                 mainWebView.reload();
1924                 return true;
1925
1926             case R.id.add_or_edit_domain:
1927                 if (domainSettingsApplied) {  // Edit the current domain settings.
1928                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1929                     reapplyDomainSettingsOnRestart = true;
1930                     currentDomainName = "";
1931
1932                     // Create an intent to launch the domains activity.
1933                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1934
1935                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1936                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1937                     domainsIntent.putExtra("closeOnBack", true);
1938
1939                     // Make it so.
1940                     startActivity(domainsIntent);
1941                 } else {  // Add a new domain.
1942                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1943                     reapplyDomainSettingsOnRestart = true;
1944                     currentDomainName = "";
1945
1946                     // Get the current domain
1947                     Uri currentUri = Uri.parse(formattedUrlString);
1948                     String currentDomain = currentUri.getHost();
1949
1950                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1951                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1952
1953                     // Create the domain and store the database ID.
1954                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1955
1956                     // Create an intent to launch the domains activity.
1957                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1958
1959                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1960                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1961                     domainsIntent.putExtra("closeOnBack", true);
1962
1963                     // Make it so.
1964                     startActivity(domainsIntent);
1965                 }
1966                 return true;
1967
1968             case R.id.toggle_first_party_cookies:
1969                 // Switch the status of firstPartyCookiesEnabled.
1970                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1971
1972                 // Update the menu checkbox.
1973                 menuItem.setChecked(firstPartyCookiesEnabled);
1974
1975                 // Apply the new cookie status.
1976                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1977
1978                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1979                 updatePrivacyIcons(true);
1980
1981                 // Display a `Snackbar`.
1982                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1983                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1984                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
1985                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1986                 } else {  // Privacy mode.
1987                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1988                 }
1989
1990                 // Reload the WebView.
1991                 mainWebView.reload();
1992                 return true;
1993
1994             case R.id.toggle_third_party_cookies:
1995                 if (Build.VERSION.SDK_INT >= 21) {
1996                     // Switch the status of thirdPartyCookiesEnabled.
1997                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1998
1999                     // Update the menu checkbox.
2000                     menuItem.setChecked(thirdPartyCookiesEnabled);
2001
2002                     // Apply the new cookie status.
2003                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2004
2005                     // Display a `Snackbar`.
2006                     if (thirdPartyCookiesEnabled) {
2007                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2008                     } else {
2009                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2010                     }
2011
2012                     // Reload the WebView.
2013                     mainWebView.reload();
2014                 } // Else do nothing because SDK < 21.
2015                 return true;
2016
2017             case R.id.toggle_dom_storage:
2018                 // Switch the status of domStorageEnabled.
2019                 domStorageEnabled = !domStorageEnabled;
2020
2021                 // Update the menu checkbox.
2022                 menuItem.setChecked(domStorageEnabled);
2023
2024                 // Apply the new DOM Storage status.
2025                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2026
2027                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2028                 updatePrivacyIcons(true);
2029
2030                 // Display a `Snackbar`.
2031                 if (domStorageEnabled) {
2032                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2033                 } else {
2034                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2035                 }
2036
2037                 // Reload the WebView.
2038                 mainWebView.reload();
2039                 return true;
2040
2041             // Form data can be removed once the minimum API >= 26.
2042             case R.id.toggle_save_form_data:
2043                 // Switch the status of saveFormDataEnabled.
2044                 saveFormDataEnabled = !saveFormDataEnabled;
2045
2046                 // Update the menu checkbox.
2047                 menuItem.setChecked(saveFormDataEnabled);
2048
2049                 // Apply the new form data status.
2050                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2051
2052                 // Display a `Snackbar`.
2053                 if (saveFormDataEnabled) {
2054                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2055                 } else {
2056                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2057                 }
2058
2059                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2060                 updatePrivacyIcons(true);
2061
2062                 // Reload the WebView.
2063                 mainWebView.reload();
2064                 return true;
2065
2066             case R.id.clear_cookies:
2067                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2068                         .setAction(R.string.undo, v -> {
2069                             // Do nothing because everything will be handled by `onDismissed()` below.
2070                         })
2071                         .addCallback(new Snackbar.Callback() {
2072                             @Override
2073                             public void onDismissed(Snackbar snackbar, int event) {
2074                                 switch (event) {
2075                                     // The user pushed the `Undo` button.
2076                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2077                                         // Do nothing.
2078                                         break;
2079
2080                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2081                                     default:
2082                                         // `cookieManager.removeAllCookie()` varies by SDK.
2083                                         if (Build.VERSION.SDK_INT < 21) {
2084                                             cookieManager.removeAllCookie();
2085                                         } else {
2086                                             // `null` indicates no callback.
2087                                             cookieManager.removeAllCookies(null);
2088                                         }
2089                                 }
2090                             }
2091                         })
2092                         .show();
2093                 return true;
2094
2095             case R.id.clear_dom_storage:
2096                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2097                         .setAction(R.string.undo, v -> {
2098                             // Do nothing because everything will be handled by `onDismissed()` below.
2099                         })
2100                         .addCallback(new Snackbar.Callback() {
2101                             @Override
2102                             public void onDismissed(Snackbar snackbar, int event) {
2103                                 switch (event) {
2104                                     // The user pushed the `Undo` button.
2105                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2106                                         // Do nothing.
2107                                         break;
2108
2109                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2110                                     default:
2111                                         // Delete the DOM Storage.
2112                                         WebStorage webStorage = WebStorage.getInstance();
2113                                         webStorage.deleteAllData();
2114
2115                                         // Manually delete the DOM storage files and directories.
2116                                         try {
2117                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2118                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2119
2120                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2121                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2122                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2123                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2124                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2125                                         } catch (IOException e) {
2126                                             // Do nothing if an error is thrown.
2127                                         }
2128                                 }
2129                             }
2130                         })
2131                         .show();
2132                 return true;
2133
2134             // Form data can be remove once the minimum API >= 26.
2135             case R.id.clear_form_data:
2136                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2137                         .setAction(R.string.undo, v -> {
2138                             // Do nothing because everything will be handled by `onDismissed()` below.
2139                         })
2140                         .addCallback(new Snackbar.Callback() {
2141                             @Override
2142                             public void onDismissed(Snackbar snackbar, int event) {
2143                                 switch (event) {
2144                                     // The user pushed the `Undo` button.
2145                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2146                                         // Do nothing.
2147                                         break;
2148
2149                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2150                                     default:
2151                                         // Delete the form data.
2152                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2153                                         mainWebViewDatabase.clearFormData();
2154                                 }
2155                             }
2156                         })
2157                         .show();
2158                 return true;
2159
2160             case R.id.font_size_twenty_five_percent:
2161                 mainWebView.getSettings().setTextZoom(25);
2162                 return true;
2163
2164             case R.id.font_size_fifty_percent:
2165                 mainWebView.getSettings().setTextZoom(50);
2166                 return true;
2167
2168             case R.id.font_size_seventy_five_percent:
2169                 mainWebView.getSettings().setTextZoom(75);
2170                 return true;
2171
2172             case R.id.font_size_one_hundred_percent:
2173                 mainWebView.getSettings().setTextZoom(100);
2174                 return true;
2175
2176             case R.id.font_size_one_hundred_twenty_five_percent:
2177                 mainWebView.getSettings().setTextZoom(125);
2178                 return true;
2179
2180             case R.id.font_size_one_hundred_fifty_percent:
2181                 mainWebView.getSettings().setTextZoom(150);
2182                 return true;
2183
2184             case R.id.font_size_one_hundred_seventy_five_percent:
2185                 mainWebView.getSettings().setTextZoom(175);
2186                 return true;
2187
2188             case R.id.font_size_two_hundred_percent:
2189                 mainWebView.getSettings().setTextZoom(200);
2190                 return true;
2191
2192             case R.id.swipe_to_refresh:
2193                 // Toggle swipe to refresh.
2194                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2195                 return true;
2196
2197             case R.id.display_images:
2198                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2199                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2200                     mainWebView.reload();
2201                 } else {  // Images are not currently loaded automatically.
2202                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2203                 }
2204
2205                 // Set `onTheFlyDisplayImagesSet`.
2206                 onTheFlyDisplayImagesSet = true;
2207                 return true;
2208
2209             case R.id.view_source:
2210                 // Launch the View Source activity.
2211                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2212                 startActivity(viewSourceIntent);
2213                 return true;
2214
2215             case R.id.easylist:
2216                 // Toggle the EasyList status.
2217                 easyListEnabled = !easyListEnabled;
2218
2219                 // Update the menu checkbox.
2220                 menuItem.setChecked(easyListEnabled);
2221
2222                 // Reload the main WebView.
2223                 mainWebView.reload();
2224                 return true;
2225
2226             case R.id.easyprivacy:
2227                 // Toggle the EasyPrivacy status.
2228                 easyPrivacyEnabled = !easyPrivacyEnabled;
2229
2230                 // Update the menu checkbox.
2231                 menuItem.setChecked(easyPrivacyEnabled);
2232
2233                 // Reload the main WebView.
2234                 mainWebView.reload();
2235                 return true;
2236
2237             case R.id.fanboys_annoyance_list:
2238                 // Toggle Fanboy's Annoyance List status.
2239                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2240
2241                 // Update the menu checkbox.
2242                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2243
2244                 // Update the staus of Fanboy's Social Blocking List.
2245                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2246                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2247
2248                 // Reload the main WebView.
2249                 mainWebView.reload();
2250                 return true;
2251
2252             case R.id.fanboys_social_blocking_list:
2253                 // Toggle Fanboy's Social Blocking List status.
2254                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2255
2256                 // Update the menu checkbox.
2257                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2258
2259                 // Reload the main WebView.
2260                 mainWebView.reload();
2261                 return true;
2262
2263             case R.id.block_all_third_party_requests:
2264                 //Toggle the third-party requests blocker status.
2265                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2266
2267                 // Update the menu checkbox.
2268                 menuItem.setChecked(blockAllThirdPartyRequests);
2269
2270                 // Reload the main WebView.
2271                 mainWebView.reload();
2272                 return true;
2273
2274             case R.id.share:
2275                 // Setup the share string.
2276                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2277
2278                 // Create the share intent.
2279                 Intent shareIntent = new Intent();
2280                 shareIntent.setAction(Intent.ACTION_SEND);
2281                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2282                 shareIntent.setType("text/plain");
2283
2284                 // Make it so.
2285                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2286                 return true;
2287
2288             case R.id.find_on_page:
2289                 // Hide the URL app bar.
2290                 supportAppBar.setVisibility(View.GONE);
2291
2292                 // Show the Find on Page `RelativeLayout`.
2293                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2294
2295                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2296                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2297                 findOnPageEditText.postDelayed(() -> {
2298                     // Set the focus on `findOnPageEditText`.
2299                     findOnPageEditText.requestFocus();
2300
2301                     // Display the keyboard.  `0` sets no input flags.
2302                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2303                 }, 200);
2304                 return true;
2305
2306             case R.id.print:
2307                 // Get a `PrintManager` instance.
2308                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2309
2310                 // Convert `mainWebView` to `printDocumentAdapter`.
2311                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2312
2313                 // Remove the lint error below that `printManager` might be `null`.
2314                 assert printManager != null;
2315
2316                 // Print the document.  The print attributes are `null`.
2317                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2318                 return true;
2319
2320             case R.id.add_to_homescreen:
2321                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2322                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2323                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2324
2325                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2326                 return true;
2327
2328             case R.id.refresh:
2329                 mainWebView.reload();
2330                 return true;
2331
2332             case R.id.ad_consent:
2333                 // Display the ad consent dialog.
2334                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2335                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2336                 return true;
2337
2338             default:
2339                 // Don't consume the event.
2340                 return super.onOptionsItemSelected(menuItem);
2341         }
2342     }
2343
2344     // removeAllCookies is deprecated, but it is required for API < 21.
2345     @SuppressWarnings("deprecation")
2346     @Override
2347     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2348         int menuItemId = menuItem.getItemId();
2349
2350         switch (menuItemId) {
2351             case R.id.home:
2352                 loadUrl(homepage);
2353                 break;
2354
2355             case R.id.back:
2356                 if (mainWebView.canGoBack()) {
2357                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2358                     formattedUrlString = "";
2359
2360                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2361                     navigatingHistory = true;
2362
2363                     // Load the previous website in the history.
2364                     mainWebView.goBack();
2365                 }
2366                 break;
2367
2368             case R.id.forward:
2369                 if (mainWebView.canGoForward()) {
2370                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2371                     formattedUrlString = "";
2372
2373                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2374                     navigatingHistory = true;
2375
2376                     // Load the next website in the history.
2377                     mainWebView.goForward();
2378                 }
2379                 break;
2380
2381             case R.id.history:
2382                 // Get the `WebBackForwardList`.
2383                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2384
2385                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2386                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2387                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2388                 break;
2389
2390             case R.id.requests:
2391                 // Launch the requests activity.
2392                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2393                 startActivity(requestsIntent);
2394                 break;
2395
2396             case R.id.downloads:
2397                 // Launch the system Download Manager.
2398                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2399
2400                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2401                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2402
2403                 startActivity(downloadManagerIntent);
2404                 break;
2405
2406             case R.id.domains:
2407                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2408                 reapplyDomainSettingsOnRestart = true;
2409                 currentDomainName = "";
2410
2411                 // Launch the domains activity.
2412                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2413                 startActivity(domainsIntent);
2414                 break;
2415
2416             case R.id.settings:
2417                 // Set the flag to reapply app settings on restart when returning from Settings.
2418                 reapplyAppSettingsOnRestart = true;
2419
2420                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2421                 reapplyDomainSettingsOnRestart = true;
2422                 currentDomainName = "";
2423
2424                 // Launch the settings activity.
2425                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2426                 startActivity(settingsIntent);
2427                 break;
2428
2429             case R.id.guide:
2430                 // Launch `GuideActivity`.
2431                 Intent guideIntent = new Intent(this, GuideActivity.class);
2432                 startActivity(guideIntent);
2433                 break;
2434
2435             case R.id.about:
2436                 // Launch `AboutActivity`.
2437                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2438                 startActivity(aboutIntent);
2439                 break;
2440
2441             case R.id.clearAndExit:
2442                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2443                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2444
2445                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2446
2447                 // Clear cookies.
2448                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2449                     // The command to remove cookies changed slightly in API 21.
2450                     if (Build.VERSION.SDK_INT >= 21) {
2451                         cookieManager.removeAllCookies(null);
2452                     } else {
2453                         cookieManager.removeAllCookie();
2454                     }
2455
2456                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2457                     try {
2458                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2459                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2460                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2461                     } catch (IOException e) {
2462                         // Do nothing if an error is thrown.
2463                     }
2464                 }
2465
2466                 // Clear DOM storage.
2467                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2468                     // Ask `WebStorage` to clear the DOM storage.
2469                     WebStorage webStorage = WebStorage.getInstance();
2470                     webStorage.deleteAllData();
2471
2472                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2473                     try {
2474                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2475                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2476
2477                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2478                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2479                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2480                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2481                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2482                     } catch (IOException e) {
2483                         // Do nothing if an error is thrown.
2484                     }
2485                 }
2486
2487                 // Clear form data if the API < 26.
2488                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2489                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2490                     webViewDatabase.clearFormData();
2491
2492                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2493                     try {
2494                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2495                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2496                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2497                     } catch (IOException e) {
2498                         // Do nothing if an error is thrown.
2499                     }
2500                 }
2501
2502                 // Clear the cache.
2503                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2504                     // `true` includes disk files.
2505                     mainWebView.clearCache(true);
2506
2507                     // Manually delete the cache directories.
2508                     try {
2509                         // Delete the main cache directory.
2510                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2511
2512                         // Delete the secondary `Service Worker` cache directory.
2513                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2514                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2515                     } catch (IOException e) {
2516                         // Do nothing if an error is thrown.
2517                     }
2518                 }
2519
2520                 // Clear SSL certificate preferences.
2521                 mainWebView.clearSslPreferences();
2522
2523                 // Clear the back/forward history.
2524                 mainWebView.clearHistory();
2525
2526                 // Clear `formattedUrlString`.
2527                 formattedUrlString = null;
2528
2529                 // Clear `customHeaders`.
2530                 customHeaders.clear();
2531
2532                 // Detach all views from `mainWebViewRelativeLayout`.
2533                 mainWebViewRelativeLayout.removeAllViews();
2534
2535                 // Destroy the internal state of `mainWebView`.
2536                 mainWebView.destroy();
2537
2538                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2539                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2540                 if (clearEverything) {
2541                     try {
2542                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2543                     } catch (IOException e) {
2544                         // Do nothing if an error is thrown.
2545                     }
2546                 }
2547
2548                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2549                 if (Build.VERSION.SDK_INT >= 21) {
2550                     finishAndRemoveTask();
2551                 } else {
2552                     finish();
2553                 }
2554
2555                 // Remove the terminated program from RAM.  The status code is `0`.
2556                 System.exit(0);
2557                 break;
2558         }
2559
2560         // Close the navigation drawer.
2561         drawerLayout.closeDrawer(GravityCompat.START);
2562         return true;
2563     }
2564
2565     @Override
2566     public void onPostCreate(Bundle savedInstanceState) {
2567         super.onPostCreate(savedInstanceState);
2568
2569         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2570         drawerToggle.syncState();
2571     }
2572
2573     @Override
2574     public void onConfigurationChanged(Configuration newConfig) {
2575         super.onConfigurationChanged(newConfig);
2576
2577         // Reload the ad for the free flavor if we are not in full screen mode.
2578         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2579             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2580             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2581         }
2582
2583         // `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:
2584         // https://code.google.com/p/android/issues/detail?id=20493#c8
2585         // ActivityCompat.invalidateOptionsMenu(this);
2586     }
2587
2588     @Override
2589     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2590         // Store the `HitTestResult`.
2591         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2592
2593         // Create strings.
2594         final String imageUrl;
2595         final String linkUrl;
2596
2597         // Get a handle for the `ClipboardManager`.
2598         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2599
2600         // Remove the lint errors below that `clipboardManager` might be `null`.
2601         assert clipboardManager != null;
2602
2603         switch (hitTestResult.getType()) {
2604             // `SRC_ANCHOR_TYPE` is a link.
2605             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2606                 // Get the target URL.
2607                 linkUrl = hitTestResult.getExtra();
2608
2609                 // Set the target URL as the title of the `ContextMenu`.
2610                 menu.setHeaderTitle(linkUrl);
2611
2612                 // Add a Load URL entry.
2613                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2614                     loadUrl(linkUrl);
2615                     return false;
2616                 });
2617
2618                 // Add a Copy URL entry.
2619                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2620                     // Save the link URL in a `ClipData`.
2621                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2622
2623                     // Set the `ClipData` as the clipboard's primary clip.
2624                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2625                     return false;
2626                 });
2627
2628                 // Add a Download URL entry.
2629                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2630                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2631                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2632                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2633
2634                         // Store the variables for future use by `onRequestPermissionsResult()`.
2635                         downloadUrl = linkUrl;
2636                         downloadContentDisposition = "none";
2637                         downloadContentLength = -1;
2638
2639                         // Show a dialog if the user has previously denied the permission.
2640                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2641                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2642                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2643
2644                             // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2645                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2646                         } else {  // Show the permission request directly.
2647                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2648                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2649                         }
2650                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2651                         // Get a handle for the download file alert dialog.
2652                         AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2653
2654                         // Show the download file alert dialog.
2655                         downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2656                     }
2657                     return false;
2658                 });
2659
2660                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2661                 menu.add(R.string.cancel);
2662                 break;
2663
2664             case WebView.HitTestResult.EMAIL_TYPE:
2665                 // Get the target URL.
2666                 linkUrl = hitTestResult.getExtra();
2667
2668                 // Set the target URL as the title of the `ContextMenu`.
2669                 menu.setHeaderTitle(linkUrl);
2670
2671                 // Add a `Write Email` entry.
2672                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2673                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2674                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2675
2676                     // Parse the url and set it as the data for the `Intent`.
2677                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2678
2679                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2680                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2681
2682                     // Make it so.
2683                     startActivity(emailIntent);
2684                     return false;
2685                 });
2686
2687                 // Add a `Copy Email Address` entry.
2688                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2689                     // Save the email address in a `ClipData`.
2690                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2691
2692                     // Set the `ClipData` as the clipboard's primary clip.
2693                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2694                     return false;
2695                 });
2696
2697                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2698                 menu.add(R.string.cancel);
2699                 break;
2700
2701             // `IMAGE_TYPE` is an image.
2702             case WebView.HitTestResult.IMAGE_TYPE:
2703                 // Get the image URL.
2704                 imageUrl = hitTestResult.getExtra();
2705
2706                 // Set the image URL as the title of the `ContextMenu`.
2707                 menu.setHeaderTitle(imageUrl);
2708
2709                 // Add a `View Image` entry.
2710                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2711                     loadUrl(imageUrl);
2712                     return false;
2713                 });
2714
2715                 // Add a `Download Image` entry.
2716                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2717                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2718                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2719                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2720
2721                         // Store the image URL for use by `onRequestPermissionResult()`.
2722                         downloadImageUrl = imageUrl;
2723
2724                         // Show a dialog if the user has previously denied the permission.
2725                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2726                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2727                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2728
2729                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2730                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2731                         } else {  // Show the permission request directly.
2732                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2733                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2734                         }
2735                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2736                         // Get a handle for the download image alert dialog.
2737                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2738
2739                         // Show the download image alert dialog.
2740                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2741                     }
2742                     return false;
2743                 });
2744
2745                 // Add a `Copy URL` entry.
2746                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2747                     // Save the image URL in a `ClipData`.
2748                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2749
2750                     // Set the `ClipData` as the clipboard's primary clip.
2751                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
2752                     return false;
2753                 });
2754
2755                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2756                 menu.add(R.string.cancel);
2757                 break;
2758
2759
2760             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2761             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2762                 // Get the image URL.
2763                 imageUrl = hitTestResult.getExtra();
2764
2765                 // Set the image URL as the title of the `ContextMenu`.
2766                 menu.setHeaderTitle(imageUrl);
2767
2768                 // Add a `View Image` entry.
2769                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2770                     loadUrl(imageUrl);
2771                     return false;
2772                 });
2773
2774                 // Add a `Download Image` entry.
2775                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2776                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2777                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2778                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2779
2780                         // Store the image URL for use by `onRequestPermissionResult()`.
2781                         downloadImageUrl = imageUrl;
2782
2783                         // Show a dialog if the user has previously denied the permission.
2784                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2785                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2786                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2787
2788                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2789                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2790                         } else {  // Show the permission request directly.
2791                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2792                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2793                         }
2794                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2795                         // Get a handle for the download image alert dialog.
2796                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2797
2798                         // Show the download image alert dialog.
2799                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2800                     }
2801                     return false;
2802                 });
2803
2804                 // Add a `Copy URL` entry.
2805                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2806                     // Save the image URL in a `ClipData`.
2807                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2808
2809                     // Set the `ClipData` as the clipboard's primary clip.
2810                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2811                     return false;
2812                 });
2813
2814                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2815                 menu.add(R.string.cancel);
2816                 break;
2817         }
2818     }
2819
2820     @Override
2821     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2822         // Get the `EditTexts` from the `dialogFragment`.
2823         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2824         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2825
2826         // Extract the strings from the `EditTexts`.
2827         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2828         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2829
2830         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2831         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2832         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2833         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2834
2835         // Display the new bookmark below the current items in the (0 indexed) list.
2836         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2837
2838         // Create the bookmark.
2839         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2840
2841         // Update `bookmarksCursor` with the current contents of this folder.
2842         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2843
2844         // Update the `ListView`.
2845         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2846
2847         // Scroll to the new bookmark.
2848         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2849     }
2850
2851     @Override
2852     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2853         // Get handles for the views in `dialogFragment`.
2854         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2855         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2856         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2857
2858         // Get new folder name string.
2859         String folderNameString = createFolderNameEditText.getText().toString();
2860
2861         // Get the new folder icon `Bitmap`.
2862         Bitmap folderIconBitmap;
2863         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2864             // Get the default folder icon and convert it to a `Bitmap`.
2865             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2866             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2867             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2868         } else {  // Use the `WebView` favorite icon.
2869             folderIconBitmap = favoriteIconBitmap;
2870         }
2871
2872         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2873         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2874         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2875         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2876
2877         // Move all the bookmarks down one in the display order.
2878         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2879             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2880             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2881         }
2882
2883         // Create the folder, which will be placed at the top of the `ListView`.
2884         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2885
2886         // Update `bookmarksCursor` with the current contents of this folder.
2887         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2888
2889         // Update the `ListView`.
2890         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2891
2892         // Scroll to the new folder.
2893         bookmarksListView.setSelection(0);
2894     }
2895
2896     @Override
2897     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2898         // Get the shortcut name.
2899         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2900         String shortcutNameString = shortcutNameEditText.getText().toString();
2901
2902         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
2903         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2904
2905         // Setup the shortcut intent.