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