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