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