1ec5a020037e08504db735b8d43fc6ecd1c00184
[PrivacyBrowser.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.AsyncTask;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.Environment;
53 import android.os.Handler;
54 import android.preference.PreferenceManager;
55 import android.print.PrintDocumentAdapter;
56 import android.print.PrintManager;
57 import android.text.Editable;
58 import android.text.Spanned;
59 import android.text.TextWatcher;
60 import android.text.style.ForegroundColorSpan;
61 import android.util.Patterns;
62 import android.view.ContextMenu;
63 import android.view.GestureDetector;
64 import android.view.KeyEvent;
65 import android.view.Menu;
66 import android.view.MenuItem;
67 import android.view.MotionEvent;
68 import android.view.View;
69 import android.view.ViewGroup;
70 import android.view.WindowManager;
71 import android.view.inputmethod.InputMethodManager;
72 import android.webkit.CookieManager;
73 import android.webkit.HttpAuthHandler;
74 import android.webkit.SslErrorHandler;
75 import android.webkit.ValueCallback;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebSettings;
80 import android.webkit.WebStorage;
81 import android.webkit.WebView;
82 import android.webkit.WebViewClient;
83 import android.webkit.WebViewDatabase;
84 import android.widget.ArrayAdapter;
85 import android.widget.CursorAdapter;
86 import android.widget.EditText;
87 import android.widget.FrameLayout;
88 import android.widget.ImageView;
89 import android.widget.LinearLayout;
90 import android.widget.ListView;
91 import android.widget.ProgressBar;
92 import android.widget.RadioButton;
93 import android.widget.RelativeLayout;
94 import android.widget.TextView;
95
96 import androidx.annotation.NonNull;
97 import androidx.appcompat.app.ActionBar;
98 import androidx.appcompat.app.ActionBarDrawerToggle;
99 import androidx.appcompat.app.AppCompatActivity;
100 import androidx.appcompat.widget.Toolbar;
101 import androidx.core.app.ActivityCompat;
102 import androidx.core.content.ContextCompat;
103 import androidx.core.view.GravityCompat;
104 import androidx.drawerlayout.widget.DrawerLayout;
105 import androidx.fragment.app.DialogFragment;
106 import androidx.fragment.app.Fragment;
107 import androidx.fragment.app.FragmentManager;
108 import androidx.fragment.app.FragmentPagerAdapter;
109 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
110 import androidx.viewpager.widget.ViewPager;
111
112 import com.google.android.material.floatingactionbutton.FloatingActionButton;
113 import com.google.android.material.navigation.NavigationView;
114 import com.google.android.material.snackbar.Snackbar;
115
116 import com.google.android.material.tabs.TabLayout;
117 import com.stoutner.privacybrowser.BuildConfig;
118 import com.stoutner.privacybrowser.R;
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.lang.ref.WeakReference;
147 import java.net.InetAddress;
148 import java.net.MalformedURLException;
149 import java.net.URL;
150 import java.net.URLDecoder;
151 import java.net.URLEncoder;
152 import java.net.UnknownHostException;
153 import java.util.ArrayList;
154 import java.util.Date;
155 import java.util.HashMap;
156 import java.util.HashSet;
157 import java.util.LinkedList;
158 import java.util.List;
159 import java.util.Map;
160 import java.util.Set;
161
162 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
163 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
164         DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
165         EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener,
166         PinnedMismatchDialog.PinnedMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
167
168     // `darkTheme` is public static so it can be accessed from everywhere.
169     public static boolean darkTheme;
170
171     // `allowScreenshots` is public static so it can be accessed from everywhere.  It is also used in `onCreate()`.
172     public static boolean allowScreenshots;
173
174     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
175     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
176     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcut()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
177     public static Bitmap favoriteIconBitmap;
178
179     // `favoriteIconDefaultBitmap` public static so it can be accessed from `PinnedMismatchDialog`.  It is also used in `onCreate()` and `applyDomainSettings`.
180     public static Bitmap favoriteIconDefaultBitmap;
181
182     // `formattedUrlString` is public static so it can be accessed from `AddDomainDialog`, `BookmarksActivity`, `DomainSettingsFragment`, `CreateBookmarkDialog`,
183     // and `PinnedMismatchDialog`.
184     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, `loadUrlFromTextBox()`, and `applyProxyThroughOrbot()`.
185     public static String formattedUrlString;
186
187     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedMismatchDialog`, and `ViewSslCertificateDialog`.
188     // It is also used in `onCreate()` and `checkPinnedMismatch()`.
189     public static SslCertificate sslCertificate;
190
191     // `currentHostIpAddresses` is public static so it can be accessed from `DomainSettingsFragment` and `ViewSslCertificateDialog`.
192     // It is also used in `onCreate()` and `GetHostIpAddresses()`.
193     public static String currentHostIpAddresses;
194
195     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
196     public static String orbotStatus;
197
198     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog`.  It is also used in `onCreate()`.
199     public static String webViewTitle;
200
201     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
202     public static String appliedUserAgentString;
203
204     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
205     public static boolean reloadOnRestart;
206
207     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`.  It is also used in `onRestart()`.
208     public static boolean loadUrlOnRestart;
209
210     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
211     public static boolean restartFromBookmarksActivity;
212
213     // The block list versions are public static so they can be accessed from `AboutTabFragment`.  They are also used in `onCreate()`.
214     public static String easyListVersion;
215     public static String easyPrivacyVersion;
216     public static String fanboysAnnoyanceVersion;
217     public static String fanboysSocialVersion;
218     public static String ultraPrivacyVersion;
219
220     // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`.  They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
221     public static List<String[]> resourceRequests;
222     public static String[] whiteListResultStringArray;
223     private int blockedRequests;
224     private int easyListBlockedRequests;
225     private int easyPrivacyBlockedRequests;
226     private int fanboysAnnoyanceListBlockedRequests;
227     private int fanboysSocialBlockingListBlockedRequests;
228     private int ultraPrivacyBlockedRequests;
229     private int thirdPartyBlockedRequests;
230
231     public final static int REQUEST_DISPOSITION = 0;
232     public final static int REQUEST_URL = 1;
233     public final static int REQUEST_BLOCKLIST = 2;
234     public final static int REQUEST_SUBLIST = 3;
235     public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
236     public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
237
238     public final static int REQUEST_DEFAULT = 0;
239     public final static int REQUEST_ALLOWED = 1;
240     public final static int REQUEST_THIRD_PARTY = 2;
241     public final static int REQUEST_BLOCKED = 3;
242
243     public final static int MAIN_WHITELIST = 1;
244     public final static int FINAL_WHITELIST = 2;
245     public final static int DOMAIN_WHITELIST = 3;
246     public final static int DOMAIN_INITIAL_WHITELIST = 4;
247     public final static int DOMAIN_FINAL_WHITELIST = 5;
248     public final static int THIRD_PARTY_WHITELIST = 6;
249     public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
250     public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
251
252     public final static int MAIN_BLACKLIST = 9;
253     public final static int INITIAL_BLACKLIST = 10;
254     public final static int FINAL_BLACKLIST = 11;
255     public final static int DOMAIN_BLACKLIST = 12;
256     public final static int DOMAIN_INITIAL_BLACKLIST = 13;
257     public final static int DOMAIN_FINAL_BLACKLIST = 14;
258     public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
259     public final static int THIRD_PARTY_BLACKLIST = 16;
260     public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
261     public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
262     public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
263     public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
264     public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
265     public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
266
267     // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
268     // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
269     public static boolean blockAllThirdPartyRequests;
270
271     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
272     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
273     public static String currentBookmarksFolder;
274
275     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
276     public static int domainSettingsDatabaseId;
277
278     // The pinned variables are public static so they can be accessed from `PinnedMismatchDialog`.  They are also used in `onCreate()`, `applyDomainSettings()`, and `checkPinnedMismatch()`.
279     public static String pinnedSslIssuedToCName;
280     public static String pinnedSslIssuedToOName;
281     public static String pinnedSslIssuedToUName;
282     public static String pinnedSslIssuedByCName;
283     public static String pinnedSslIssuedByOName;
284     public static String pinnedSslIssuedByUName;
285     public static Date pinnedSslStartDate;
286     public static Date pinnedSslEndDate;
287     public static String pinnedHostIpAddresses;
288
289     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
290     public final static int UNRECOGNIZED_USER_AGENT = -1;
291     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
292     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
293     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
294     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
295     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
296
297
298
299     // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, `applyDomainSettings()`, and `GetHostIpAddresses`.
300     private static boolean urlIsLoading;
301
302     // `gettingIpAddresses` is used in `onCreate() and `GetHostIpAddresses`.
303     private static boolean gettingIpAddresses;
304
305     // `pinnedDomainSslCertificate` is used in `onCreate()`, `applyDomainSettings()`, and `checkPinnedMismatch()`.
306     private static boolean pinnedSslCertificate;
307
308     // `pinnedIpAddress` is used in `applyDomainSettings()` and `checkPinnedMismatch()`.
309     private static boolean pinnedIpAddresses;
310
311     // `ignorePinnedDomainInformation` is used in `onSslMismatchProceed()`, `applyDomainSettings()`, and `checkPinnedMismatch()`.
312     private static boolean ignorePinnedDomainInformation;
313
314     // The fragment manager is initialized in `onCreate()` and accessed from the static `checkPinnedMismatch()`.
315     private static FragmentManager fragmentManager;
316
317
318     // A handle for the activity is set in `onCreate()` and accessed in `WebViewPagerAdapter`.
319     private Activity activity;
320
321     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
322     private boolean navigatingHistory;
323
324     // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
325     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `applyProxyThroughOrbot()`.
326     private NestedScrollWebView currentWebView;
327
328     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
329     private FrameLayout fullScreenVideoFrameLayout;
330
331     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
332     private CookieManager cookieManager;
333
334     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
335     private final Map<String, String> customHeaders = new HashMap<>();
336
337     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
338     private boolean javaScriptEnabled;
339
340     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
341     private boolean firstPartyCookiesEnabled;
342
343     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
344     private boolean thirdPartyCookiesEnabled;
345
346     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
347     private boolean domStorageEnabled;
348
349     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.  It can be removed once the minimum API >= 26.
350     private boolean saveFormDataEnabled;
351
352     // `nightMode` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and  `applyDomainSettings()`.
353     private boolean nightMode;
354
355     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyProxyThroughOrbot()`.
356     private String homepage;
357
358     // `searchURL` is used in `loadURLFromTextBox()` and `applyProxyThroughOrbot()`.
359     private String searchURL;
360
361     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
362     private Menu mainMenu;
363
364     // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
365     private MenuItem refreshMenuItem;
366
367     // The WebView pager adapter is used in `onCreate()`, `onResume()`, and `addTab()`.
368     private WebViewPagerAdapter webViewPagerAdapter;
369
370     // The navigation requests menu item is used in `onCreate()` and accessed from `WebViewPagerAdapter`.
371     private MenuItem navigationRequestsMenuItem;
372
373     // The blocklist helper is used in `onCreate()` and `WebViewPagerAdapter`.
374     BlockListHelper blockListHelper;
375
376     // The blocklists are populated in `onCreate()` and accessed from `WebViewPagerAdapter`.
377     private ArrayList<List<String[]>> easyList;
378     private ArrayList<List<String[]>> easyPrivacy;
379     private ArrayList<List<String[]>> fanboysAnnoyanceList;
380     private ArrayList<List<String[]>> fanboysSocialList;
381     private ArrayList<List<String[]>> ultraPrivacy;
382
383     // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
384     private MenuItem blocklistsMenuItem;
385     private MenuItem easyListMenuItem;
386     private MenuItem easyPrivacyMenuItem;
387     private MenuItem fanboysAnnoyanceListMenuItem;
388     private MenuItem fanboysSocialBlockingListMenuItem;
389     private MenuItem ultraPrivacyMenuItem;
390     private MenuItem blockAllThirdPartyRequestsMenuItem;
391
392     // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
393     private boolean easyListEnabled;
394     private boolean easyPrivacyEnabled;
395     private boolean fanboysAnnoyanceListEnabled;
396     private boolean fanboysSocialBlockingListEnabled;
397     private boolean ultraPrivacyEnabled;
398
399     // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
400     private String webViewDefaultUserAgent;
401
402     // `defaultCustomUserAgentString` is used in `onPrepareOptionsMenu()` and `applyDomainSettings()`.
403     private String defaultCustomUserAgentString;
404
405     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
406     private Runtime privacyBrowserRuntime;
407
408     // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
409     private boolean proxyThroughOrbot;
410
411     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
412     private boolean incognitoModeEnabled;
413
414     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
415     private boolean fullScreenBrowsingModeEnabled;
416
417     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
418     private boolean inFullScreenBrowsingMode;
419
420     // Hide app bar is used in `onCreate()` and `applyAppSettings()`.
421     private boolean hideAppBar;
422
423     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
424     private boolean reapplyDomainSettingsOnRestart;
425
426     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
427     private boolean reapplyAppSettingsOnRestart;
428
429     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
430     private boolean displayingFullScreenVideo;
431
432     // `downloadWithExternalApp` is used in `onCreate()`, `onCreateContextMenu()`, and `applyDomainSettings()`.
433     private boolean downloadWithExternalApp;
434
435     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
436     private String currentDomainName;
437
438     // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
439     private BroadcastReceiver orbotStatusBroadcastReceiver;
440
441     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
442     private boolean waitingForOrbot;
443
444     // `domainSettingsApplied` is used in `prepareOptionsMenu()` and `applyDomainSettings()`.
445     private boolean domainSettingsApplied;
446
447     // `domainSettingsJavaScriptEnabled` is used in `onOptionsItemSelected()` and `applyDomainSettings()`.
448     private Boolean domainSettingsJavaScriptEnabled;
449
450     // `waitingForOrbotHtmlString` is used in `onCreate()` and `applyProxyThroughOrbot()`.
451     private String waitingForOrbotHtmlString;
452
453     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
454     private String privateDataDirectoryString;
455
456     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
457     private EditText findOnPageEditText;
458
459     // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
460     private boolean displayAdditionalAppBarIcons;
461
462     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
463     private ActionBarDrawerToggle actionBarDrawerToggle;
464
465     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
466     private EditText urlTextBox;
467
468     // The color spans are used in `onCreate()` and `highlightUrlText()`.
469     private ForegroundColorSpan redColorSpan;
470     private ForegroundColorSpan initialGrayColorSpan;
471     private ForegroundColorSpan finalGrayColorSpan;
472
473     // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
474     private int drawerHeaderPaddingLeftAndRight;
475     private int drawerHeaderPaddingTop;
476     private int drawerHeaderPaddingBottom;
477
478     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
479     private SslErrorHandler sslErrorHandler;
480
481     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
482     private static HttpAuthHandler httpAuthHandler;
483
484     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
485     private InputMethodManager inputMethodManager;
486
487     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
488     // and `loadBookmarksFolder()`.
489     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
490
491     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
492     private ListView bookmarksListView;
493
494     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
495     private TextView bookmarksTitleTextView;
496
497     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
498     private Cursor bookmarksCursor;
499
500     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
501     private CursorAdapter bookmarksCursorAdapter;
502
503     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
504     private String oldFolderNameString;
505
506     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
507     private ValueCallback<Uri[]> fileChooserCallback;
508
509     // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
510     private String downloadUrl;
511     private String downloadContentDisposition;
512     private long downloadContentLength;
513
514     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
515     private String downloadImageUrl;
516
517     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
518     private ArrayAdapter<CharSequence> userAgentNamesArray;
519     private String[] userAgentDataArray;
520
521     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
522     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
523     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
524
525     @Override
526     // 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.
527     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
528     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
529     // Remove Android Studio's warning about deprecations.  The deprecated `getColor()` must be used until API >= 23.
530     @SuppressWarnings("deprecation")
531     protected void onCreate(Bundle savedInstanceState) {
532         // Get a handle for the shared preferences.
533         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
534
535         // Get the theme and screenshot preferences.
536         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
537         allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
538
539         // Disable screenshots if not allowed.
540         if (!allowScreenshots) {
541             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
542         }
543
544         // Set the activity theme.
545         if (darkTheme) {
546             setTheme(R.style.PrivacyBrowserDark);
547         } else {
548             setTheme(R.style.PrivacyBrowserLight);
549         }
550
551         // Run the default commands.
552         super.onCreate(savedInstanceState);
553
554         // Set the content view.
555         setContentView(R.layout.main_framelayout);
556
557         // Get handles for views, resources, and managers.
558         activity = this;
559         Resources resources = getResources();
560         fragmentManager = getSupportFragmentManager();
561         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
562         Toolbar toolbar = findViewById(R.id.toolbar);
563
564         // Set the action bar.  `SupportActionBar` must be used until the minimum API is >= 21.
565         setSupportActionBar(toolbar);
566         ActionBar actionBar = getSupportActionBar();
567
568         // This is needed to get rid of the Android Studio warning that the action bar might be null.
569         assert actionBar != null;
570
571         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
572         actionBar.setCustomView(R.layout.url_app_bar);
573         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
574
575         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
576         redColorSpan = new ForegroundColorSpan(resources.getColor(R.color.red_a700));
577         initialGrayColorSpan = new ForegroundColorSpan(resources.getColor(R.color.gray_500));
578         finalGrayColorSpan = new ForegroundColorSpan(resources.getColor(R.color.gray_500));
579
580         // Get a handle for `urlTextBox`.
581         urlTextBox = findViewById(R.id.url_edittext);
582
583         // Remove the formatting from `urlTextBar` when the user is editing the text.
584         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
585             if (hasFocus) {  // The user is editing the URL text box.
586                 // Remove the highlighting.
587                 urlTextBox.getText().removeSpan(redColorSpan);
588                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
589                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
590             } else {  // The user has stopped editing the URL text box.
591                 // Move to the beginning of the string.
592                 urlTextBox.setSelection(0);
593
594                 // Reapply the highlighting.
595                 highlightUrlText();
596             }
597         });
598
599         // Set the go button on the keyboard to load the URL in `urlTextBox`.
600         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
601             // If the event is a key-down event on the `enter` button, load the URL.
602             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
603                 // Load the URL into the mainWebView and consume the event.
604                 loadUrlFromTextBox();
605
606                 // If the enter key was pressed, consume the event.
607                 return true;
608             } else {
609                 // If any other key was pressed, do not consume the event.
610                 return false;
611             }
612         });
613
614         // Set `waitingForOrbotHTMLString`.
615         waitingForOrbotHtmlString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
616
617         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
618         currentDomainName = "";
619         orbotStatus = "unknown";
620         waitingForOrbot = false;
621
622         // Create an Orbot status `BroadcastReceiver`.
623         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
624             @Override
625             public void onReceive(Context context, Intent intent) {
626                 // Store the content of the status message in `orbotStatus`.
627                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
628
629                 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
630                 if (orbotStatus.equals("ON") && waitingForOrbot) {
631                     // Reset `waitingForOrbot`.
632                     waitingForOrbot = false;
633
634                     // Load `formattedUrlString
635                     loadUrl(formattedUrlString);
636                 }
637             }
638         };
639
640         // Register `orbotStatusBroadcastReceiver` on `this` context.
641         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
642
643         // Instantiate the block list helper.
644         blockListHelper = new BlockListHelper();
645
646         // Initialize the list of resource requests.
647         resourceRequests = new ArrayList<>();
648
649         // Parse the block lists.
650         easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
651         easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
652         fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
653         fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
654         ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
655
656         // Store the list versions.
657         easyListVersion = easyList.get(0).get(0)[0];
658         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
659         fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
660         fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
661         ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
662
663         // Get handles for views that need to be modified.
664         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
665         final NavigationView navigationView = findViewById(R.id.navigationview);
666         TabLayout tabLayout = findViewById(R.id.tablayout);
667         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
668         ViewPager webViewPager = findViewById(R.id.webviewpager);
669         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
670         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
671         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
672         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
673         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
674         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
675         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
676
677         // Listen for touches on the navigation menu.
678         navigationView.setNavigationItemSelectedListener(this);
679
680         // Get handles for the navigation menu and the back and forward menu items.  The menu is zero-based.
681         final Menu navigationMenu = navigationView.getMenu();
682         final MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
683         final MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
684         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
685         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
686         navigationRequestsMenuItem = navigationMenu.getItem(6);
687
688         // Initialize the web view pager adapter.
689         webViewPagerAdapter = new WebViewPagerAdapter(fragmentManager);
690
691         // Set the pager adapter on the web view pager.
692         webViewPager.setAdapter(webViewPagerAdapter);
693
694         // Store up to 100 tabs in memory.
695         webViewPager.setOffscreenPageLimit(100);
696
697         // Update the web view pager every time a tab is modified.
698         webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
699             @Override
700             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
701                 // Do nothing.
702             }
703
704             @Override
705             public void onPageSelected(int position) {
706                 // TODO.  Consider using an array of the WebViews.
707                 // Get the current WebView fragment.  Instantiate item returns the current item if it already exists.
708                 Fragment webViewFragment = (Fragment) webViewPagerAdapter.instantiateItem(webViewPager, position);
709
710                 // Remove the lint error below that the WebView fragment might be null.
711                 assert webViewFragment.getView() != null;
712
713                 // Store the current WebView.
714                 currentWebView = webViewFragment.getView().findViewById(R.id.nestedscroll_webview);
715
716                 // 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.
717                 if (tabLayout.getSelectedTabPosition() != position) {
718                     // Get a handle for the corresponding tab.
719                     TabLayout.Tab correspondingTab = tabLayout.getTabAt(position);
720
721                     // Assert that the corresponding tab is not null.
722                     assert correspondingTab != null;
723
724                     // Select the corresponding tab.
725                     correspondingTab.select();
726                 }
727             }
728
729             @Override
730             public void onPageScrollStateChanged(int state) {
731                 // Do nothing.
732             }
733         });
734
735         // Display the View SSL Certificate dialog when the currently selected tab is reselected.
736         tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
737             @Override
738             public void onTabSelected(TabLayout.Tab tab) {
739                 // Select the same page in the view pager.
740                 webViewPager.setCurrentItem(tab.getPosition());
741             }
742
743             @Override
744             public void onTabUnselected(TabLayout.Tab tab) {
745                 // Do nothing.
746             }
747
748             @Override
749             public void onTabReselected(TabLayout.Tab tab) {
750                 // Instantiate the View SSL Certificate dialog.
751                 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
752
753                 // Display the View SSL Certificate dialog.
754                 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
755             }
756         });
757
758         // Add the first tab.
759         webViewPagerAdapter.addPage();
760
761         // 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.
762         if (darkTheme) {
763             launchBookmarksActivityFab.setImageDrawable(resources.getDrawable(R.drawable.bookmarks_dark));
764             createBookmarkFolderFab.setImageDrawable(resources.getDrawable(R.drawable.create_folder_dark));
765             createBookmarkFab.setImageDrawable(resources.getDrawable(R.drawable.create_bookmark_dark));
766             bookmarksListView.setBackgroundColor(resources.getColor(R.color.gray_850));
767         } else {
768             launchBookmarksActivityFab.setImageDrawable(resources.getDrawable(R.drawable.bookmarks_light));
769             createBookmarkFolderFab.setImageDrawable(resources.getDrawable(R.drawable.create_folder_light));
770             createBookmarkFab.setImageDrawable(resources.getDrawable(R.drawable.create_bookmark_light));
771             bookmarksListView.setBackgroundColor(resources.getColor(R.color.white));
772         }
773
774         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
775         launchBookmarksActivityFab.setOnClickListener(v -> {
776             // Create an intent to launch the bookmarks activity.
777             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
778
779             // Include the current folder with the `Intent`.
780             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
781
782             // Make it so.
783             startActivity(bookmarksIntent);
784         });
785
786         // Set the create new bookmark folder FAB to display an alert dialog.
787         createBookmarkFolderFab.setOnClickListener(v -> {
788             // Show the create bookmark folder dialog and name the instance `@string/create_folder`.
789             DialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
790             createBookmarkFolderDialog.show(fragmentManager, resources.getString(R.string.create_folder));
791         });
792
793         // Set the create new bookmark FAB to display an alert dialog.
794         createBookmarkFab.setOnClickListener(view -> {
795             // Show the create bookmark dialog and name the instance `@string/create_bookmark`.
796             DialogFragment createBookmarkDialog = new CreateBookmarkDialog();
797             createBookmarkDialog.show(fragmentManager, resources.getString(R.string.create_bookmark));
798         });
799
800         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
801         findOnPageEditText.addTextChangedListener(new TextWatcher() {
802             @Override
803             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
804                 // Do nothing.
805             }
806
807             @Override
808             public void onTextChanged(CharSequence s, int start, int before, int count) {
809                 // Do nothing.
810             }
811
812             @Override
813             public void afterTextChanged(Editable s) {
814                 // Search for the text in `mainWebView`.
815                 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
816             }
817         });
818
819         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
820         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
821             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
822                 // Hide the soft keyboard.  `0` indicates no additional flags.
823                 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
824
825                 // Consume the event.
826                 return true;
827             } else {  // A different key was pressed.
828                 // Do not consume the event.
829                 return false;
830             }
831         });
832
833         // Implement swipe to refresh.
834         swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
835
836         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
837         swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
838
839         // Set the swipe to refresh color according to the theme.
840         if (darkTheme) {
841             swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
842             swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
843         } else {
844             swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
845         }
846
847         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
848         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
849         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
850
851         // Initialize the bookmarks database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
852         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
853
854         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
855         currentBookmarksFolder = "";
856
857         // Load the home folder, which is `""` in the database.
858         loadBookmarksFolder();
859
860         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
861             // Convert the id from long to int to match the format of the bookmarks database.
862             int databaseID = (int) id;
863
864             // Get the bookmark cursor for this ID and move it to the first row.
865             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
866             bookmarkCursor.moveToFirst();
867
868             // Act upon the bookmark according to the type.
869             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
870                 // Store the new folder name in `currentBookmarksFolder`.
871                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
872
873                 // Load the new folder.
874                 loadBookmarksFolder();
875             } else {  // The selected bookmark is not a folder.
876                 // Load the bookmark URL.
877                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
878
879                 // Close the bookmarks drawer.
880                 drawerLayout.closeDrawer(GravityCompat.END);
881             }
882
883             // Close the `Cursor`.
884             bookmarkCursor.close();
885         });
886
887         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
888             // Convert the database ID from `long` to `int`.
889             int databaseId = (int) id;
890
891             // Find out if the selected bookmark is a folder.
892             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
893
894             if (isFolder) {
895                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
896                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
897
898                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
899                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
900                 editBookmarkFolderDialog.show(fragmentManager, resources.getString(R.string.edit_folder));
901             } else {
902                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
903                 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
904                 editBookmarkDialog.show(fragmentManager, resources.getString(R.string.edit_bookmark));
905             }
906
907             // Consume the event.
908             return true;
909         });
910
911         // Get the status bar pixel size.
912         int statusBarResourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
913         int statusBarPixelSize = resources.getDimensionPixelSize(statusBarResourceId);
914
915         // Get the resource density.
916         float screenDensity = resources.getDisplayMetrics().density;
917
918         // Calculate the drawer header padding.  This is used to move the text in the drawer headers below any cutouts.
919         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
920         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
921         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
922
923         // The drawer listener is used to update the navigation menu.`
924         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
925             @Override
926             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
927             }
928
929             @Override
930             public void onDrawerOpened(@NonNull View drawerView) {
931             }
932
933             @Override
934             public void onDrawerClosed(@NonNull View drawerView) {
935             }
936
937             @Override
938             public void onDrawerStateChanged(int newState) {
939                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
940                     // Get handles for the drawer headers.
941                     TextView navigationHeaderTextView = findViewById(R.id.navigationText);
942                     TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
943
944                     // 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.
945                     if (navigationHeaderTextView != null) {
946                         navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
947                     }
948
949                     // 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.
950                     if (bookmarksHeaderTextView != null) {
951                         bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
952                     }
953
954                     // Update the navigation menu items.
955                     navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
956                     navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
957                     navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
958                     navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
959                     navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
960
961                     // Hide the keyboard (if displayed).
962                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
963
964                     // 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.
965                     urlTextBox.clearFocus();
966                     currentWebView.clearFocus();
967                 }
968             }
969         });
970
971         // Create the hamburger icon at the start of the AppBar.
972         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
973
974         // Initialize cookieManager.
975         cookieManager = CookieManager.getInstance();
976
977         // 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).
978         customHeaders.put("X-Requested-With", "");
979
980         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
981         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
982
983         // Get a handle for the `Runtime`.
984         privacyBrowserRuntime = Runtime.getRuntime();
985
986         // Store the application's private data directory.
987         privateDataDirectoryString = getApplicationInfo().dataDir;
988         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
989
990         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
991         inFullScreenBrowsingMode = false;
992
993         // Initialize the privacy settings variables.
994         javaScriptEnabled = false;
995         firstPartyCookiesEnabled = false;
996         thirdPartyCookiesEnabled = false;
997         domStorageEnabled = false;
998         saveFormDataEnabled = false;  // Form data can be removed once the minimum API >= 26.
999         nightMode = false;
1000
1001         // Store the default user agent.
1002         // TODO webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1003
1004         // Initialize the WebView title.
1005         webViewTitle = getString(R.string.no_title);
1006
1007         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1008         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1009         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1010         assert favoriteIconBitmapDrawable != null;
1011         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1012
1013         // If the favorite icon is null, load the default.
1014         if (favoriteIconBitmap == null) {
1015             favoriteIconBitmap = favoriteIconDefaultBitmap;
1016         }
1017
1018         // Initialize the user agent array adapter and string array.
1019         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
1020         userAgentDataArray = resources.getStringArray(R.array.user_agent_data);
1021
1022         // Get the intent that started the app.
1023         Intent launchingIntent = getIntent();
1024
1025         // Get the information from the intent.
1026         String launchingIntentAction = launchingIntent.getAction();
1027         Uri launchingIntentUriData = launchingIntent.getData();
1028
1029         // If the intent action is a web search, perform the search.
1030         if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
1031             // Create an encoded URL string.
1032             String encodedUrlString;
1033
1034             // Sanitize the search input and convert it to a search.
1035             try {
1036                 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
1037             } catch (UnsupportedEncodingException exception) {
1038                 encodedUrlString = "";
1039             }
1040
1041             // Add the base search URL.
1042             formattedUrlString = searchURL + encodedUrlString;
1043         } else if (launchingIntentUriData != null){  // Check to see if the intent contains a new URL.
1044             // Set the formatted URL string.
1045             formattedUrlString = launchingIntentUriData.toString();
1046         }
1047     }
1048
1049     @Override
1050     protected void onNewIntent(Intent intent) {
1051         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1052         setIntent(intent);
1053
1054         // Get the information from the intent.
1055         String intentAction = intent.getAction();
1056         Uri intentUriData = intent.getData();
1057
1058         // If the intent action is a web search, perform the search.
1059         if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
1060             // Create an encoded URL string.
1061             String encodedUrlString;
1062
1063             // Sanitize the search input and convert it to a search.
1064             try {
1065                 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
1066             } catch (UnsupportedEncodingException exception) {
1067                 encodedUrlString = "";
1068             }
1069
1070             // Add the base search URL.
1071             formattedUrlString = searchURL + encodedUrlString;
1072         } else if (intentUriData != null){  // Check to see if the intent contains a new URL.
1073             // Set the formatted URL string.
1074             formattedUrlString = intentUriData.toString();
1075         }
1076
1077         // Load the URL.
1078         loadUrl(formattedUrlString);
1079
1080         // Get a handle for the drawer layout.
1081         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1082
1083         // Close the navigation drawer if it is open.
1084         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1085             drawerLayout.closeDrawer(GravityCompat.START);
1086         }
1087
1088         // Close the bookmarks drawer if it is open.
1089         if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1090             drawerLayout.closeDrawer(GravityCompat.END);
1091         }
1092
1093         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1094         currentWebView.requestFocus();
1095     }
1096
1097     @Override
1098     public void onRestart() {
1099         // Run the default commands.
1100         super.onRestart();
1101
1102         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1103         if (proxyThroughOrbot) {
1104             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1105             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1106
1107             // Send the intent to the Orbot package.
1108             orbotIntent.setPackage("org.torproject.android");
1109
1110             // Make it so.
1111             sendBroadcast(orbotIntent);
1112         }
1113
1114         // Apply the app settings if returning from the Settings activity..
1115         if (reapplyAppSettingsOnRestart) {
1116             // Apply the app settings.
1117             applyAppSettings();
1118
1119             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1120             if (reloadOnRestart) {
1121                 // Reload the WebViews.
1122                 // TODO
1123                 currentWebView.reload();
1124
1125                 // Reset `reloadOnRestartBoolean`.
1126                 reloadOnRestart = false;
1127             }
1128
1129             // Reset the return from settings flag.
1130             reapplyAppSettingsOnRestart = false;
1131         }
1132
1133         // Apply the domain settings if returning from the Domains activity.
1134         if (reapplyDomainSettingsOnRestart) {
1135             // Reapply the domain settings.
1136             applyDomainSettings(formattedUrlString, false, true);
1137
1138             // Reset `reapplyDomainSettingsOnRestart`.
1139             reapplyDomainSettingsOnRestart = false;
1140         }
1141
1142         // Load the URL on restart to apply changes to night mode.
1143         if (loadUrlOnRestart) {
1144             // Load the current `formattedUrlString`.
1145             loadUrl(formattedUrlString);
1146
1147             // Reset `loadUrlOnRestart.
1148             loadUrlOnRestart = false;
1149         }
1150
1151         // Update the bookmarks drawer if returning from the Bookmarks activity.
1152         if (restartFromBookmarksActivity) {
1153             // Get a handle for the drawer layout.
1154             DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1155
1156             // Close the bookmarks drawer.
1157             drawerLayout.closeDrawer(GravityCompat.END);
1158
1159             // Reload the bookmarks drawer.
1160             loadBookmarksFolder();
1161
1162             // Reset `restartFromBookmarksActivity`.
1163             restartFromBookmarksActivity = false;
1164         }
1165
1166         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1167         updatePrivacyIcons(true);
1168     }
1169
1170     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1171     @Override
1172     public void onResume() {
1173         // Run the default commands.
1174         super.onResume();
1175
1176         // Resume JavaScript (if enabled).
1177         // TODO mainWebView.resumeTimers();
1178
1179         // Resume `mainWebView`.
1180         // TODO mainWebView.onResume();
1181
1182         // Display a message to the user if waiting for Orbot.
1183         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1184             // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1185             currentWebView.getSettings().setUseWideViewPort(false);
1186
1187             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1188             currentWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
1189         }
1190
1191         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
1192             // Get a handle for the root frame layouts.
1193             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1194
1195             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
1196             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1197
1198             /* Hide the system bars.
1199              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1200              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1201              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1202              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1203              */
1204             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1205                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1206         } else if (BuildConfig.FLAVOR.contentEquals("free")) {  // Resume the adView for the free flavor.
1207             // Resume the ad.
1208             AdHelper.resumeAd(findViewById(R.id.adview));
1209         }
1210     }
1211
1212     @Override
1213     public void onPause() {
1214         // Run the default commands.
1215         super.onPause();
1216
1217         // Pause `mainWebView`.
1218         // TODO
1219         currentWebView.onPause();
1220
1221         // Stop all JavaScript.
1222         // TODO
1223         currentWebView.pauseTimers();
1224
1225         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1226         if (BuildConfig.FLAVOR.contentEquals("free")) {
1227             // Pause the ad.
1228             AdHelper.pauseAd(findViewById(R.id.adview));
1229         }
1230     }
1231
1232     @Override
1233     public void onDestroy() {
1234         // Unregister the Orbot status broadcast receiver.
1235         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1236
1237         // Close the bookmarks cursor and database.
1238         bookmarksCursor.close();
1239         bookmarksDatabaseHelper.close();
1240
1241         // Run the default commands.
1242         super.onDestroy();
1243     }
1244
1245     @Override
1246     public boolean onCreateOptionsMenu(Menu menu) {
1247         // Inflate the menu.  This adds items to the action bar if it is present.
1248         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1249
1250         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1251         mainMenu = menu;
1252
1253         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1254         updatePrivacyIcons(false);
1255
1256         // Get handles for the menu items.
1257         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1258         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1259         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1260         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1261         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1262         refreshMenuItem = menu.findItem(R.id.refresh);
1263         blocklistsMenuItem = menu.findItem(R.id.blocklists);
1264         easyListMenuItem = menu.findItem(R.id.easylist);
1265         easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1266         fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1267         fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1268         ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1269         blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1270         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1271
1272         // Only display third-party cookies if API >= 21
1273         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1274
1275         // Only display the form data menu items if the API < 26.
1276         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1277         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1278
1279         // Only show Ad Consent if this is the free flavor.
1280         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1281
1282         // Get the shared preference values.
1283         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1284
1285         // Get the status of the additional AppBar icons.
1286         displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1287
1288         // 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.
1289         if (displayAdditionalAppBarIcons) {
1290             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1291             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1292             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1293         } else { //Do not display the additional icons.
1294             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1295             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1296             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1297         }
1298
1299         // Replace Refresh with Stop if a URL is already loading.
1300         if (urlIsLoading) {
1301             // Set the title.
1302             refreshMenuItem.setTitle(R.string.stop);
1303
1304             // If the icon is displayed in the AppBar, set it according to the theme.
1305             if (displayAdditionalAppBarIcons) {
1306                 if (darkTheme) {
1307                     refreshMenuItem.setIcon(R.drawable.close_dark);
1308                 } else {
1309                     refreshMenuItem.setIcon(R.drawable.close_light);
1310                 }
1311             }
1312         }
1313
1314         return true;
1315     }
1316
1317     @Override
1318     public boolean onPrepareOptionsMenu(Menu menu) {
1319         // Get a handle for the swipe refresh layout.
1320         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1321
1322         // Get handles for the menu items.
1323         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1324         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1325         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1326         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1327         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1328         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1329         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1330         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1331         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1332         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1333         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1334         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1335         MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1336         MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1337
1338         // Set the text for the domain menu item.
1339         if (domainSettingsApplied) {
1340             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1341         } else {
1342             addOrEditDomain.setTitle(R.string.add_domain_settings);
1343         }
1344
1345         // Set the status of the menu item checkboxes.
1346         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1347         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1348         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1349         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1350         easyListMenuItem.setChecked(easyListEnabled);
1351         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1352         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1353         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1354         ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1355         blockAllThirdPartyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1356         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1357         // TODO displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1358         nightModeMenuItem.setChecked(nightMode);
1359         proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1360
1361         // Enable third-party cookies if first-party cookies are enabled.
1362         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1363
1364         // Enable DOM Storage if JavaScript is enabled.
1365         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1366
1367         // Enable Clear Cookies if there are any.
1368         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1369
1370         // Get a count of the number of files in the Local Storage directory.
1371         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1372         int localStorageDirectoryNumberOfFiles = 0;
1373         if (localStorageDirectory.exists()) {
1374             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1375         }
1376
1377         // Get a count of the number of files in the IndexedDB directory.
1378         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1379         int indexedDBDirectoryNumberOfFiles = 0;
1380         if (indexedDBDirectory.exists()) {
1381             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1382         }
1383
1384         // Enable Clear DOM Storage if there is any.
1385         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1386
1387         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1388         if (Build.VERSION.SDK_INT < 26) {
1389             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1390             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1391         } else {
1392             // Disable clear form data because it is not supported on current version of Android.
1393             clearFormDataMenuItem.setEnabled(false);
1394         }
1395
1396         // Enable Clear Data if any of the submenu items are enabled.
1397         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1398
1399         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1400         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1401
1402         // Initialize the display names for the blocklists with the number of blocked requests.
1403         blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
1404         easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1405         easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1406         fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1407         fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1408         ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1409         blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1410
1411         // Get the current user agent.
1412         // TODO String currentUserAgent = mainWebView.getSettings().getUserAgentString();
1413         String currentUserAgent = "";
1414
1415         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1416         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1417             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1418         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1419             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1420         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1421             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1422         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1423             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1424         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1425             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1426         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1427             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1428         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1429             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1430         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1431             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1432         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1433             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1434         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1435             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1436         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1437             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1438         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1439             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1440         } else {  // Custom user agent.
1441             menu.findItem(R.id.user_agent_custom).setChecked(true);
1442         }
1443
1444         // Initialize font size variables.
1445         // TODO int fontSize = mainWebView.getSettings().getTextZoom();
1446         int fontSize = 100;
1447         String fontSizeTitle;
1448         MenuItem selectedFontSizeMenuItem;
1449
1450         // Prepare the font size title and current size menu item.
1451         switch (fontSize) {
1452             case 25:
1453                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1454                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1455                 break;
1456
1457             case 50:
1458                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1459                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1460                 break;
1461
1462             case 75:
1463                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1464                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1465                 break;
1466
1467             case 100:
1468                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1469                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1470                 break;
1471
1472             case 125:
1473                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1474                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1475                 break;
1476
1477             case 150:
1478                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1479                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1480                 break;
1481
1482             case 175:
1483                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1484                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1485                 break;
1486
1487             case 200:
1488                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1489                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1490                 break;
1491
1492             default:
1493                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1494                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1495                 break;
1496         }
1497
1498         // Set the font size title and select the current size menu item.
1499         fontSizeMenuItem.setTitle(fontSizeTitle);
1500         selectedFontSizeMenuItem.setChecked(true);
1501
1502         // Run all the other default commands.
1503         super.onPrepareOptionsMenu(menu);
1504
1505         // Display the menu.
1506         return true;
1507     }
1508
1509     @Override
1510     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1511     @SuppressLint("SetJavaScriptEnabled")
1512     // removeAllCookies is deprecated, but it is required for API < 21.
1513     @SuppressWarnings("deprecation")
1514     public boolean onOptionsItemSelected(MenuItem menuItem) {
1515         // Reenter full screen browsing mode if it was interrupted by the options menu.  <https://redmine.stoutner.com/issues/389>
1516         if (inFullScreenBrowsingMode) {
1517             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
1518             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1519
1520             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1521
1522             /* Hide the system bars.
1523              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1524              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1525              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1526              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1527              */
1528             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1529                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1530         }
1531
1532         // Get the selected menu item ID.
1533         int menuItemId = menuItem.getItemId();
1534
1535         // Run the commands that correlate to the selected menu item.
1536         switch (menuItemId) {
1537             case R.id.toggle_javascript:
1538                 // Switch the status of javaScriptEnabled.
1539                 javaScriptEnabled = !javaScriptEnabled;
1540
1541                 // Apply the new JavaScript status.
1542                 currentWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1543
1544                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1545                 updatePrivacyIcons(true);
1546
1547                 // Display a `Snackbar`.
1548                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1549                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1550                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1551                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1552                 } else {  // Privacy mode.
1553                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1554                 }
1555
1556                 // Reload the current WebView.
1557                 currentWebView.reload();
1558                 return true;
1559
1560             case R.id.add_or_edit_domain:
1561                 if (domainSettingsApplied) {  // Edit the current domain settings.
1562                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1563                     reapplyDomainSettingsOnRestart = true;
1564                     currentDomainName = "";
1565
1566                     // Create an intent to launch the domains activity.
1567                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1568
1569                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1570                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1571                     domainsIntent.putExtra("closeOnBack", true);
1572
1573                     // Make it so.
1574                     startActivity(domainsIntent);
1575                 } else {  // Add a new domain.
1576                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1577                     reapplyDomainSettingsOnRestart = true;
1578                     currentDomainName = "";
1579
1580                     // Get the current domain
1581                     Uri currentUri = Uri.parse(formattedUrlString);
1582                     String currentDomain = currentUri.getHost();
1583
1584                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1585                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1586
1587                     // Create the domain and store the database ID.
1588                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1589
1590                     // Create an intent to launch the domains activity.
1591                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1592
1593                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1594                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1595                     domainsIntent.putExtra("closeOnBack", true);
1596
1597                     // Make it so.
1598                     startActivity(domainsIntent);
1599                 }
1600                 return true;
1601
1602             case R.id.toggle_first_party_cookies:
1603                 // Switch the status of firstPartyCookiesEnabled.
1604                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1605
1606                 // Update the menu checkbox.
1607                 menuItem.setChecked(firstPartyCookiesEnabled);
1608
1609                 // Apply the new cookie status.
1610                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1611
1612                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1613                 updatePrivacyIcons(true);
1614
1615                 // Display a `Snackbar`.
1616                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1617                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1618                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
1619                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1620                 } else {  // Privacy mode.
1621                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1622                 }
1623
1624                 // Reload the current WebView.
1625                 currentWebView.reload();
1626                 return true;
1627
1628             case R.id.toggle_third_party_cookies:
1629                 if (Build.VERSION.SDK_INT >= 21) {
1630                     // Switch the status of thirdPartyCookiesEnabled.
1631                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1632
1633                     // Update the menu checkbox.
1634                     menuItem.setChecked(thirdPartyCookiesEnabled);
1635
1636                     // Apply the new cookie status.
1637                     cookieManager.setAcceptThirdPartyCookies(currentWebView, thirdPartyCookiesEnabled);
1638
1639                     // Display a `Snackbar`.
1640                     if (thirdPartyCookiesEnabled) {
1641                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1642                     } else {
1643                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1644                     }
1645
1646                     // Reload the current WebView.
1647                     currentWebView.reload();
1648                 } // Else do nothing because SDK < 21.
1649                 return true;
1650
1651             case R.id.toggle_dom_storage:
1652                 // Switch the status of domStorageEnabled.
1653                 domStorageEnabled = !domStorageEnabled;
1654
1655                 // Update the menu checkbox.
1656                 menuItem.setChecked(domStorageEnabled);
1657
1658                 // Apply the new DOM Storage status.
1659                 currentWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1660
1661                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1662                 updatePrivacyIcons(true);
1663
1664                 // Display a `Snackbar`.
1665                 if (domStorageEnabled) {
1666                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1667                 } else {
1668                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1669                 }
1670
1671                 // Reload the current WebView.
1672                 currentWebView.reload();
1673                 return true;
1674
1675             // Form data can be removed once the minimum API >= 26.
1676             case R.id.toggle_save_form_data:
1677                 // Switch the status of saveFormDataEnabled.
1678                 saveFormDataEnabled = !saveFormDataEnabled;
1679
1680                 // Update the menu checkbox.
1681                 menuItem.setChecked(saveFormDataEnabled);
1682
1683                 // Apply the new form data status.
1684                 currentWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1685
1686                 // Display a `Snackbar`.
1687                 if (saveFormDataEnabled) {
1688                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1689                 } else {
1690                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1691                 }
1692
1693                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1694                 updatePrivacyIcons(true);
1695
1696                 // Reload the current WebView.
1697                 currentWebView.reload();
1698                 return true;
1699
1700             case R.id.clear_cookies:
1701                 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1702                         .setAction(R.string.undo, v -> {
1703                             // Do nothing because everything will be handled by `onDismissed()` below.
1704                         })
1705                         .addCallback(new Snackbar.Callback() {
1706                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1707                             @Override
1708                             public void onDismissed(Snackbar snackbar, int event) {
1709                                 switch (event) {
1710                                     // The user pushed the undo button.
1711                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1712                                         // Do nothing.
1713                                         break;
1714
1715                                     // The snackbar was dismissed without the undo button being pushed.
1716                                     default:
1717                                         // `cookieManager.removeAllCookie()` varies by SDK.
1718                                         if (Build.VERSION.SDK_INT < 21) {
1719                                             cookieManager.removeAllCookie();
1720                                         } else {
1721                                             cookieManager.removeAllCookies(null);
1722                                         }
1723                                 }
1724                             }
1725                         })
1726                         .show();
1727                 return true;
1728
1729             case R.id.clear_dom_storage:
1730                 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1731                         .setAction(R.string.undo, v -> {
1732                             // Do nothing because everything will be handled by `onDismissed()` below.
1733                         })
1734                         .addCallback(new Snackbar.Callback() {
1735                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1736                             @Override
1737                             public void onDismissed(Snackbar snackbar, int event) {
1738                                 switch (event) {
1739                                     // The user pushed the undo button.
1740                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1741                                         // Do nothing.
1742                                         break;
1743
1744                                     // The snackbar was dismissed without the undo button being pushed.
1745                                     default:
1746                                         // Delete the DOM Storage.
1747                                         WebStorage webStorage = WebStorage.getInstance();
1748                                         webStorage.deleteAllData();
1749
1750                                         // Initialize a handler to manually delete the DOM storage files and directories.
1751                                         Handler deleteDomStorageHandler = new Handler();
1752
1753                                         // Setup a runnable to manually delete the DOM storage files and directories.
1754                                         Runnable deleteDomStorageRunnable = () -> {
1755                                             try {
1756                                                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1757                                                 Process deleteLocalStorageProcess = privacyBrowserRuntime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1758
1759                                                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1760                                                 Process deleteIndexProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1761                                                 Process deleteQuotaManagerProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1762                                                 Process deleteQuotaManagerJournalProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1763                                                 Process deleteDatabasesProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1764
1765                                                 // Wait for the processes to finish.
1766                                                 deleteLocalStorageProcess.waitFor();
1767                                                 deleteIndexProcess.waitFor();
1768                                                 deleteQuotaManagerProcess.waitFor();
1769                                                 deleteQuotaManagerJournalProcess.waitFor();
1770                                                 deleteDatabasesProcess.waitFor();
1771                                             } catch (Exception exception) {
1772                                                 // Do nothing if an error is thrown.
1773                                             }
1774                                         };
1775
1776                                         // Manually delete the DOM storage files after 200 milliseconds.
1777                                         deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1778                                 }
1779                             }
1780                         })
1781                         .show();
1782                 return true;
1783
1784             // Form data can be remove once the minimum API >= 26.
1785             case R.id.clear_form_data:
1786                 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1787                         .setAction(R.string.undo, v -> {
1788                             // Do nothing because everything will be handled by `onDismissed()` below.
1789                         })
1790                         .addCallback(new Snackbar.Callback() {
1791                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1792                             @Override
1793                             public void onDismissed(Snackbar snackbar, int event) {
1794                                 switch (event) {
1795                                     // The user pushed the undo button.
1796                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1797                                         // Do nothing.
1798                                         break;
1799
1800                                     // The snackbar was dismissed without the `Undo` button being pushed.
1801                                     default:
1802                                         // Delete the form data.
1803                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1804                                         mainWebViewDatabase.clearFormData();
1805                                 }
1806                             }
1807                         })
1808                         .show();
1809                 return true;
1810
1811             case R.id.easylist:
1812                 // Toggle the EasyList status.
1813                 easyListEnabled = !easyListEnabled;
1814
1815                 // Update the menu checkbox.
1816                 menuItem.setChecked(easyListEnabled);
1817
1818                 // Reload the current WebView.
1819                 currentWebView.reload();
1820                 return true;
1821
1822             case R.id.easyprivacy:
1823                 // Toggle the EasyPrivacy status.
1824                 easyPrivacyEnabled = !easyPrivacyEnabled;
1825
1826                 // Update the menu checkbox.
1827                 menuItem.setChecked(easyPrivacyEnabled);
1828
1829                 // Reload the current WebView.
1830                 currentWebView.reload();
1831                 return true;
1832
1833             case R.id.fanboys_annoyance_list:
1834                 // Toggle Fanboy's Annoyance List status.
1835                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
1836
1837                 // Update the menu checkbox.
1838                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
1839
1840                 // Update the staus of Fanboy's Social Blocking List.
1841                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
1842                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1843
1844                 // Reload the current WebView.
1845                 currentWebView.reload();
1846                 return true;
1847
1848             case R.id.fanboys_social_blocking_list:
1849                 // Toggle Fanboy's Social Blocking List status.
1850                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
1851
1852                 // Update the menu checkbox.
1853                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
1854
1855                 // Reload the current WebView.
1856                 currentWebView.reload();
1857                 return true;
1858
1859             case R.id.ultraprivacy:
1860                 // Toggle the UltraPrivacy status.
1861                 ultraPrivacyEnabled = !ultraPrivacyEnabled;
1862
1863                 // Update the menu checkbox.
1864                 menuItem.setChecked(ultraPrivacyEnabled);
1865
1866                 // Reload the current WebView.
1867                 currentWebView.reload();
1868                 return true;
1869
1870             case R.id.block_all_third_party_requests:
1871                 //Toggle the third-party requests blocker status.
1872                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
1873
1874                 // Update the menu checkbox.
1875                 menuItem.setChecked(blockAllThirdPartyRequests);
1876
1877                 // Reload the current WebView.
1878                 currentWebView.reload();
1879                 return true;
1880
1881             case R.id.user_agent_privacy_browser:
1882                 // Update the user agent.
1883                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1884
1885                 // Reload the current WebView.
1886                 currentWebView.reload();
1887                 return true;
1888
1889             case R.id.user_agent_webview_default:
1890                 // Update the user agent.
1891                 currentWebView.getSettings().setUserAgentString("");
1892
1893                 // Reload the current WebView.
1894                 currentWebView.reload();
1895                 return true;
1896
1897             case R.id.user_agent_firefox_on_android:
1898                 // Update the user agent.
1899                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1900
1901                 // Reload the current WebView.
1902                 currentWebView.reload();
1903                 return true;
1904
1905             case R.id.user_agent_chrome_on_android:
1906                 // Update the user agent.
1907                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1908
1909                 // Reload the current WebView.
1910                 currentWebView.reload();
1911                 return true;
1912
1913             case R.id.user_agent_safari_on_ios:
1914                 // Update the user agent.
1915                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1916
1917                 // Reload the current WebView.
1918                 currentWebView.reload();
1919                 return true;
1920
1921             case R.id.user_agent_firefox_on_linux:
1922                 // Update the user agent.
1923                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1924
1925                 // Reload the current WebView.
1926                 currentWebView.reload();
1927                 return true;
1928
1929             case R.id.user_agent_chromium_on_linux:
1930                 // Update the user agent.
1931                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1932
1933                 // Reload the current WebView.
1934                 currentWebView.reload();
1935                 return true;
1936
1937             case R.id.user_agent_firefox_on_windows:
1938                 // Update the user agent.
1939                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1940
1941                 // Reload the current WebView.
1942                 currentWebView.reload();
1943                 return true;
1944
1945             case R.id.user_agent_chrome_on_windows:
1946                 // Update the user agent.
1947                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1948
1949                 // Reload the current WebView.
1950                 currentWebView.reload();
1951                 return true;
1952
1953             case R.id.user_agent_edge_on_windows:
1954                 // Update the user agent.
1955                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1956
1957                 // Reload the current WebView.
1958                 currentWebView.reload();
1959                 return true;
1960
1961             case R.id.user_agent_internet_explorer_on_windows:
1962                 // Update the user agent.
1963                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1964
1965                 // Reload the current WebView.
1966                 currentWebView.reload();
1967                 return true;
1968
1969             case R.id.user_agent_safari_on_macos:
1970                 // Update the user agent.
1971                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1972
1973                 // Reload the current WebView.
1974                 currentWebView.reload();
1975                 return true;
1976
1977             case R.id.user_agent_custom:
1978                 // Update the user agent.
1979                 currentWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
1980
1981                 // Reload the current WebView.
1982                 currentWebView.reload();
1983                 return true;
1984
1985             case R.id.font_size_twenty_five_percent:
1986                 currentWebView.getSettings().setTextZoom(25);
1987                 return true;
1988
1989             case R.id.font_size_fifty_percent:
1990                 currentWebView.getSettings().setTextZoom(50);
1991                 return true;
1992
1993             case R.id.font_size_seventy_five_percent:
1994                 currentWebView.getSettings().setTextZoom(75);
1995                 return true;
1996
1997             case R.id.font_size_one_hundred_percent:
1998                 currentWebView.getSettings().setTextZoom(100);
1999                 return true;
2000
2001             case R.id.font_size_one_hundred_twenty_five_percent:
2002                 currentWebView.getSettings().setTextZoom(125);
2003                 return true;
2004
2005             case R.id.font_size_one_hundred_fifty_percent:
2006                 currentWebView.getSettings().setTextZoom(150);
2007                 return true;
2008
2009             case R.id.font_size_one_hundred_seventy_five_percent:
2010                 currentWebView.getSettings().setTextZoom(175);
2011                 return true;
2012
2013             case R.id.font_size_two_hundred_percent:
2014                 currentWebView.getSettings().setTextZoom(200);
2015                 return true;
2016
2017             case R.id.swipe_to_refresh:
2018                 // Get a handle for the swipe refresh layout.
2019                 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
2020
2021                 // Toggle swipe to refresh.
2022                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2023                 return true;
2024
2025             case R.id.display_images:
2026                 if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2027                     // Disable loading of images.
2028                     currentWebView.getSettings().setLoadsImagesAutomatically(false);
2029
2030                     // Reload the website to remove existing images.
2031                     currentWebView.reload();
2032                 } else {  // Images are not currently loaded automatically.
2033                     // Enable loading of images.  Missing images will be loaded without the need for a reload.
2034                     currentWebView.getSettings().setLoadsImagesAutomatically(true);
2035                 }
2036                 return true;
2037
2038             case R.id.night_mode:
2039                 // Toggle night mode.
2040                 nightMode = !nightMode;
2041
2042                 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2043                 if (nightMode) {  // Night mode is enabled.  Enable JavaScript.
2044                     // Update the global variable.
2045                     javaScriptEnabled = true;
2046                 } else if (domainSettingsApplied) {  // Night mode is disabled and domain settings are applied.  Set JavaScript according to the domain settings.
2047                     // Get the JavaScript preference that was stored the last time domain settings were loaded.
2048                     javaScriptEnabled = domainSettingsJavaScriptEnabled;
2049                 } else {  // Night mode is disabled and domain settings are not applied.  Set JavaScript according to the global preference.
2050                     // Get a handle for the shared preference.
2051                     SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2052
2053                     // Get the JavaScript preference.
2054                     javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
2055                 }
2056
2057                 // Apply the JavaScript setting to the WebView.
2058                 currentWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2059
2060                 // Update the privacy icons.
2061                 updatePrivacyIcons(false);
2062
2063                 // Reload the website.
2064                 currentWebView.reload();
2065                 return true;
2066
2067             case R.id.find_on_page:
2068                 // Get a handle for the views.
2069                 Toolbar toolbar = findViewById(R.id.toolbar);
2070                 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2071
2072                 // Hide the toolbar.
2073                 toolbar.setVisibility(View.GONE);
2074
2075                 // Show the find on page linear layout.
2076                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2077
2078                 // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
2079                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2080                 findOnPageEditText.postDelayed(() -> {
2081                     // Set the focus on `findOnPageEditText`.
2082                     findOnPageEditText.requestFocus();
2083
2084                     // Display the keyboard.  `0` sets no input flags.
2085                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2086                 }, 200);
2087                 return true;
2088
2089             case R.id.view_source:
2090                 // Launch the View Source activity.
2091                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2092                 startActivity(viewSourceIntent);
2093                 return true;
2094
2095             case R.id.share_url:
2096                 // Setup the share string.
2097                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2098
2099                 // Create the share intent.
2100                 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2101                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2102                 shareIntent.setType("text/plain");
2103
2104                 // Make it so.
2105                 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2106                 return true;
2107
2108             case R.id.print:
2109                 // Get a `PrintManager` instance.
2110                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2111
2112                 // Create a print document adapter form the current WebView.
2113                 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2114
2115                 // Remove the lint error below that `printManager` might be `null`.
2116                 assert printManager != null;
2117
2118                 // Print the document.  The print attributes are `null`.
2119                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2120                 return true;
2121
2122             case R.id.open_with_app:
2123                 openWithApp(formattedUrlString);
2124                 return true;
2125
2126             case R.id.open_with_browser:
2127                 openWithBrowser(formattedUrlString);
2128                 return true;
2129
2130             case R.id.add_to_homescreen:
2131                 // Instantiate the create home screen shortcut dialog.
2132                 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), formattedUrlString, favoriteIconBitmap);
2133
2134                 // Show the create home screen shortcut dialog.
2135                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2136                 return true;
2137
2138             case R.id.proxy_through_orbot:
2139                 // Toggle the proxy through Orbot variable.
2140                 proxyThroughOrbot = !proxyThroughOrbot;
2141
2142                 // Apply the proxy through Orbot settings.
2143                 applyProxyThroughOrbot(true);
2144                 return true;
2145
2146             case R.id.refresh:
2147                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2148                     // Reload the current WebView.
2149                     currentWebView.reload();
2150                 } else {  // The stop button was pushed.
2151                     // Stop the loading of the WebView.
2152                     currentWebView.stopLoading();
2153                 }
2154                 return true;
2155
2156             case R.id.ad_consent:
2157                 // Display the ad consent dialog.
2158                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2159                 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2160                 return true;
2161
2162             default:
2163                 // Don't consume the event.
2164                 return super.onOptionsItemSelected(menuItem);
2165         }
2166     }
2167
2168     // removeAllCookies is deprecated, but it is required for API < 21.
2169     @SuppressWarnings("deprecation")
2170     @Override
2171     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2172         // Get the menu item ID.
2173         int menuItemId = menuItem.getItemId();
2174
2175         // Run the commands that correspond to the selected menu item.
2176         switch (menuItemId) {
2177             case R.id.close_tab:
2178                 // Get a handle for the tab layout.
2179                 TabLayout tabLayout = findViewById(R.id.tablayout);
2180
2181                 // Get the current tab number.
2182                 int currentTabNumber = tabLayout.getSelectedTabPosition();
2183
2184                 // Delete the tab and page.
2185                 webViewPagerAdapter.deletePage(currentTabNumber);
2186                 break;
2187
2188             case R.id.clear_and_exit:
2189                 // Close the bookmarks cursor and database.
2190                 bookmarksCursor.close();
2191                 bookmarksDatabaseHelper.close();
2192
2193                 // Get a handle for the shared preferences.
2194                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2195
2196                 // Get the status of the clear everything preference.
2197                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2198
2199                 // Clear cookies.
2200                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2201                     // The command to remove cookies changed slightly in API 21.
2202                     if (Build.VERSION.SDK_INT >= 21) {
2203                         cookieManager.removeAllCookies(null);
2204                     } else {
2205                         cookieManager.removeAllCookie();
2206                     }
2207
2208                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2209                     try {
2210                         // Two commands must be used because `Runtime.exec()` does not like `*`.
2211                         Process deleteCookiesProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2212                         Process deleteCookiesJournalProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2213
2214                         // Wait until the processes have finished.
2215                         deleteCookiesProcess.waitFor();
2216                         deleteCookiesJournalProcess.waitFor();
2217                     } catch (Exception exception) {
2218                         // Do nothing if an error is thrown.
2219                     }
2220                 }
2221
2222                 // Clear DOM storage.
2223                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2224                     // Ask `WebStorage` to clear the DOM storage.
2225                     WebStorage webStorage = WebStorage.getInstance();
2226                     webStorage.deleteAllData();
2227
2228                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2229                     try {
2230                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2231                         Process deleteLocalStorageProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2232
2233                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2234                         Process deleteIndexProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2235                         Process deleteQuotaManagerProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2236                         Process deleteQuotaManagerJournalProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2237                         Process deleteDatabaseProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2238
2239                         // Wait until the processes have finished.
2240                         deleteLocalStorageProcess.waitFor();
2241                         deleteIndexProcess.waitFor();
2242                         deleteQuotaManagerProcess.waitFor();
2243                         deleteQuotaManagerJournalProcess.waitFor();
2244                         deleteDatabaseProcess.waitFor();
2245                     } catch (Exception exception) {
2246                         // Do nothing if an error is thrown.
2247                     }
2248                 }
2249
2250                 // Clear form data if the API < 26.
2251                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2252                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2253                     webViewDatabase.clearFormData();
2254
2255                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2256                     try {
2257                         // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2258                         Process deleteWebDataProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2259                         Process deleteWebDataJournalProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2260
2261                         // Wait until the processes have finished.
2262                         deleteWebDataProcess.waitFor();
2263                         deleteWebDataJournalProcess.waitFor();
2264                     } catch (Exception exception) {
2265                         // Do nothing if an error is thrown.
2266                     }
2267                 }
2268
2269                 // Clear the cache.
2270                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2271                     // Clear the cache.
2272                     // TODO
2273                     currentWebView.clearCache(true);
2274
2275                     // Manually delete the cache directories.
2276                     try {
2277                         // Delete the main cache directory.
2278                         Process deleteCacheProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2279
2280                         // Delete the secondary `Service Worker` cache directory.
2281                         // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2282                         Process deleteServiceWorkerProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2283
2284                         // Wait until the processes have finished.
2285                         deleteCacheProcess.waitFor();
2286                         deleteServiceWorkerProcess.waitFor();
2287                     } catch (Exception exception) {
2288                         // Do nothing if an error is thrown.
2289                     }
2290                 }
2291
2292                 // Clear SSL certificate preferences.
2293                 // TODO
2294                 currentWebView.clearSslPreferences();
2295
2296                 // Clear the back/forward history.
2297                 // TODO
2298                 currentWebView.clearHistory();
2299
2300                 // Clear `formattedUrlString`.
2301                 formattedUrlString = null;
2302
2303                 // Clear `customHeaders`.
2304                 customHeaders.clear();
2305
2306                 // Destroy the internal state of `mainWebView`.
2307                 // TODO
2308                 currentWebView.destroy();
2309
2310                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2311                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2312                 if (clearEverything) {
2313                     try {
2314                         // Delete the folder.
2315                         Process deleteAppWebviewProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2316
2317                         // Wait until the process has finished.
2318                         deleteAppWebviewProcess.waitFor();
2319                     } catch (Exception exception) {
2320                         // Do nothing if an error is thrown.
2321                     }
2322                 }
2323
2324                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2325                 if (Build.VERSION.SDK_INT >= 21) {
2326                     finishAndRemoveTask();
2327                 } else {
2328                     finish();
2329                 }
2330
2331                 // Remove the terminated program from RAM.  The status code is `0`.
2332                 System.exit(0);
2333                 break;
2334
2335             case R.id.home:
2336                 loadUrl(homepage);
2337                 break;
2338
2339             case R.id.back:
2340                 if (currentWebView.canGoBack()) {
2341                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2342                     formattedUrlString = "";
2343
2344                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2345                     navigatingHistory = true;
2346
2347                     // Load the previous website in the history.
2348                     currentWebView.goBack();
2349                 }
2350                 break;
2351
2352             case R.id.forward:
2353                 if (currentWebView.canGoForward()) {
2354                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2355                     formattedUrlString = "";
2356
2357                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2358                     navigatingHistory = true;
2359
2360                     // Load the next website in the history.
2361                     currentWebView.goForward();
2362                 }
2363                 break;
2364
2365             case R.id.history:
2366                 // Get the `WebBackForwardList`.
2367                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2368
2369                 // Show the URL history dialog and name this instance `R.string.history`.
2370                 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2371                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2372                 break;
2373
2374             case R.id.requests:
2375                 // Launch the requests activity.
2376                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2377                 startActivity(requestsIntent);
2378                 break;
2379
2380             case R.id.downloads:
2381                 // Launch the system Download Manager.
2382                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2383
2384                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2385                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2386
2387                 startActivity(downloadManagerIntent);
2388                 break;
2389
2390             case R.id.domains:
2391                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2392                 reapplyDomainSettingsOnRestart = true;
2393                 currentDomainName = "";
2394
2395                 // Launch the domains activity.
2396                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2397                 startActivity(domainsIntent);
2398                 break;
2399
2400             case R.id.settings:
2401                 // Set the flag to reapply app settings on restart when returning from Settings.
2402                 reapplyAppSettingsOnRestart = true;
2403
2404                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2405                 reapplyDomainSettingsOnRestart = true;
2406                 currentDomainName = "";
2407
2408                 // Launch the settings activity.
2409                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2410                 startActivity(settingsIntent);
2411                 break;
2412
2413             case R.id.import_export:
2414                 // Launch the import/export activity.
2415                 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2416                 startActivity(importExportIntent);
2417                 break;
2418
2419             case R.id.logcat:
2420                 // Launch the logcat activity.
2421                 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2422                 startActivity(logcatIntent);
2423                 break;
2424
2425             case R.id.guide:
2426                 // Launch `GuideActivity`.
2427                 Intent guideIntent = new Intent(this, GuideActivity.class);
2428                 startActivity(guideIntent);
2429                 break;
2430
2431             case R.id.about:
2432                 // Launch `AboutActivity`.
2433                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2434                 startActivity(aboutIntent);
2435                 break;
2436         }
2437
2438         // Get a handle for the drawer layout.
2439         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2440
2441         // Close the navigation drawer.
2442         drawerLayout.closeDrawer(GravityCompat.START);
2443         return true;
2444     }
2445
2446     @Override
2447     public void onPostCreate(Bundle savedInstanceState) {
2448         // Run the default commands.
2449         super.onPostCreate(savedInstanceState);
2450
2451         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2452         actionBarDrawerToggle.syncState();
2453     }
2454
2455     @Override
2456     public void onConfigurationChanged(Configuration newConfig) {
2457         // Run the default commands.
2458         super.onConfigurationChanged(newConfig);
2459
2460         // Get the status bar pixel size.
2461         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2462         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2463
2464         // Get the resource density.
2465         float screenDensity = getResources().getDisplayMetrics().density;
2466
2467         // Recalculate the drawer header padding.
2468         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2469         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2470         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2471
2472         // Reload the ad for the free flavor if not in full screen mode.
2473         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2474             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2475             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2476         }
2477
2478         // `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:
2479         // https://code.google.com/p/android/issues/detail?id=20493#c8
2480         // ActivityCompat.invalidateOptionsMenu(this);
2481     }
2482
2483     @Override
2484     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2485         // Store the `HitTestResult`.
2486         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2487
2488         // Create strings.
2489         final String imageUrl;
2490         final String linkUrl;
2491
2492         // Get a handle for the the clipboard and fragment managers.
2493         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2494         FragmentManager fragmentManager = getSupportFragmentManager();
2495
2496         // Remove the lint errors below that `clipboardManager` might be `null`.
2497         assert clipboardManager != null;
2498
2499         switch (hitTestResult.getType()) {
2500             // `SRC_ANCHOR_TYPE` is a link.
2501             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2502                 // Get the target URL.
2503                 linkUrl = hitTestResult.getExtra();
2504
2505                 // Set the target URL as the title of the `ContextMenu`.
2506                 menu.setHeaderTitle(linkUrl);
2507
2508                 // Add a Load URL entry.
2509                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2510                     loadUrl(linkUrl);
2511                     return false;
2512                 });
2513
2514                 // Add a Copy URL entry.
2515                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2516                     // Save the link URL in a `ClipData`.
2517                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2518
2519                     // Set the `ClipData` as the clipboard's primary clip.
2520                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2521                     return false;
2522                 });
2523
2524                 // Add a Download URL entry.
2525                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2526                     // Check if the download should be processed by an external app.
2527                     if (downloadWithExternalApp) {  // Download with an external app.
2528                         openUrlWithExternalApp(linkUrl);
2529                     } else {  // Download with Android's download manager.
2530                         // Check to see if the storage permission has already been granted.
2531                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2532                             // Store the variables for future use by `onRequestPermissionsResult()`.
2533                             downloadUrl = linkUrl;
2534                             downloadContentDisposition = "none";
2535                             downloadContentLength = -1;
2536
2537                             // Show a dialog if the user has previously denied the permission.
2538                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2539                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2540                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2541
2542                                 // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2543                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2544                             } else {  // Show the permission request directly.
2545                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2546                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2547                             }
2548                         } else {  // The storage permission has already been granted.
2549                             // Get a handle for the download file alert dialog.
2550                             DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2551
2552                             // Show the download file alert dialog.
2553                             downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2554                         }
2555                     }
2556                     return false;
2557                 });
2558
2559                 // Add an Open with App entry.
2560                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2561                     openWithApp(linkUrl);
2562                     return false;
2563                 });
2564
2565                 // Add an Open with Browser entry.
2566                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2567                     openWithBrowser(linkUrl);
2568                     return false;
2569                 });
2570
2571                 // Add a Cancel entry, which by default closes the context menu.
2572                 menu.add(R.string.cancel);
2573                 break;
2574
2575             case WebView.HitTestResult.EMAIL_TYPE:
2576                 // Get the target URL.
2577                 linkUrl = hitTestResult.getExtra();
2578
2579                 // Set the target URL as the title of the `ContextMenu`.
2580                 menu.setHeaderTitle(linkUrl);
2581
2582                 // Add a Write Email entry.
2583                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2584                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2585                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2586
2587                     // Parse the url and set it as the data for the `Intent`.
2588                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2589
2590                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2591                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2592
2593                     // Make it so.
2594                     startActivity(emailIntent);
2595                     return false;
2596                 });
2597
2598                 // Add a Copy Email Address entry.
2599                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2600                     // Save the email address in a `ClipData`.
2601                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2602
2603                     // Set the `ClipData` as the clipboard's primary clip.
2604                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2605                     return false;
2606                 });
2607
2608                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2609                 menu.add(R.string.cancel);
2610                 break;
2611
2612             // `IMAGE_TYPE` is an image.
2613             case WebView.HitTestResult.IMAGE_TYPE:
2614                 // Get the image URL.
2615                 imageUrl = hitTestResult.getExtra();
2616
2617                 // Set the image URL as the title of the `ContextMenu`.
2618                 menu.setHeaderTitle(imageUrl);
2619
2620                 // Add a View Image entry.
2621                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2622                     loadUrl(imageUrl);
2623                     return false;
2624                 });
2625
2626                 // Add a Download Image entry.
2627                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2628                     // Check if the download should be processed by an external app.
2629                     if (downloadWithExternalApp) {  // Download with an external app.
2630                         openUrlWithExternalApp(imageUrl);
2631                     } else {  // Download with Android's download manager.
2632                         // Check to see if the storage permission has already been granted.
2633                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2634                             // Store the image URL for use by `onRequestPermissionResult()`.
2635                             downloadImageUrl = imageUrl;
2636
2637                             // Show a dialog if the user has previously denied the permission.
2638                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2639                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2640                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2641
2642                                 // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2643                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2644                             } else {  // Show the permission request directly.
2645                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2646                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2647                             }
2648                         } else {  // The storage permission has already been granted.
2649                             // Get a handle for the download image alert dialog.
2650                             DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2651
2652                             // Show the download image alert dialog.
2653                             downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2654                         }
2655                     }
2656                     return false;
2657                 });
2658
2659                 // Add a Copy URL entry.