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