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