]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Add an option to block all third-party requests. https://redmine.stoutner.com/issues/209
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.ActivityNotFoundException;
29 import android.content.BroadcastReceiver;
30 import android.content.ClipData;
31 import android.content.ClipboardManager;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageManager;
37 import android.content.res.Configuration;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Typeface;
42 import android.graphics.drawable.BitmapDrawable;
43 import android.graphics.drawable.Drawable;
44 import android.net.Uri;
45 import android.net.http.SslCertificate;
46 import android.net.http.SslError;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.Environment;
50 import android.os.Handler;
51 import android.preference.PreferenceManager;
52 import android.print.PrintDocumentAdapter;
53 import android.print.PrintManager;
54 import android.support.annotation.NonNull;
55 import android.support.design.widget.CoordinatorLayout;
56 import android.support.design.widget.FloatingActionButton;
57 import android.support.design.widget.NavigationView;
58 import android.support.design.widget.Snackbar;
59 import android.support.v4.app.ActivityCompat;
60 import android.support.v4.content.ContextCompat;
61 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
62 import android.support.v4.content.pm.ShortcutInfoCompat;
63 import android.support.v4.content.pm.ShortcutManagerCompat;
64 import android.support.v4.graphics.drawable.IconCompat;
65 import android.support.v4.view.GravityCompat;
66 import android.support.v4.widget.DrawerLayout;
67 import android.support.v4.widget.SwipeRefreshLayout;
68 import android.support.v7.app.ActionBar;
69 import android.support.v7.app.ActionBarDrawerToggle;
70 import android.support.v7.app.AppCompatActivity;
71 import android.support.v7.app.AppCompatDialogFragment;
72 import android.support.v7.widget.Toolbar;
73 import android.text.Editable;
74 import android.text.Spanned;
75 import android.text.TextWatcher;
76 import android.text.style.ForegroundColorSpan;
77 import android.util.Patterns;
78 import android.view.ContextMenu;
79 import android.view.GestureDetector;
80 import android.view.KeyEvent;
81 import android.view.Menu;
82 import android.view.MenuItem;
83 import android.view.MotionEvent;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.WindowManager;
87 import android.view.inputmethod.InputMethodManager;
88 import android.webkit.CookieManager;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.SslErrorHandler;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebBackForwardList;
93 import android.webkit.WebChromeClient;
94 import android.webkit.WebResourceResponse;
95 import android.webkit.WebStorage;
96 import android.webkit.WebView;
97 import android.webkit.WebViewClient;
98 import android.webkit.WebViewDatabase;
99 import android.widget.ArrayAdapter;
100 import android.widget.CursorAdapter;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.ImageView;
104 import android.widget.LinearLayout;
105 import android.widget.ListView;
106 import android.widget.ProgressBar;
107 import android.widget.RadioButton;
108 import android.widget.RelativeLayout;
109 import android.widget.TextView;
110
111 import com.stoutner.privacybrowser.BuildConfig;
112 import com.stoutner.privacybrowser.R;
113 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
122 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
123 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
124 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
125 import com.stoutner.privacybrowser.helpers.AdHelper;
126 import com.stoutner.privacybrowser.helpers.BlockListHelper;
127 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
128 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
130 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
131 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
132
133 import java.io.ByteArrayInputStream;
134 import java.io.ByteArrayOutputStream;
135 import java.io.File;
136 import java.io.IOException;
137 import java.io.UnsupportedEncodingException;
138 import java.net.MalformedURLException;
139 import java.net.URL;
140 import java.net.URLDecoder;
141 import java.net.URLEncoder;
142 import java.util.ArrayList;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map;
148 import java.util.Set;
149
150 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
151 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
152         CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
153         DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
154         HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
155         SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
156
157     // `darkTheme` is public static so it can be accessed from everywhere.
158     public static boolean darkTheme;
159
160     // `allowScreenshots` is public static so it can be accessed from everywhere.  It is also used in `onCreate()`.
161     public static boolean allowScreenshots;
162
163     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
164     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
165     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
166     public static Bitmap favoriteIconBitmap;
167
168     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
169     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
170     public static String formattedUrlString;
171
172     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
173     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
174     public static SslCertificate sslCertificate;
175
176     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`.
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                         applyDomainSettings(url, true, false);
1388                     }
1389
1390                     // 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.
1391                     urlIsLoading = true;
1392                 }
1393             }
1394
1395             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1396             @Override
1397             public void onPageFinished(WebView view, String url) {
1398                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1399                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1400                     cookieManager.flush();
1401                 }
1402
1403                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1404                 urlIsLoading = false;
1405
1406                 // Clear the cache and history if Incognito Mode is enabled.
1407                 if (incognitoModeEnabled) {
1408                     // Clear the cache.  `true` includes disk files.
1409                     mainWebView.clearCache(true);
1410
1411                     // Clear the back/forward history.
1412                     mainWebView.clearHistory();
1413
1414                     // Manually delete cache folders.
1415                     try {
1416                         // Delete the main cache directory.
1417                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1418
1419                         // Delete the secondary `Service Worker` cache directory.
1420                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1421                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1422                     } catch (IOException e) {
1423                         // Do nothing if an error is thrown.
1424                     }
1425                 }
1426
1427                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1428                 if (!waitingForOrbot) {
1429                     // Check to see if `WebView` has set `url` to be `about:blank`.
1430                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1431                         // Set `formattedUrlString` to `""`.
1432                         formattedUrlString = "";
1433
1434                         urlTextBox.setText(formattedUrlString);
1435
1436                         // Request focus for `urlTextBox`.
1437                         urlTextBox.requestFocus();
1438
1439                         // Display the keyboard.
1440                         inputMethodManager.showSoftInput(urlTextBox, 0);
1441
1442                         // Apply the domain settings.  This clears any settings from the previous domain.
1443                         applyDomainSettings(formattedUrlString, true, false);
1444                     } else {  // `WebView` has loaded a webpage.
1445                         // Set `formattedUrlString`.
1446                         formattedUrlString = url;
1447
1448                         // Only update `urlTextBox` if the user is not typing in it.
1449                         if (!urlTextBox.hasFocus()) {
1450                             // Display the formatted URL text.
1451                             urlTextBox.setText(formattedUrlString);
1452
1453                             // Apply text highlighting to `urlTextBox`.
1454                             highlightUrlText();
1455                         }
1456                     }
1457
1458                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1459                     sslCertificate = mainWebView.getCertificate();
1460
1461                     // 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.
1462                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1463                         // Initialize the current SSL certificate variables.
1464                         String currentWebsiteIssuedToCName = "";
1465                         String currentWebsiteIssuedToOName = "";
1466                         String currentWebsiteIssuedToUName = "";
1467                         String currentWebsiteIssuedByCName = "";
1468                         String currentWebsiteIssuedByOName = "";
1469                         String currentWebsiteIssuedByUName = "";
1470                         Date currentWebsiteSslStartDate = null;
1471                         Date currentWebsiteSslEndDate = null;
1472
1473
1474                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1475                         if (sslCertificate != null) {
1476                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1477                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1478                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1479                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1480                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1481                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1482                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1483                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1484                         }
1485
1486                         // 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`.
1487                         String currentWebsiteSslStartDateString = "";
1488                         String currentWebsiteSslEndDateString = "";
1489                         String pinnedDomainSslStartDateString = "";
1490                         String pinnedDomainSslEndDateString = "";
1491
1492                         // Convert the `Dates` to `Strings` if they are not `null`.
1493                         if (currentWebsiteSslStartDate != null) {
1494                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1495                         }
1496
1497                         if (currentWebsiteSslEndDate != null) {
1498                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1499                         }
1500
1501                         if (pinnedDomainSslStartDate != null) {
1502                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1503                         }
1504
1505                         if (pinnedDomainSslEndDate != null) {
1506                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1507                         }
1508
1509                         // Check to see if the pinned SSL certificate matches the current website certificate.
1510                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1511                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1512                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1513                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1514                             // The pinned SSL certificate doesn't match the current domain certificate.
1515                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1516                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1517                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1518                         }
1519                     }
1520                 }
1521             }
1522
1523             // Handle SSL Certificate errors.
1524             @Override
1525             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1526                 // Get the current website SSL certificate.
1527                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1528
1529                 // Extract the individual pieces of information from the current website SSL certificate.
1530                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1531                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1532                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1533                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1534                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1535                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1536                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1537                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1538
1539                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1540                 if (pinnedDomainSslCertificate &&
1541                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1542                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1543                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1544                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1545                     // An SSL certificate is pinned and matches the current domain certificate.
1546                     // Proceed to the website without displaying an error.
1547                     handler.proceed();
1548                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1549                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1550                     sslErrorHandler = handler;
1551
1552                     // Display the SSL error `AlertDialog`.
1553                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1554                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1555                 }
1556             }
1557         });
1558
1559         // Load the website if not waiting for Orbot to connect.
1560         if (!waitingForOrbot) {
1561             loadUrl(formattedUrlString);
1562         }
1563     }
1564
1565     @Override
1566     protected void onNewIntent(Intent intent) {
1567         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1568         setIntent(intent);
1569
1570         // Check to see if the intent contains a new URL.
1571         if (intent.getData() != null) {
1572             // Get the intent data.
1573             final Uri intentUriData = intent.getData();
1574
1575             // Load the website.
1576             loadUrl(intentUriData.toString());
1577
1578             // Close the navigation drawer if it is open.
1579             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1580                 drawerLayout.closeDrawer(GravityCompat.START);
1581             }
1582
1583             // Close the bookmarks drawer if it is open.
1584             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1585                 drawerLayout.closeDrawer(GravityCompat.END);
1586             }
1587
1588             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1589             mainWebView.requestFocus();
1590         }
1591     }
1592
1593     @Override
1594     public void onRestart() {
1595         // Run the default commands.
1596         super.onRestart();
1597
1598         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1599         if (proxyThroughOrbot) {
1600             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1601             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1602
1603             // Send the intent to the Orbot package.
1604             orbotIntent.setPackage("org.torproject.android");
1605
1606             // Make it so.
1607             sendBroadcast(orbotIntent);
1608         }
1609
1610         // Apply the app settings if returning from the Settings activity..
1611         if (reapplyAppSettingsOnRestart) {
1612             // Apply the app settings.
1613             applyAppSettings();
1614
1615             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1616             if (reloadOnRestart) {
1617                 // Reload `mainWebView`.
1618                 mainWebView.reload();
1619
1620                 // Reset `reloadOnRestartBoolean`.
1621                 reloadOnRestart = false;
1622             }
1623
1624             // Reset the return from settings flag.
1625             reapplyAppSettingsOnRestart = false;
1626         }
1627
1628         // Apply the domain settings if returning from the Domains activity.
1629         if (reapplyDomainSettingsOnRestart) {
1630             // Reapply the domain settings.
1631             applyDomainSettings(formattedUrlString, false, true);
1632
1633             // Reset `reapplyDomainSettingsOnRestart`.
1634             reapplyDomainSettingsOnRestart = false;
1635         }
1636
1637         // Load the URL on restart to apply changes to night mode.
1638         if (loadUrlOnRestart) {
1639             // Load the current `formattedUrlString`.
1640             loadUrl(formattedUrlString);
1641
1642             // Reset `loadUrlOnRestart.
1643             loadUrlOnRestart = false;
1644         }
1645
1646         // Update the bookmarks drawer if returning from the Bookmarks activity.
1647         if (restartFromBookmarksActivity) {
1648             // Close the bookmarks drawer.
1649             drawerLayout.closeDrawer(GravityCompat.END);
1650
1651             // Reload the bookmarks drawer.
1652             loadBookmarksFolder();
1653
1654             // Reset `restartFromBookmarksActivity`.
1655             restartFromBookmarksActivity = false;
1656         }
1657
1658         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1659         updatePrivacyIcons(true);
1660     }
1661
1662     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1663     @Override
1664     public void onResume() {
1665         // Run the default commands.
1666         super.onResume();
1667
1668         // Resume JavaScript (if enabled).
1669         mainWebView.resumeTimers();
1670
1671         // Resume `mainWebView`.
1672         mainWebView.onResume();
1673
1674         // Resume the adView for the free flavor.
1675         if (BuildConfig.FLAVOR.contentEquals("free")) {
1676             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1677             AdHelper.resumeAd(findViewById(R.id.adview));
1678         }
1679     }
1680
1681     @Override
1682     public void onPause() {
1683         // Pause `mainWebView`.
1684         mainWebView.onPause();
1685
1686         // Stop all JavaScript.
1687         mainWebView.pauseTimers();
1688
1689         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1690         if (BuildConfig.FLAVOR.contentEquals("free")) {
1691             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1692             AdHelper.pauseAd(findViewById(R.id.adview));
1693         }
1694
1695         super.onPause();
1696     }
1697
1698     @Override
1699     public boolean onCreateOptionsMenu(Menu menu) {
1700         // Inflate the menu; this adds items to the action bar if it is present.
1701         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1702
1703         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1704         mainMenu = menu;
1705
1706         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1707         updatePrivacyIcons(false);
1708
1709         // Get handles for the menu items.
1710         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1711         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1712         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1713         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1714         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1715         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1716         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1717
1718         // Only display third-party cookies if API >= 21
1719         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1720
1721         // Only display the form data menu items if the API < 26.
1722         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1723         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1724
1725         // Only show Ad Consent if this is the free flavor.
1726         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1727
1728         // Get the shared preference values.  `this` references the current context.
1729         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1730
1731         // 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.
1732         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1733             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1734             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1735             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1736         } else { //Do not display the additional icons.
1737             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1738             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1739             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1740         }
1741
1742         return true;
1743     }
1744
1745     @Override
1746     public boolean onPrepareOptionsMenu(Menu menu) {
1747         // Get handles for the menu items.
1748         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1749         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1750         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1751         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1752         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1753         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1754         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1755         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1756         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1757         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1758         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1759         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1760         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1761         MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1762         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1763         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1764         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1765
1766         // Set the text for the domain menu item.
1767         if (domainSettingsApplied) {
1768             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1769         } else {
1770             addOrEditDomain.setTitle(R.string.add_domain_settings);
1771         }
1772
1773         // Set the status of the menu item checkboxes.
1774         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1775         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1776         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1777         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1778         easyListMenuItem.setChecked(easyListEnabled);
1779         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1780         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1781         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1782         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1783         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1784         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1785
1786         // Enable third-party cookies if first-party cookies are enabled.
1787         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1788
1789         // Enable DOM Storage if JavaScript is enabled.
1790         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1791
1792         // Enable Clear Cookies if there are any.
1793         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1794
1795         // Get a count of the number of files in the Local Storage directory.
1796         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1797         int localStorageDirectoryNumberOfFiles = 0;
1798         if (localStorageDirectory.exists()) {
1799             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1800         }
1801
1802         // Get a count of the number of files in the IndexedDB directory.
1803         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1804         int indexedDBDirectoryNumberOfFiles = 0;
1805         if (indexedDBDirectory.exists()) {
1806             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1807         }
1808
1809         // Enable Clear DOM Storage if there is any.
1810         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1811
1812         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1813         if (Build.VERSION.SDK_INT < 26) {
1814             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1815             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1816         }
1817
1818         // Enable Clear Data if any of the submenu items are enabled.
1819         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1820
1821         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1822         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1823
1824         // Initialize font size variables.
1825         int fontSize = mainWebView.getSettings().getTextZoom();
1826         String fontSizeTitle;
1827         MenuItem selectedFontSizeMenuItem;
1828
1829         // Prepare the font size title and current size menu item.
1830         switch (fontSize) {
1831             case 25:
1832                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1833                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1834                 break;
1835
1836             case 50:
1837                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1838                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1839                 break;
1840
1841             case 75:
1842                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1843                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1844                 break;
1845
1846             case 100:
1847                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1848                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1849                 break;
1850
1851             case 125:
1852                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1853                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1854                 break;
1855
1856             case 150:
1857                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1858                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1859                 break;
1860
1861             case 175:
1862                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1863                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1864                 break;
1865
1866             case 200:
1867                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1868                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1869                 break;
1870
1871             default:
1872                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1873                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1874                 break;
1875         }
1876
1877         // Set the font size title and select the current size menu item.
1878         fontSizeMenuItem.setTitle(fontSizeTitle);
1879         selectedFontSizeMenuItem.setChecked(true);
1880
1881         // Run all the other default commands.
1882         super.onPrepareOptionsMenu(menu);
1883
1884         // Display the menu.
1885         return true;
1886     }
1887
1888     @Override
1889     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1890     @SuppressLint("SetJavaScriptEnabled")
1891     // removeAllCookies is deprecated, but it is required for API < 21.
1892     @SuppressWarnings("deprecation")
1893     public boolean onOptionsItemSelected(MenuItem menuItem) {
1894         // Get the selected menu item ID.
1895         int menuItemId = menuItem.getItemId();
1896
1897         // Set the commands that relate to the menu entries.
1898         switch (menuItemId) {
1899             case R.id.toggle_javascript:
1900                 // Switch the status of javaScriptEnabled.
1901                 javaScriptEnabled = !javaScriptEnabled;
1902
1903                 // Apply the new JavaScript status.
1904                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1905
1906                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1907                 updatePrivacyIcons(true);
1908
1909                 // Display a `Snackbar`.
1910                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1911                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1912                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1913                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1914                 } else {  // Privacy mode.
1915                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1916                 }
1917
1918                 // Reload the WebView.
1919                 mainWebView.reload();
1920                 return true;
1921
1922             case R.id.add_or_edit_domain:
1923                 if (domainSettingsApplied) {  // Edit the current domain settings.
1924                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1925                     reapplyDomainSettingsOnRestart = true;
1926                     currentDomainName = "";
1927
1928                     // Create an intent to launch the domains activity.
1929                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1930
1931                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1932                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1933                     domainsIntent.putExtra("closeOnBack", true);
1934
1935                     // Make it so.
1936                     startActivity(domainsIntent);
1937                 } else {  // Add a new domain.
1938                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1939                     reapplyDomainSettingsOnRestart = true;
1940                     currentDomainName = "";
1941
1942                     // Get the current domain
1943                     Uri currentUri = Uri.parse(formattedUrlString);
1944                     String currentDomain = currentUri.getHost();
1945
1946                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1947                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1948
1949                     // Create the domain and store the database ID.
1950                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1951
1952                     // Create an intent to launch the domains activity.
1953                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1954
1955                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1956                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1957                     domainsIntent.putExtra("closeOnBack", true);
1958
1959                     // Make it so.
1960                     startActivity(domainsIntent);
1961                 }
1962                 return true;
1963
1964             case R.id.toggle_first_party_cookies:
1965                 // Switch the status of firstPartyCookiesEnabled.
1966                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1967
1968                 // Update the menu checkbox.
1969                 menuItem.setChecked(firstPartyCookiesEnabled);
1970
1971                 // Apply the new cookie status.
1972                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1973
1974                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1975                 updatePrivacyIcons(true);
1976
1977                 // Display a `Snackbar`.
1978                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1979                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1980                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
1981                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1982                 } else {  // Privacy mode.
1983                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1984                 }
1985
1986                 // Reload the WebView.
1987                 mainWebView.reload();
1988                 return true;
1989
1990             case R.id.toggle_third_party_cookies:
1991                 if (Build.VERSION.SDK_INT >= 21) {
1992                     // Switch the status of thirdPartyCookiesEnabled.
1993                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1994
1995                     // Update the menu checkbox.
1996                     menuItem.setChecked(thirdPartyCookiesEnabled);
1997
1998                     // Apply the new cookie status.
1999                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2000
2001                     // Display a `Snackbar`.
2002                     if (thirdPartyCookiesEnabled) {
2003                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2004                     } else {
2005                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2006                     }
2007
2008                     // Reload the WebView.
2009                     mainWebView.reload();
2010                 } // Else do nothing because SDK < 21.
2011                 return true;
2012
2013             case R.id.toggle_dom_storage:
2014                 // Switch the status of domStorageEnabled.
2015                 domStorageEnabled = !domStorageEnabled;
2016
2017                 // Update the menu checkbox.
2018                 menuItem.setChecked(domStorageEnabled);
2019
2020                 // Apply the new DOM Storage status.
2021                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2022
2023                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2024                 updatePrivacyIcons(true);
2025
2026                 // Display a `Snackbar`.
2027                 if (domStorageEnabled) {
2028                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2029                 } else {
2030                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2031                 }
2032
2033                 // Reload the WebView.
2034                 mainWebView.reload();
2035                 return true;
2036
2037             // Form data can be removed once the minimum API >= 26.
2038             case R.id.toggle_save_form_data:
2039                 // Switch the status of saveFormDataEnabled.
2040                 saveFormDataEnabled = !saveFormDataEnabled;
2041
2042                 // Update the menu checkbox.
2043                 menuItem.setChecked(saveFormDataEnabled);
2044
2045                 // Apply the new form data status.
2046                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2047
2048                 // Display a `Snackbar`.
2049                 if (saveFormDataEnabled) {
2050                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2051                 } else {
2052                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2053                 }
2054
2055                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2056                 updatePrivacyIcons(true);
2057
2058                 // Reload the WebView.
2059                 mainWebView.reload();
2060                 return true;
2061
2062             case R.id.clear_cookies:
2063                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2064                         .setAction(R.string.undo, v -> {
2065                             // Do nothing because everything will be handled by `onDismissed()` below.
2066                         })
2067                         .addCallback(new Snackbar.Callback() {
2068                             @Override
2069                             public void onDismissed(Snackbar snackbar, int event) {
2070                                 switch (event) {
2071                                     // The user pushed the `Undo` button.
2072                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2073                                         // Do nothing.
2074                                         break;
2075
2076                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2077                                     default:
2078                                         // `cookieManager.removeAllCookie()` varies by SDK.
2079                                         if (Build.VERSION.SDK_INT < 21) {
2080                                             cookieManager.removeAllCookie();
2081                                         } else {
2082                                             // `null` indicates no callback.
2083                                             cookieManager.removeAllCookies(null);
2084                                         }
2085                                 }
2086                             }
2087                         })
2088                         .show();
2089                 return true;
2090
2091             case R.id.clear_dom_storage:
2092                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2093                         .setAction(R.string.undo, v -> {
2094                             // Do nothing because everything will be handled by `onDismissed()` below.
2095                         })
2096                         .addCallback(new Snackbar.Callback() {
2097                             @Override
2098                             public void onDismissed(Snackbar snackbar, int event) {
2099                                 switch (event) {
2100                                     // The user pushed the `Undo` button.
2101                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2102                                         // Do nothing.
2103                                         break;
2104
2105                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2106                                     default:
2107                                         // Delete the DOM Storage.
2108                                         WebStorage webStorage = WebStorage.getInstance();
2109                                         webStorage.deleteAllData();
2110
2111                                         // Manually delete the DOM storage files and directories.
2112                                         try {
2113                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2114                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2115
2116                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2117                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2118                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2119                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2120                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2121                                         } catch (IOException e) {
2122                                             // Do nothing if an error is thrown.
2123                                         }
2124                                 }
2125                             }
2126                         })
2127                         .show();
2128                 return true;
2129
2130             // Form data can be remove once the minimum API >= 26.
2131             case R.id.clear_form_data:
2132                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2133                         .setAction(R.string.undo, v -> {
2134                             // Do nothing because everything will be handled by `onDismissed()` below.
2135                         })
2136                         .addCallback(new Snackbar.Callback() {
2137                             @Override
2138                             public void onDismissed(Snackbar snackbar, int event) {
2139                                 switch (event) {
2140                                     // The user pushed the `Undo` button.
2141                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2142                                         // Do nothing.
2143                                         break;
2144
2145                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2146                                     default:
2147                                         // Delete the form data.
2148                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2149                                         mainWebViewDatabase.clearFormData();
2150                                 }
2151                             }
2152                         })
2153                         .show();
2154                 return true;
2155
2156             case R.id.font_size_twenty_five_percent:
2157                 mainWebView.getSettings().setTextZoom(25);
2158                 return true;
2159
2160             case R.id.font_size_fifty_percent:
2161                 mainWebView.getSettings().setTextZoom(50);
2162                 return true;
2163
2164             case R.id.font_size_seventy_five_percent:
2165                 mainWebView.getSettings().setTextZoom(75);
2166                 return true;
2167
2168             case R.id.font_size_one_hundred_percent:
2169                 mainWebView.getSettings().setTextZoom(100);
2170                 return true;
2171
2172             case R.id.font_size_one_hundred_twenty_five_percent:
2173                 mainWebView.getSettings().setTextZoom(125);
2174                 return true;
2175
2176             case R.id.font_size_one_hundred_fifty_percent:
2177                 mainWebView.getSettings().setTextZoom(150);
2178                 return true;
2179
2180             case R.id.font_size_one_hundred_seventy_five_percent:
2181                 mainWebView.getSettings().setTextZoom(175);
2182                 return true;
2183
2184             case R.id.font_size_two_hundred_percent:
2185                 mainWebView.getSettings().setTextZoom(200);
2186                 return true;
2187
2188             case R.id.swipe_to_refresh:
2189                 // Toggle swipe to refresh.
2190                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2191                 return true;
2192
2193             case R.id.display_images:
2194                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2195                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2196                     mainWebView.reload();
2197                 } else {  // Images are not currently loaded automatically.
2198                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2199                 }
2200
2201                 // Set `onTheFlyDisplayImagesSet`.
2202                 onTheFlyDisplayImagesSet = true;
2203                 return true;
2204
2205             case R.id.view_source:
2206                 // Launch the View Source activity.
2207                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2208                 startActivity(viewSourceIntent);
2209                 return true;
2210
2211             case R.id.easylist:
2212                 // Toggle the EasyList status.
2213                 easyListEnabled = !easyListEnabled;
2214
2215                 // Update the menu checkbox.
2216                 menuItem.setChecked(easyListEnabled);
2217
2218                 // Reload the main WebView.
2219                 mainWebView.reload();
2220                 return true;
2221
2222             case R.id.easyprivacy:
2223                 // Toggle the EasyPrivacy status.
2224                 easyPrivacyEnabled = !easyPrivacyEnabled;
2225
2226                 // Update the menu checkbox.
2227                 menuItem.setChecked(easyPrivacyEnabled);
2228
2229                 // Reload the main WebView.
2230                 mainWebView.reload();
2231                 return true;
2232
2233             case R.id.fanboys_annoyance_list:
2234                 // Toggle Fanboy's Annoyance List status.
2235                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2236
2237                 // Update the menu checkbox.
2238                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2239
2240                 // Update the staus of Fanboy's Social Blocking List.
2241                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2242                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2243
2244                 // Reload the main WebView.
2245                 mainWebView.reload();
2246                 return true;
2247
2248             case R.id.fanboys_social_blocking_list:
2249                 // Toggle Fanboy's Social Blocking List status.
2250                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2251
2252                 // Update the menu checkbox.
2253                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2254
2255                 // Reload the main WebView.
2256                 mainWebView.reload();
2257                 return true;
2258
2259             case R.id.block_all_third_party_requests:
2260                 //Toggle the third-party requests blocker status.
2261                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2262
2263                 // Update the menu checkbox.
2264                 menuItem.setChecked(blockAllThirdPartyRequests);
2265
2266                 // Reload the main WebView.
2267                 mainWebView.reload();
2268                 return true;
2269
2270             case R.id.share:
2271                 // Setup the share string.
2272                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2273
2274                 // Create the share intent.
2275                 Intent shareIntent = new Intent();
2276                 shareIntent.setAction(Intent.ACTION_SEND);
2277                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2278                 shareIntent.setType("text/plain");
2279
2280                 // Make it so.
2281                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2282                 return true;
2283
2284             case R.id.find_on_page:
2285                 // Hide the URL app bar.
2286                 supportAppBar.setVisibility(View.GONE);
2287
2288                 // Show the Find on Page `RelativeLayout`.
2289                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2290
2291                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2292                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2293                 findOnPageEditText.postDelayed(() -> {
2294                     // Set the focus on `findOnPageEditText`.
2295                     findOnPageEditText.requestFocus();
2296
2297                     // Display the keyboard.  `0` sets no input flags.
2298                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2299                 }, 200);
2300                 return true;
2301
2302             case R.id.print:
2303                 // Get a `PrintManager` instance.
2304                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2305
2306                 // Convert `mainWebView` to `printDocumentAdapter`.
2307                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2308
2309                 // Remove the lint error below that `printManager` might be `null`.
2310                 assert printManager != null;
2311
2312                 // Print the document.  The print attributes are `null`.
2313                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2314                 return true;
2315
2316             case R.id.add_to_homescreen:
2317                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2318                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2319                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2320
2321                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2322                 return true;
2323
2324             case R.id.refresh:
2325                 mainWebView.reload();
2326                 return true;
2327
2328             case R.id.ad_consent:
2329                 // Display the ad consent dialog.
2330                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2331                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2332                 return true;
2333
2334             default:
2335                 // Don't consume the event.
2336                 return super.onOptionsItemSelected(menuItem);
2337         }
2338     }
2339
2340     // removeAllCookies is deprecated, but it is required for API < 21.
2341     @SuppressWarnings("deprecation")
2342     @Override
2343     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2344         int menuItemId = menuItem.getItemId();
2345
2346         switch (menuItemId) {
2347             case R.id.home:
2348                 loadUrl(homepage);
2349                 break;
2350
2351             case R.id.back:
2352                 if (mainWebView.canGoBack()) {
2353                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2354                     navigatingHistory = true;
2355
2356                     // Load the previous website in the history.
2357                     mainWebView.goBack();
2358                 }
2359                 break;
2360
2361             case R.id.forward:
2362                 if (mainWebView.canGoForward()) {
2363                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2364                     navigatingHistory = true;
2365
2366                     // Load the next website in the history.
2367                     mainWebView.goForward();
2368                 }
2369                 break;
2370
2371             case R.id.history:
2372                 // Get the `WebBackForwardList`.
2373                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2374
2375                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2376                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2377                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2378                 break;
2379
2380             case R.id.requests:
2381                 // Launch the requests activity.
2382                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2383                 startActivity(requestsIntent);
2384                 break;
2385
2386             case R.id.downloads:
2387                 // Launch the system Download Manager.
2388                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2389
2390                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2391                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2392
2393                 startActivity(downloadManagerIntent);
2394                 break;
2395
2396             case R.id.domains:
2397                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2398                 reapplyDomainSettingsOnRestart = true;
2399                 currentDomainName = "";
2400
2401                 // Launch the domains activity.
2402                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2403                 startActivity(domainsIntent);
2404                 break;
2405
2406             case R.id.settings:
2407                 // Set the flag to reapply app settings on restart when returning from Settings.
2408                 reapplyAppSettingsOnRestart = true;
2409
2410                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2411                 reapplyDomainSettingsOnRestart = true;
2412                 currentDomainName = "";
2413
2414                 // Launch the settings activity.
2415                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2416                 startActivity(settingsIntent);
2417                 break;
2418
2419             case R.id.guide:
2420                 // Launch `GuideActivity`.
2421                 Intent guideIntent = new Intent(this, GuideActivity.class);
2422                 startActivity(guideIntent);
2423                 break;
2424
2425             case R.id.about:
2426                 // Launch `AboutActivity`.
2427                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2428                 startActivity(aboutIntent);
2429                 break;
2430
2431             case R.id.clearAndExit:
2432                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2433                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2434
2435                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2436
2437                 // Clear cookies.
2438                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2439                     // The command to remove cookies changed slightly in API 21.
2440                     if (Build.VERSION.SDK_INT >= 21) {
2441                         cookieManager.removeAllCookies(null);
2442                     } else {
2443                         cookieManager.removeAllCookie();
2444                     }
2445
2446                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2447                     try {
2448                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2449                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2450                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2451                     } catch (IOException e) {
2452                         // Do nothing if an error is thrown.
2453                     }
2454                 }
2455
2456                 // Clear DOM storage.
2457                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2458                     // Ask `WebStorage` to clear the DOM storage.
2459                     WebStorage webStorage = WebStorage.getInstance();
2460                     webStorage.deleteAllData();
2461
2462                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2463                     try {
2464                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2465                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2466
2467                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2468                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2469                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2470                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2471                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2472                     } catch (IOException e) {
2473                         // Do nothing if an error is thrown.
2474                     }
2475                 }
2476
2477                 // Clear form data if the API < 26.
2478                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2479                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2480                     webViewDatabase.clearFormData();
2481
2482                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2483                     try {
2484                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2485                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2486                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2487                     } catch (IOException e) {
2488                         // Do nothing if an error is thrown.
2489                     }
2490                 }
2491
2492                 // Clear the cache.
2493                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2494                     // `true` includes disk files.
2495                     mainWebView.clearCache(true);
2496
2497                     // Manually delete the cache directories.
2498                     try {
2499                         // Delete the main cache directory.
2500                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2501
2502                         // Delete the secondary `Service Worker` cache directory.
2503                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2504                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2505                     } catch (IOException e) {
2506                         // Do nothing if an error is thrown.
2507                     }
2508                 }
2509
2510                 // Clear SSL certificate preferences.
2511                 mainWebView.clearSslPreferences();
2512
2513                 // Clear the back/forward history.
2514                 mainWebView.clearHistory();
2515
2516                 // Clear `formattedUrlString`.
2517                 formattedUrlString = null;
2518
2519                 // Clear `customHeaders`.
2520                 customHeaders.clear();
2521
2522                 // Detach all views from `mainWebViewRelativeLayout`.
2523                 mainWebViewRelativeLayout.removeAllViews();
2524
2525                 // Destroy the internal state of `mainWebView`.
2526                 mainWebView.destroy();
2527
2528                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2529                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2530                 if (clearEverything) {
2531                     try {
2532                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2533                     } catch (IOException e) {
2534                         // Do nothing if an error is thrown.
2535                     }
2536                 }
2537
2538                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2539                 if (Build.VERSION.SDK_INT >= 21) {
2540                     finishAndRemoveTask();
2541                 } else {
2542                     finish();
2543                 }
2544
2545                 // Remove the terminated program from RAM.  The status code is `0`.
2546                 System.exit(0);
2547                 break;
2548         }
2549
2550         // Close the navigation drawer.
2551         drawerLayout.closeDrawer(GravityCompat.START);
2552         return true;
2553     }
2554
2555     @Override
2556     public void onPostCreate(Bundle savedInstanceState) {
2557         super.onPostCreate(savedInstanceState);
2558
2559         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2560         drawerToggle.syncState();
2561     }
2562
2563     @Override
2564     public void onConfigurationChanged(Configuration newConfig) {
2565         super.onConfigurationChanged(newConfig);
2566
2567         // Reload the ad for the free flavor if we are not in full screen mode.
2568         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2569             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2570             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2571         }
2572
2573         // `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:
2574         // https://code.google.com/p/android/issues/detail?id=20493#c8
2575         // ActivityCompat.invalidateOptionsMenu(this);
2576     }
2577
2578     @Override
2579     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2580         // Store the `HitTestResult`.
2581         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2582
2583         // Create strings.
2584         final String imageUrl;
2585         final String linkUrl;
2586
2587         // Get a handle for the `ClipboardManager`.
2588         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2589
2590         // Remove the lint errors below that `clipboardManager` might be `null`.
2591         assert clipboardManager != null;
2592
2593         switch (hitTestResult.getType()) {
2594             // `SRC_ANCHOR_TYPE` is a link.
2595             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2596                 // Get the target URL.
2597                 linkUrl = hitTestResult.getExtra();
2598
2599                 // Set the target URL as the title of the `ContextMenu`.
2600                 menu.setHeaderTitle(linkUrl);
2601
2602                 // Add a Load URL entry.
2603                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2604                     loadUrl(linkUrl);
2605                     return false;
2606                 });
2607
2608                 // Add a Copy URL entry.
2609                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2610                     // Save the link URL in a `ClipData`.
2611                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2612
2613                     // Set the `ClipData` as the clipboard's primary clip.
2614                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2615                     return false;
2616                 });
2617
2618                 // Add a Download URL entry.
2619                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2620                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2621                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2622                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2623
2624                         // Store the variables for future use by `onRequestPermissionsResult()`.
2625                         downloadUrl = linkUrl;
2626                         downloadContentDisposition = "none";
2627                         downloadContentLength = -1;
2628
2629                         // Show a dialog if the user has previously denied the permission.
2630                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2631                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2632                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2633
2634                             // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2635                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2636                         } else {  // Show the permission request directly.
2637                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2638                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2639                         }
2640                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2641                         // Get a handle for the download file alert dialog.
2642                         AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2643
2644                         // Show the download file alert dialog.
2645                         downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2646                     }
2647                     return false;
2648                 });
2649
2650                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2651                 menu.add(R.string.cancel);
2652                 break;
2653
2654             case WebView.HitTestResult.EMAIL_TYPE:
2655                 // Get the target URL.
2656                 linkUrl = hitTestResult.getExtra();
2657
2658                 // Set the target URL as the title of the `ContextMenu`.
2659                 menu.setHeaderTitle(linkUrl);
2660
2661                 // Add a `Write Email` entry.
2662                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2663                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2664                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2665
2666                     // Parse the url and set it as the data for the `Intent`.
2667                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2668
2669                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2670                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2671
2672                     // Make it so.
2673                     startActivity(emailIntent);
2674                     return false;
2675                 });
2676
2677                 // Add a `Copy Email Address` entry.
2678                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2679                     // Save the email address in a `ClipData`.
2680                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2681
2682                     // Set the `ClipData` as the clipboard's primary clip.
2683                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2684                     return false;
2685                 });
2686
2687                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2688                 menu.add(R.string.cancel);
2689                 break;
2690
2691             // `IMAGE_TYPE` is an image.
2692             case WebView.HitTestResult.IMAGE_TYPE:
2693                 // Get the image URL.
2694                 imageUrl = hitTestResult.getExtra();
2695
2696                 // Set the image URL as the title of the `ContextMenu`.
2697                 menu.setHeaderTitle(imageUrl);
2698
2699                 // Add a `View Image` entry.
2700                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2701                     loadUrl(imageUrl);
2702                     return false;
2703                 });
2704
2705                 // Add a `Download Image` entry.
2706                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2707                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2708                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2709                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2710
2711                         // Store the image URL for use by `onRequestPermissionResult()`.
2712                         downloadImageUrl = imageUrl;
2713
2714                         // Show a dialog if the user has previously denied the permission.
2715                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2716                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2717                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2718
2719                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2720                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2721                         } else {  // Show the permission request directly.
2722                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2723                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2724                         }
2725                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2726                         // Get a handle for the download image alert dialog.
2727                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2728
2729                         // Show the download image alert dialog.
2730                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2731                     }
2732                     return false;
2733                 });
2734
2735                 // Add a `Copy URL` entry.
2736                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2737                     // Save the image URL in a `ClipData`.
2738                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2739
2740                     // Set the `ClipData` as the clipboard's primary clip.
2741                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
2742                     return false;
2743                 });
2744
2745                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2746                 menu.add(R.string.cancel);
2747                 break;
2748
2749
2750             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2751             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2752                 // Get the image URL.
2753                 imageUrl = hitTestResult.getExtra();
2754
2755                 // Set the image URL as the title of the `ContextMenu`.
2756                 menu.setHeaderTitle(imageUrl);
2757
2758                 // Add a `View Image` entry.
2759                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2760                     loadUrl(imageUrl);
2761                     return false;
2762                 });
2763
2764                 // Add a `Download Image` entry.
2765                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2766                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2767                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2768                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2769
2770                         // Store the image URL for use by `onRequestPermissionResult()`.
2771                         downloadImageUrl = imageUrl;
2772
2773                         // Show a dialog if the user has previously denied the permission.
2774                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2775                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2776                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2777
2778                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2779                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2780                         } else {  // Show the permission request directly.
2781                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2782                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2783                         }
2784                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2785                         // Get a handle for the download image alert dialog.
2786                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2787
2788                         // Show the download image alert dialog.
2789                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2790                     }
2791                     return false;
2792                 });
2793
2794                 // Add a `Copy URL` entry.
2795                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2796                     // Save the image URL in a `ClipData`.
2797                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2798
2799                     // Set the `ClipData` as the clipboard's primary clip.
2800                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2801                     return false;
2802                 });
2803
2804                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2805                 menu.add(R.string.cancel);
2806                 break;
2807         }
2808     }
2809
2810     @Override
2811     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2812         // Get the `EditTexts` from the `dialogFragment`.
2813         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2814         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2815
2816         // Extract the strings from the `EditTexts`.
2817         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2818         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2819
2820         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2821         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2822         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2823         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2824
2825         // Display the new bookmark below the current items in the (0 indexed) list.
2826         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2827
2828         // Create the bookmark.
2829         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2830
2831         // Update `bookmarksCursor` with the current contents of this folder.
2832         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2833
2834         // Update the `ListView`.
2835         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2836
2837         // Scroll to the new bookmark.
2838         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2839     }
2840
2841     @Override
2842     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2843         // Get handles for the views in `dialogFragment`.
2844         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2845         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2846         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2847
2848         // Get new folder name string.
2849         String folderNameString = createFolderNameEditText.getText().toString();
2850
2851         // Get the new folder icon `Bitmap`.
2852         Bitmap folderIconBitmap;
2853         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2854             // Get the default folder icon and convert it to a `Bitmap`.
2855             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2856             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2857             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2858         } else {  // Use the `WebView` favorite icon.
2859             folderIconBitmap = favoriteIconBitmap;
2860         }
2861
2862         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2863         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2864         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2865         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2866
2867         // Move all the bookmarks down one in the display order.
2868         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2869             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2870             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2871         }
2872
2873         // Create the folder, which will be placed at the top of the `ListView`.
2874         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2875
2876         // Update `bookmarksCursor` with the current contents of this folder.
2877         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2878
2879         // Update the `ListView`.
2880         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2881
2882         // Scroll to the new folder.
2883         bookmarksListView.setSelection(0);
2884     }
2885
2886     @Override
2887     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2888         // Get the shortcut name.
2889         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2890         String shortcutNameString = shortcutNameEditText.getText().toString();
2891
2892         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
2893         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2894
2895         // Setup the shortcut intent.
2896         Intent shortcutIntent = new Intent();
2897         shortcutIntent.setAction(Intent.ACTION_VIEW);
2898         shortcutIntent.setData(Uri.parse(formattedUrlString));
2899
2900         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
2901         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2902
2903         // Add the required fields to the shortcut info builder.
2904         shortcutInfoBuilder.setIcon(favoriteIcon);
2905         shortcutInfoBuilder.setIntent(shortcutIntent);
2906         shortcutInfoBuilder.setShortLabel(shortcutNameString);
2907
2908         // Request the pin.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2909         ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2910     }
2911
2912     @Override
2913     public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2914         switch (downloadType) {
2915             case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2916                 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2917                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2918                 break;
2919
2920             case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2921                 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2922                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2923                 break;
2924         }
2925     }
2926
2927     @Override
2928     public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2929         switch (requestCode) {
2930             case DOWNLOAD_FILE_REQUEST_CODE:
2931                 // Show the download file alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
2932                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2933
2934                 // On API 23, displaying the fragment must be delayed or the app will crash.
2935                 if (Build.VERSION.SDK_INT == 23) {
2936                     new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2937                 } else {
2938                     downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2939                 }
2940
2941                 // Reset the download variables.
2942                 downloadUrl = "";
2943                 downloadContentDisposition = "";
2944                 downloadContentLength = 0;
2945                 break;
2946
2947             case DOWNLOAD_IMAGE_REQUEST_CODE:
2948                 // Show the download image alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
2949                 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2950
2951                 // On API 23, displaying the fragment must be delayed or the app will crash.
2952                 if (Build.VERSION.SDK_INT == 23) {
2953                     new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2954                 } else {
2955                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2956                 }
2957
2958                 // Reset the image URL variable.
2959                 downloadImageUrl = "";
2960                 break;
2961         }
2962     }
2963
2964     @Override
2965     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2966         // Download the image if it has an HTTP or HTTPS URI.
2967         if (imageUrl.startsWith("http")) {
2968             // Get a handle for the system `DOWNLOAD_SERVICE`.
2969             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2970
2971             // Parse `imageUrl`.
2972             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2973
2974             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
2975             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2976             if (firstPartyCookiesEnabled) {
2977                 // Get the cookies for `imageUrl`.
2978                 String cookies = cookieManager.getCookie(imageUrl);
2979
2980                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2981                 downloadRequest.addRequestHeader("Cookie", cookies);
2982             }
2983
2984             // Get the file name from the dialog fragment.
2985             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2986             String imageName = downloadImageNameEditText.getText().toString();
2987
2988             // Specify the download location.
2989             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
2990                 // Download to the public download directory.
2991                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2992             } else {  // External write permission denied.
2993                 // Download to the app's external download directory.
2994                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2995             }
2996
2997             // Allow `MediaScanner` to index the download if it is a media file.
2998             downloadRequest.allowScanningByMediaScanner();
2999
3000             // Add the URL as the description for the download.
3001             downloadRequest.setDescription(imageUrl);
3002
3003             // Show the download notification after the download is completed.
3004             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3005
3006             // Remove the lint warning below that `downloadManager` might be `null`.
3007             assert downloadManager != null;
3008
3009             // Initiate the download.
3010             downloadManager.enqueue(downloadRequest);
3011         } else {  // The image is not an HTTP or HTTPS URI.
3012             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3013         }
3014     }
3015
3016     @Override
3017     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3018         // Download the file if it has an HTTP or HTTPS URI.
3019         if (downloadUrl.startsWith("http")) {
3020             // Get a handle for the system `DOWNLOAD_SERVICE`.
3021             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3022
3023             // Parse `downloadUrl`.
3024             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3025
3026             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
3027             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3028             if (firstPartyCookiesEnabled) {
3029                 // Get the cookies for `downloadUrl`.
3030                 String cookies = cookieManager.getCookie(downloadUrl);
3031
3032                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3033                 downloadRequest.addRequestHeader("Cookie", cookies);
3034             }
3035
3036             // Get the file name from the dialog fragment.
3037             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3038             String fileName = downloadFileNameEditText.getText().toString();
3039
3040             // Specify the download location.
3041             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3042                 // Download to the public download directory.
3043                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3044             } else {  // External write permission denied.
3045                 // Download to the app's external download directory.
3046                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3047             }
3048
3049             // Allow `MediaScanner` to index the download if it is a media file.
3050             downloadRequest.allowScanningByMediaScanner();
3051
3052             // Add the URL as the description for the download.
3053             downloadRequest.setDescription(downloadUrl);
3054
3055             // Show the download notification after the download is completed.
3056             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3057
3058             // Remove the lint warning below that `downloadManager` might be `null`.
3059             assert downloadManager != null;
3060
3061             // Initiate the download.
3062             downloadManager.enqueue(downloadRequest);
3063         } else {  // The download is not an HTTP or HTTPS URI.
3064             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3065         }
3066     }
3067
3068     @Override
3069     public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3070         // Get handles for the views from `dialogFragment`.
3071         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3072         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3073         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3074
3075         // Store the bookmark strings.
3076         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3077         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3078
3079         // Update the bookmark.
3080         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
3081             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3082         } else {  // Update the bookmark using the `WebView` favorite icon.
3083             // Convert the favorite icon to a byte array.  `0` is for lossless compression (the only option for a PNG).
3084             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3085             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3086             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3087
3088             //  Update the bookmark and the favorite icon.
3089             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3090         }
3091
3092         // Update `bookmarksCursor` with the current contents of this folder.
3093         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3094
3095         // Update the `ListView`.
3096         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3097     }
3098
3099     @Override
3100     public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3101         // Get handles for the views from `dialogFragment`.
3102         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3103         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3104         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3105         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3106
3107         // Get the new folder name.
3108         String newFolderNameString = editFolderNameEditText.getText().toString();
3109
3110         // Check if the favorite icon has changed.
3111         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
3112             // Update the name in the database.
3113             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3114         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
3115             // Get the new folder icon `Bitmap`.
3116             Bitmap folderIconBitmap;
3117             if (defaultFolderIconRadioButton.isChecked()) {
3118                 // Get the default folder icon and convert it to a `Bitmap`.
3119                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3120                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3121                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3122             } else {  // Use the `WebView` favorite icon.
3123                 folderIconBitmap = favoriteIconBitmap;
3124             }
3125
3126             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3127             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3128             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3129             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3130
3131             // Update the folder icon in the database.
3132             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3133         } else {  // The folder icon and the name have changed.
3134             // Get the new folder icon `Bitmap`.
3135             Bitmap folderIconBitmap;
3136             if (defaultFolderIconRadioButton.isChecked()) {
3137                 // Get the default folder icon and convert it to a `Bitmap`.
3138                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3139                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3140                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3141             } else {  // Use the `WebView` favorite icon.
3142                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3143             }
3144
3145             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3146             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3147             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3148             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3149
3150             // Update the folder name and icon in the database.
3151             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3152         }
3153
3154         // Update `bookmarksCursor` with the current contents of this folder.
3155         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3156
3157         // Update the `ListView`.
3158         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3159     }
3160
3161     @Override
3162     public void onHttpAuthenticationCancel() {
3163         // Cancel the `HttpAuthHandler`.
3164         httpAuthHandler.cancel();
3165     }
3166
3167     @Override
3168     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3169         // Get handles for the `EditTexts`.
3170         EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3171         EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3172
3173         // Proceed with the HTTP authentication.
3174         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3175     }
3176
3177     public void viewSslCertificate(View view) {
3178         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3179         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3180         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3181     }
3182
3183     @Override
3184     public void onSslErrorCancel() {
3185         sslErrorHandler.cancel();
3186     }
3187
3188     @Override
3189     public void onSslErrorProceed() {
3190         sslErrorHandler.proceed();
3191     }
3192
3193     @Override
3194     public void onSslMismatchBack() {
3195         if (mainWebView.canGoBack()) {  // There is a back page in the history.
3196             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3197             navigatingHistory = true;
3198
3199             // Go back.
3200             mainWebView.goBack();
3201         } else {  // There are no pages to go back to.
3202             // Load a blank page
3203             loadUrl("");
3204         }
3205     }
3206
3207     @Override
3208     public void onSslMismatchProceed() {
3209         // Do not check the pinned SSL certificate for this domain again until the domain changes.
3210         ignorePinnedSslCertificate = true;
3211     }
3212
3213     @Override
3214     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3215         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3216         navigatingHistory = true;
3217
3218         // Load the history entry.
3219         mainWebView.goBackOrForward(moveBackOrForwardSteps);
3220     }
3221
3222     @Override
3223     public void onClearHistory() {
3224         // Clear the history.
3225         mainWebView.clearHistory();
3226     }
3227
3228     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3229     @Override
3230     public void onBackPressed() {
3231         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
3232             // Close the navigation drawer.
3233             drawerLayout.closeDrawer(GravityCompat.START);
3234         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
3235             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
3236                 // close the bookmarks drawer.
3237                 drawerLayout.closeDrawer(GravityCompat.END);
3238             } else {  // A subfolder is displayed.
3239                 // Place the former parent folder in `currentFolder`.
3240                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3241
3242                 // Load the new folder.
3243                 loadBookmarksFolder();
3244             }
3245
3246         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
3247             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3248             navigatingHistory = true;
3249
3250             // Go back.
3251             mainWebView.goBack();
3252         } else {  // There isn't anything to do in Privacy Browser.
3253             // Pass `onBackPressed()` to the system.
3254             super.onBackPressed();
3255         }
3256     }
3257
3258     // Process the results of an upload file chooser.  Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
3259     @Override
3260     public void onActivityResult(int requestCode, int resultCode, Intent data) {
3261         // File uploads only work on API >= 21.
3262         if (Build.VERSION.SDK_INT >= 21) {
3263             // Pass the file to the WebView.
3264             fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3265         }
3266     }
3267
3268     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3269         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
3270         String unformattedUrlString = urlTextBox.getText().toString().trim();
3271
3272         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
3273         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3274             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
3275             if (!unformattedUrlString.startsWith("http")) {
3276                 unformattedUrlString = "http://" + unformattedUrlString;
3277             }
3278
3279             // Initialize `unformattedUrl`.
3280             URL unformattedUrl = null;
3281
3282             // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
3283             try {
3284                 unformattedUrl = new URL(unformattedUrlString);
3285             } catch (MalformedURLException e) {
3286                 e.printStackTrace();
3287             }
3288
3289             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3290             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3291             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3292             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3293             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3294             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3295
3296             // Build the URI.
3297             Uri.Builder formattedUri = new Uri.Builder();
3298             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3299
3300             // Decode `formattedUri` as a `String` in `UTF-8`.
3301             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3302         } else if (unformattedUrlString.isEmpty()){  // Load a blank web site.
3303             // Load a blank string.
3304             formattedUrlString = "";
3305         } else {  // Search for the contents of the URL box.
3306             // Sanitize the search input and convert it to a search.
3307             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3308
3309             // Add the base search URL.
3310             formattedUrlString = searchURL + encodedUrlString;
3311         }
3312
3313         // Clear the focus from the URL text box.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3314         urlTextBox.clearFocus();
3315
3316         // Make it so.
3317         loadUrl(formattedUrlString);
3318     }
3319
3320     private void loadUrl(String url) {// Apply any custom domain settings.
3321         // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3322         formattedUrlString = url;
3323
3324         // Apply the domain settings.
3325         applyDomainSettings(url, true, false);
3326
3327         // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3328         urlIsLoading = true;
3329
3330         // Load the URL.
3331         mainWebView.loadUrl(url, customHeaders);
3332     }
3333
3334     public void findPreviousOnPage(View view) {
3335         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
3336         mainWebView.findNext(false);
3337     }
3338
3339     public void findNextOnPage(View view) {
3340         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3341         mainWebView.findNext(true);
3342     }
3343
3344     public void closeFindOnPage(View view) {
3345         // Delete the contents of `find_on_page_edittext`.
3346         findOnPageEditText.setText(null);
3347
3348         // Clear the highlighted phrases.
3349         mainWebView.clearMatches();
3350
3351         // Hide the Find on Page `RelativeLayout`.
3352         findOnPageLinearLayout.setVisibility(View.GONE);
3353
3354         // Show the URL app bar.
3355         supportAppBar.setVisibility(View.VISIBLE);
3356
3357         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
3358         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3359     }
3360
3361     private void applyAppSettings() {
3362         // Get a handle for the shared preferences.
3363         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3364
3365         // Store the values from the shared preferences in variables.
3366         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3367         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3368         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3369         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3370         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3371         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3372         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3373         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3374         proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3375         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3376         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3377         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3378         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3379
3380         // Set the homepage, search, and proxy options.
3381         if (proxyThroughOrbot) {  // Set the Tor options.
3382             // Set `torHomepageString` as `homepage`.
3383             homepage = torHomepageString;
3384
3385             // If formattedUrlString is null assign the homepage to it.
3386             if (formattedUrlString == null) {
3387                 formattedUrlString = homepage;
3388             }
3389
3390             // Set the search URL.
3391             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
3392                 searchURL = torSearchCustomURLString;
3393             } else {  // Use the string from the pre-built list.
3394                 searchURL = torSearchString;
3395             }
3396
3397             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
3398             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3399
3400             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
3401             if (darkTheme) {
3402                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3403             } else {
3404                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3405             }
3406
3407             // Display a message to the user if we are waiting on Orbot.
3408             if (!orbotStatus.equals("ON")) {
3409                 // Set `waitingForOrbot`.
3410                 waitingForOrbot = true;
3411
3412                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
3413                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3414             }
3415         } else {  // Set the non-Tor options.
3416             // Set `homepageString` as `homepage`.
3417             homepage = homepageString;
3418
3419             // If formattedUrlString is null assign the homepage to it.
3420             if (formattedUrlString == null) {
3421                 formattedUrlString = homepage;
3422             }
3423
3424             // Set the search URL.
3425             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
3426                 searchURL = searchCustomURLString;
3427             } else {  // Use the string from the pre-built list.
3428                 searchURL = searchString;
3429             }
3430
3431             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
3432             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3433
3434             // Set the default `appBar` background.  `this` refers to the context.
3435             if (darkTheme) {
3436                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3437             } else {
3438                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3439             }
3440
3441             // Reset `waitingForOrbot.
3442             waitingForOrbot = false;
3443         }
3444
3445         // Set Do Not Track status.
3446         if (doNotTrackEnabled) {
3447             customHeaders.put("DNT", "1");
3448         } else {
3449             customHeaders.remove("DNT");
3450         }
3451
3452         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3453         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3454             if (hideSystemBarsOnFullscreen) {  // Hide everything.
3455                 // Remove the translucent navigation setting if it is currently flagged.
3456                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3457
3458                 // Remove the translucent status bar overlay.
3459                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3460
3461                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3462                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3463
3464                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3465                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3466                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3467                  */
3468                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3469             } else {  // Hide everything except the status and navigation bars.
3470                 // Add the translucent status flag if it is unset.
3471                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3472
3473                 if (translucentNavigationBarOnFullscreen) {
3474                     // Set the navigation bar to be translucent.
3475                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3476                 } else {
3477                     // Set the navigation bar to be black.
3478                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3479                 }
3480             }
3481         } else {  // Switch to normal viewing mode.
3482             // Reset `inFullScreenBrowsingMode` to `false`.
3483             inFullScreenBrowsingMode = false;
3484
3485             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3486             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3487                 appBar.show();
3488             }
3489
3490             // Show the `BannerAd` in the free flavor.
3491             if (BuildConfig.FLAVOR.contentEquals("free")) {
3492                 // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3493                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3494             }
3495
3496             // Remove the translucent navigation bar flag if it is set.
3497             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3498
3499             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3500             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3501
3502             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3503             rootCoordinatorLayout.setSystemUiVisibility(0);
3504
3505             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3506             rootCoordinatorLayout.setFitsSystemWindows(true);
3507         }
3508     }
3509
3510     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3511     // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3512     @SuppressWarnings("deprecation")
3513     private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3514         // Reset `navigatingHistory`.
3515         navigatingHistory = false;
3516
3517         // Parse the URL into a URI.
3518         Uri uri = Uri.parse(url);
3519
3520         // Extract the domain from `uri`.
3521         String hostName = uri.getHost();
3522
3523         // Initialize `loadingNewDomainName`.
3524         boolean loadingNewDomainName;
3525
3526         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3527         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3528         //noinspection SimplifiableIfStatement
3529         if ((hostName == null) || (currentDomainName == null)) {
3530             loadingNewDomainName = true;
3531         } else {  // Determine if `hostName` equals `currentDomainName`.
3532             loadingNewDomainName = !hostName.equals(currentDomainName);
3533         }
3534
3535         // Strings don't like to be null.
3536         if (hostName == null) {
3537             hostName = "";
3538         }
3539
3540         // Only apply the domain settings if a new domain is being loaded.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3541         if (loadingNewDomainName) {
3542             // Set the new `hostname` as the `currentDomainName`.
3543             currentDomainName = hostName;
3544
3545             // Reset `ignorePinnedSslCertificate`.
3546             ignorePinnedSslCertificate = false;
3547
3548             // Reset the favorite icon if specified.
3549             if (resetFavoriteIcon) {
3550                 favoriteIconBitmap = favoriteIconDefaultBitmap;
3551                 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3552             }
3553
3554             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3555             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3556             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3557
3558             // Get a full cursor from `domainsDatabaseHelper`.
3559             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3560
3561             // Initialize `domainSettingsSet`.
3562             Set<String> domainSettingsSet = new HashSet<>();
3563
3564             // Get the domain name column index.
3565             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3566
3567             // Populate `domainSettingsSet`.
3568             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3569                 // Move `domainsCursor` to the current row.
3570                 domainNameCursor.moveToPosition(i);
3571
3572                 // Store the domain name in `domainSettingsSet`.
3573                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3574             }
3575
3576             // Close `domainNameCursor.
3577             domainNameCursor.close();
3578
3579             // Initialize variables to track if domain settings will be applied and, if so, under which name.
3580             domainSettingsApplied = false;
3581             String domainNameInDatabase = null;
3582
3583             // Check the hostname.
3584             if (domainSettingsSet.contains(hostName)) {
3585                 domainSettingsApplied = true;
3586                 domainNameInDatabase = hostName;
3587             }
3588
3589             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3590             while (!domainSettingsApplied && hostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3591                 if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
3592                     // Apply the domain settings.
3593                     domainSettingsApplied = true;
3594
3595                     // Store the applied domain names as it appears in the database.
3596                     domainNameInDatabase = "*." + hostName;
3597                 }
3598
3599                 // Strip out the lowest subdomain of of the host name.
3600                 hostName = hostName.substring(hostName.indexOf(".") + 1);
3601             }
3602
3603
3604             // Get a handle for the shared preference.
3605             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3606
3607             // Store the general preference information.
3608             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3609             String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3610             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3611             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3612             nightMode = sharedPreferences.getBoolean("night_mode", false);
3613
3614             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
3615                 // Get a cursor for the current host and move it to the first position.
3616                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3617                 currentHostDomainSettingsCursor.moveToFirst();
3618
3619                 // Get the settings from the cursor.
3620                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3621                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3622                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3623                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3624                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3625                 // Form data can be removed once the minimum API >= 26.
3626                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3627                 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3628                 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3629                 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3630                 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3631                 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3632                 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3633                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3634                 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3635                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3636                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3637                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3638                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3639                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3640                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3641                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3642                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3643                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3644
3645                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3646                 switch (nightModeInt) {
3647                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3648                         nightMode = true;
3649                         break;
3650
3651                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3652                         nightMode = false;
3653                         break;
3654                 }
3655
3656                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3657                 if (nightMode) {
3658                     javaScriptEnabled = true;
3659                 }
3660
3661                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3662                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3663                     pinnedDomainSslStartDate = null;
3664                 } else {
3665                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3666                 }
3667
3668                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3669                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3670                     pinnedDomainSslEndDate = null;
3671                 } else {
3672                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3673                 }
3674
3675                 // Close `currentHostDomainSettingsCursor`.
3676                 currentHostDomainSettingsCursor.close();
3677
3678                 // Apply the domain settings.
3679                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3680                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3681                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3682
3683                 // Apply the form data setting if the API < 26.
3684                 if (Build.VERSION.SDK_INT < 26) {
3685                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3686                 }
3687
3688                 // Apply the font size.
3689                 if (fontSize == 0) {  // Apply the default font size.
3690                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3691                 } else {  // Apply the specified font size.
3692                     mainWebView.getSettings().setTextZoom(fontSize);
3693                 }
3694
3695                 // Set third-party cookies status if API >= 21.
3696                 if (Build.VERSION.SDK_INT >= 21) {
3697                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3698                 }
3699
3700                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
3701                 // <https://redmine.stoutner.com/issues/160>
3702                 if (!urlIsLoading) {
3703                     // Set the user agent.
3704                     if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3705                         // Get the array position of the default user agent name.
3706                         int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3707
3708                         // Set the user agent according to the system default.
3709                         switch (defaultUserAgentArrayPosition) {
3710                             case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3711                                 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3712                                 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3713                                 break;
3714
3715                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3716                                 // Set the user agent to `""`, which uses the default value.
3717                                 mainWebView.getSettings().setUserAgentString("");
3718                                 break;
3719
3720                             case SETTINGS_CUSTOM_USER_AGENT:
3721                                 // Set the custom user agent.
3722                                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3723                                 break;
3724
3725                             default:
3726                                 // Get the user agent string from the user agent data array
3727                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3728                         }
3729                     } else {  // Set the user agent according to the stored name.
3730                         // Get the array position of the user agent name.
3731                         int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3732
3733                         switch (userAgentArrayPosition) {
3734                             case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3735                                 mainWebView.getSettings().setUserAgentString(userAgentName);
3736                                 break;
3737
3738                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3739                                 // Set the user agent to `""`, which uses the default value.
3740                                 mainWebView.getSettings().setUserAgentString("");
3741                                 break;
3742
3743                             default:
3744                                 // Get the user agent string from the user agent data array.
3745                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3746                         }
3747                     }
3748
3749                     // Set swipe to refresh.
3750                     switch (swipeToRefreshInt) {
3751                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3752                             // Set swipe to refresh according to the default.
3753                             swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3754                             break;
3755
3756                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3757                             // Enable swipe to refresh.
3758                             swipeRefreshLayout.setEnabled(true);
3759                             break;
3760
3761                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3762                             // Disable swipe to refresh.
3763                             swipeRefreshLayout.setEnabled(false);
3764                     }
3765
3766                     // Store the applied user agent string, which is used in the View Source activity.
3767                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3768                 }
3769
3770                 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3771                 if (darkTheme) {
3772                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3773                 } else {
3774                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3775                 }
3776             } else {  // The new URL does not have custom domain settings.  Load the defaults.
3777                 // Store the values from `sharedPreferences` in variables.
3778                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3779                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3780                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3781                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3782                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);  // Form data can be removed once the minimum API >= 26.
3783                 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3784                 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3785                 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3786                 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3787                 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3788
3789                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3790                 if (nightMode) {
3791                     javaScriptEnabled = true;
3792                 }
3793
3794                 // Apply the default settings.
3795                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3796                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3797                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3798                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3799                 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3800
3801                 // Apply the form data setting if the API < 26.
3802                 if (Build.VERSION.SDK_INT < 26) {
3803                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3804                 }
3805
3806                 // Reset the pinned SSL certificate information.
3807                 domainSettingsDatabaseId = -1;
3808                 pinnedDomainSslCertificate = false;
3809                 pinnedDomainSslIssuedToCNameString = "";
3810                 pinnedDomainSslIssuedToONameString = "";
3811                 pinnedDomainSslIssuedToUNameString = "";
3812                 pinnedDomainSslIssuedByCNameString = "";
3813                 pinnedDomainSslIssuedByONameString = "";
3814                 pinnedDomainSslIssuedByUNameString = "";
3815                 pinnedDomainSslStartDate = null;
3816                 pinnedDomainSslEndDate = null;
3817
3818                 // Set third-party cookies status if API >= 21.
3819                 if (Build.VERSION.SDK_INT >= 21) {
3820                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3821                 }
3822
3823                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
3824                 // <https://redmine.stoutner.com/issues/160>
3825                 if (!urlIsLoading) {
3826                     // Get the array position of the user agent name.
3827                     int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3828
3829                     // Set the user agent.
3830                     switch (userAgentArrayPosition) {
3831                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3832                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3833                             mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3834                             break;
3835
3836                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3837                             // Set the user agent to `""`, which uses the default value.
3838                             mainWebView.getSettings().setUserAgentString("");
3839                             break;
3840
3841                         case SETTINGS_CUSTOM_USER_AGENT:
3842                             // Set the custom user agent.
3843                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3844                             break;
3845
3846                         default:
3847                             // Get the user agent string from the user agent data array
3848                             mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3849                     }
3850
3851                     // Store the applied user agent string, which is used in the View Source activity.
3852                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3853                 }
3854
3855                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3856                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3857             }
3858
3859             // Close `domainsDatabaseHelper`.
3860             domainsDatabaseHelper.close();
3861
3862             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
3863             onTheFlyDisplayImagesSet = false;
3864             setDisplayWebpageImages();
3865
3866             // Update the privacy icons, but only if `mainMenu` has already been populated.
3867             if (mainMenu != null) {
3868                 updatePrivacyIcons(true);
3869             }
3870         }
3871
3872         // Reload the website if returning from the Domains activity.
3873         if (reloadWebsite) {
3874             mainWebView.reload();
3875         }
3876     }
3877
3878     private void setDisplayWebpageImages() {
3879         if (!onTheFlyDisplayImagesSet) {
3880             if (domainSettingsApplied) {  // Custom domain settings are applied.
3881                 switch (displayWebpageImagesInt) {
3882                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3883                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3884                         break;
3885
3886                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3887                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
3888                         break;
3889
3890                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3891                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
3892                         break;
3893                 }
3894             } else {  // Default settings are applied.
3895                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3896             }
3897         }
3898     }
3899
3900     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3901         // Get handles for the menu items.
3902         MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3903         MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3904         MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3905         MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
3906
3907         // Update the privacy icon.
3908         if (javaScriptEnabled) {  // JavaScript is enabled.
3909             privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3910         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
3911             privacyMenuItem.setIcon(R.drawable.warning);
3912         } else {  // All the dangerous features are disabled.
3913             privacyMenuItem.setIcon(R.drawable.privacy_mode);
3914         }
3915
3916         // Update the first-party cookies icon.
3917         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
3918             firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3919         } else {  // First-party cookies are disabled.
3920             if (darkTheme) {
3921                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3922             } else {
3923                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3924             }
3925         }
3926
3927         // Update the DOM storage icon.
3928         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
3929             domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3930         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
3931             if (darkTheme) {
3932                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3933             } else {
3934                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3935             }
3936         } else {  // JavaScript is disabled, so DOM storage is ghosted.
3937             if (darkTheme) {
3938                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3939             } else {
3940                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3941             }
3942         }
3943
3944         // Update the refresh icon.
3945         if (darkTheme) {
3946             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3947         } else {
3948             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3949         }
3950
3951         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3952         if (runInvalidateOptionsMenu) {
3953             invalidateOptionsMenu();
3954         }
3955     }
3956
3957     private void highlightUrlText() {
3958         String urlString = urlTextBox.getText().toString();
3959
3960         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
3961             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3962         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
3963             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3964         }
3965
3966         // Get the index of the `/` immediately after the domain name.
3967         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3968
3969         // De-emphasize the text after the domain name.
3970         if (endOfDomainName > 0) {
3971             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3972         }
3973     }
3974
3975     private void loadBookmarksFolder() {
3976         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3977         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3978
3979         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
3980         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3981             @Override
3982             public View newView(Context context, Cursor cursor, ViewGroup parent) {
3983                 // Inflate the individual item layout.  `false` does not attach it to the root.
3984                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3985             }
3986
3987             @Override
3988             public void bindView(View view, Context context, Cursor cursor) {
3989                 // Get handles for the views.
3990                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3991                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3992
3993                 // Get the favorite icon byte array from the cursor.
3994                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3995
3996                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3997                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3998
3999                 // Display the bitmap in `bookmarkFavoriteIcon`.
4000                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4001
4002                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4003                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4004                 bookmarkNameTextView.setText(bookmarkNameString);
4005
4006                 // Make the font bold for folders.
4007                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4008                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4009                 } else {  // Reset the font to default for normal bookmarks.
4010                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4011                 }
4012             }
4013         };
4014
4015         // Populate the `ListView` with the adapter.
4016         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4017
4018         // Set the bookmarks drawer title.
4019         if (currentBookmarksFolder.isEmpty()) {
4020             bookmarksTitleTextView.setText(R.string.bookmarks);
4021         } else {
4022             bookmarksTitleTextView.setText(currentBookmarksFolder);
4023         }
4024     }
4025 }