Move Clear and Exit to the top of the navigation menu. https://redmine.stoutner...
[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                 // Store the current WebView.
711                 currentWebView = (NestedScrollWebView) webViewFragment.getView();
712
713                 // 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.
714                 if (tabLayout.getSelectedTabPosition() != position) {
715                     // Get a handle for the corresponding tab.
716                     TabLayout.Tab correspondingTab = tabLayout.getTabAt(position);
717
718                     // Assert that the corresponding tab is not null.
719                     assert correspondingTab != null;
720
721                     // Select the corresponding tab.
722                     correspondingTab.select();
723                 }
724             }
725
726             @Override
727             public void onPageScrollStateChanged(int state) {
728                 // Do nothing.
729             }
730         });
731
732         // Display the View SSL Certificate dialog when the currently selected tab is reselected.
733         tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
734             @Override
735             public void onTabSelected(TabLayout.Tab tab) {
736                 // Select the same page in the view pager.
737                 webViewPager.setCurrentItem(tab.getPosition());
738             }
739
740             @Override
741             public void onTabUnselected(TabLayout.Tab tab) {
742                 // Do nothing.
743             }
744
745             @Override
746             public void onTabReselected(TabLayout.Tab tab) {
747                 // Instantiate the View SSL Certificate dialog.
748                 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
749
750                 // Display the View SSL Certificate dialog.
751                 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
752             }
753         });
754
755         // Add the first tab.
756         webViewPagerAdapter.addPage();
757
758         // 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.
759         if (darkTheme) {
760             launchBookmarksActivityFab.setImageDrawable(resources.getDrawable(R.drawable.bookmarks_dark));
761             createBookmarkFolderFab.setImageDrawable(resources.getDrawable(R.drawable.create_folder_dark));
762             createBookmarkFab.setImageDrawable(resources.getDrawable(R.drawable.create_bookmark_dark));
763             bookmarksListView.setBackgroundColor(resources.getColor(R.color.gray_850));
764         } else {
765             launchBookmarksActivityFab.setImageDrawable(resources.getDrawable(R.drawable.bookmarks_light));
766             createBookmarkFolderFab.setImageDrawable(resources.getDrawable(R.drawable.create_folder_light));
767             createBookmarkFab.setImageDrawable(resources.getDrawable(R.drawable.create_bookmark_light));
768             bookmarksListView.setBackgroundColor(resources.getColor(R.color.white));
769         }
770
771         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
772         launchBookmarksActivityFab.setOnClickListener(v -> {
773             // Create an intent to launch the bookmarks activity.
774             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
775
776             // Include the current folder with the `Intent`.
777             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
778
779             // Make it so.
780             startActivity(bookmarksIntent);
781         });
782
783         // Set the create new bookmark folder FAB to display an alert dialog.
784         createBookmarkFolderFab.setOnClickListener(v -> {
785             // Show the create bookmark folder dialog and name the instance `@string/create_folder`.
786             DialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
787             createBookmarkFolderDialog.show(fragmentManager, resources.getString(R.string.create_folder));
788         });
789
790         // Set the create new bookmark FAB to display an alert dialog.
791         createBookmarkFab.setOnClickListener(view -> {
792             // Show the create bookmark dialog and name the instance `@string/create_bookmark`.
793             DialogFragment createBookmarkDialog = new CreateBookmarkDialog();
794             createBookmarkDialog.show(fragmentManager, resources.getString(R.string.create_bookmark));
795         });
796
797         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
798         findOnPageEditText.addTextChangedListener(new TextWatcher() {
799             @Override
800             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
801                 // Do nothing.
802             }
803
804             @Override
805             public void onTextChanged(CharSequence s, int start, int before, int count) {
806                 // Do nothing.
807             }
808
809             @Override
810             public void afterTextChanged(Editable s) {
811                 // Search for the text in `mainWebView`.
812                 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
813             }
814         });
815
816         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
817         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
818             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
819                 // Hide the soft keyboard.  `0` indicates no additional flags.
820                 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
821
822                 // Consume the event.
823                 return true;
824             } else {  // A different key was pressed.
825                 // Do not consume the event.
826                 return false;
827             }
828         });
829
830         // Implement swipe to refresh.
831         swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
832
833         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
834         swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
835
836         // Set the swipe to refresh color according to the theme.
837         if (darkTheme) {
838             swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
839             swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
840         } else {
841             swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
842         }
843
844         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
845         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
846         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
847
848         // Initialize the bookmarks database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
849         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
850
851         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
852         currentBookmarksFolder = "";
853
854         // Load the home folder, which is `""` in the database.
855         loadBookmarksFolder();
856
857         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
858             // Convert the id from long to int to match the format of the bookmarks database.
859             int databaseID = (int) id;
860
861             // Get the bookmark cursor for this ID and move it to the first row.
862             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
863             bookmarkCursor.moveToFirst();
864
865             // Act upon the bookmark according to the type.
866             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
867                 // Store the new folder name in `currentBookmarksFolder`.
868                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
869
870                 // Load the new folder.
871                 loadBookmarksFolder();
872             } else {  // The selected bookmark is not a folder.
873                 // Load the bookmark URL.
874                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
875
876                 // Close the bookmarks drawer.
877                 drawerLayout.closeDrawer(GravityCompat.END);
878             }
879
880             // Close the `Cursor`.
881             bookmarkCursor.close();
882         });
883
884         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
885             // Convert the database ID from `long` to `int`.
886             int databaseId = (int) id;
887
888             // Find out if the selected bookmark is a folder.
889             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
890
891             if (isFolder) {
892                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
893                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
894
895                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
896                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
897                 editBookmarkFolderDialog.show(fragmentManager, resources.getString(R.string.edit_folder));
898             } else {
899                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
900                 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
901                 editBookmarkDialog.show(fragmentManager, resources.getString(R.string.edit_bookmark));
902             }
903
904             // Consume the event.
905             return true;
906         });
907
908         // Get the status bar pixel size.
909         int statusBarResourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
910         int statusBarPixelSize = resources.getDimensionPixelSize(statusBarResourceId);
911
912         // Get the resource density.
913         float screenDensity = resources.getDisplayMetrics().density;
914
915         // Calculate the drawer header padding.  This is used to move the text in the drawer headers below any cutouts.
916         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
917         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
918         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
919
920         // The drawer listener is used to update the navigation menu.`
921         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
922             @Override
923             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
924             }
925
926             @Override
927             public void onDrawerOpened(@NonNull View drawerView) {
928             }
929
930             @Override
931             public void onDrawerClosed(@NonNull View drawerView) {
932             }
933
934             @Override
935             public void onDrawerStateChanged(int newState) {
936                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
937                     // Get handles for the drawer headers.
938                     TextView navigationHeaderTextView = findViewById(R.id.navigationText);
939                     TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
940
941                     // 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.
942                     if (navigationHeaderTextView != null) {
943                         navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
944                     }
945
946                     // 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.
947                     if (bookmarksHeaderTextView != null) {
948                         bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
949                     }
950
951                     // Update the navigation menu items.
952                     navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
953                     navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
954                     navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
955                     navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
956                     navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
957
958                     // Hide the keyboard (if displayed).
959                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
960
961                     // 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.
962                     urlTextBox.clearFocus();
963                     currentWebView.clearFocus();
964                 }
965             }
966         });
967
968         // Create the hamburger icon at the start of the AppBar.
969         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
970
971         // Initialize cookieManager.
972         cookieManager = CookieManager.getInstance();
973
974         // 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).
975         customHeaders.put("X-Requested-With", "");
976
977         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
978         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
979
980         // Get a handle for the `Runtime`.
981         privacyBrowserRuntime = Runtime.getRuntime();
982
983         // Store the application's private data directory.
984         privateDataDirectoryString = getApplicationInfo().dataDir;
985         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
986
987         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
988         inFullScreenBrowsingMode = false;
989
990         // Initialize the privacy settings variables.
991         javaScriptEnabled = false;
992         firstPartyCookiesEnabled = false;
993         thirdPartyCookiesEnabled = false;
994         domStorageEnabled = false;
995         saveFormDataEnabled = false;  // Form data can be removed once the minimum API >= 26.
996         nightMode = false;
997
998         // Store the default user agent.
999         // TODO webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1000
1001         // Initialize the WebView title.
1002         webViewTitle = getString(R.string.no_title);
1003
1004         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1005         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1006         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1007         assert favoriteIconBitmapDrawable != null;
1008         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1009
1010         // If the favorite icon is null, load the default.
1011         if (favoriteIconBitmap == null) {
1012             favoriteIconBitmap = favoriteIconDefaultBitmap;
1013         }
1014
1015         // Initialize the user agent array adapter and string array.
1016         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
1017         userAgentDataArray = resources.getStringArray(R.array.user_agent_data);
1018
1019         // Get the intent that started the app.
1020         Intent launchingIntent = getIntent();
1021
1022         // Get the information from the intent.
1023         String launchingIntentAction = launchingIntent.getAction();
1024         Uri launchingIntentUriData = launchingIntent.getData();
1025
1026         // If the intent action is a web search, perform the search.
1027         if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
1028             // Create an encoded URL string.
1029             String encodedUrlString;
1030
1031             // Sanitize the search input and convert it to a search.
1032             try {
1033                 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
1034             } catch (UnsupportedEncodingException exception) {
1035                 encodedUrlString = "";
1036             }
1037
1038             // Add the base search URL.
1039             formattedUrlString = searchURL + encodedUrlString;
1040         } else if (launchingIntentUriData != null){  // Check to see if the intent contains a new URL.
1041             // Set the formatted URL string.
1042             formattedUrlString = launchingIntentUriData.toString();
1043         }
1044     }
1045
1046     @Override
1047     protected void onNewIntent(Intent intent) {
1048         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1049         setIntent(intent);
1050
1051         // Get the information from the intent.
1052         String intentAction = intent.getAction();
1053         Uri intentUriData = intent.getData();
1054
1055         // If the intent action is a web search, perform the search.
1056         if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
1057             // Create an encoded URL string.
1058             String encodedUrlString;
1059
1060             // Sanitize the search input and convert it to a search.
1061             try {
1062                 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
1063             } catch (UnsupportedEncodingException exception) {
1064                 encodedUrlString = "";
1065             }
1066
1067             // Add the base search URL.
1068             formattedUrlString = searchURL + encodedUrlString;
1069         } else if (intentUriData != null){  // Check to see if the intent contains a new URL.
1070             // Set the formatted URL string.
1071             formattedUrlString = intentUriData.toString();
1072         }
1073
1074         // Load the URL.
1075         loadUrl(formattedUrlString);
1076
1077         // Get a handle for the drawer layout.
1078         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1079
1080         // Close the navigation drawer if it is open.
1081         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1082             drawerLayout.closeDrawer(GravityCompat.START);
1083         }
1084
1085         // Close the bookmarks drawer if it is open.
1086         if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1087             drawerLayout.closeDrawer(GravityCompat.END);
1088         }
1089
1090         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1091         currentWebView.requestFocus();
1092     }
1093
1094     @Override
1095     public void onRestart() {
1096         // Run the default commands.
1097         super.onRestart();
1098
1099         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1100         if (proxyThroughOrbot) {
1101             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1102             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1103
1104             // Send the intent to the Orbot package.
1105             orbotIntent.setPackage("org.torproject.android");
1106
1107             // Make it so.
1108             sendBroadcast(orbotIntent);
1109         }
1110
1111         // Apply the app settings if returning from the Settings activity..
1112         if (reapplyAppSettingsOnRestart) {
1113             // Apply the app settings.
1114             applyAppSettings();
1115
1116             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1117             if (reloadOnRestart) {
1118                 // Reload the WebViews.
1119                 // TODO
1120                 currentWebView.reload();
1121
1122                 // Reset `reloadOnRestartBoolean`.
1123                 reloadOnRestart = false;
1124             }
1125
1126             // Reset the return from settings flag.
1127             reapplyAppSettingsOnRestart = false;
1128         }
1129
1130         // Apply the domain settings if returning from the Domains activity.
1131         if (reapplyDomainSettingsOnRestart) {
1132             // Reapply the domain settings.
1133             applyDomainSettings(formattedUrlString, false, true);
1134
1135             // Reset `reapplyDomainSettingsOnRestart`.
1136             reapplyDomainSettingsOnRestart = false;
1137         }
1138
1139         // Load the URL on restart to apply changes to night mode.
1140         if (loadUrlOnRestart) {
1141             // Load the current `formattedUrlString`.
1142             loadUrl(formattedUrlString);
1143
1144             // Reset `loadUrlOnRestart.
1145             loadUrlOnRestart = false;
1146         }
1147
1148         // Update the bookmarks drawer if returning from the Bookmarks activity.
1149         if (restartFromBookmarksActivity) {
1150             // Get a handle for the drawer layout.
1151             DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1152
1153             // Close the bookmarks drawer.
1154             drawerLayout.closeDrawer(GravityCompat.END);
1155
1156             // Reload the bookmarks drawer.
1157             loadBookmarksFolder();
1158
1159             // Reset `restartFromBookmarksActivity`.
1160             restartFromBookmarksActivity = false;
1161         }
1162
1163         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1164         updatePrivacyIcons(true);
1165     }
1166
1167     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1168     @Override
1169     public void onResume() {
1170         // Run the default commands.
1171         super.onResume();
1172
1173         // Resume JavaScript (if enabled).
1174         // TODO mainWebView.resumeTimers();
1175
1176         // Resume `mainWebView`.
1177         // TODO mainWebView.onResume();
1178
1179         // Display a message to the user if waiting for Orbot.
1180         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1181             // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1182             currentWebView.getSettings().setUseWideViewPort(false);
1183
1184             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1185             currentWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
1186         }
1187
1188         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
1189             // Get a handle for the root frame layouts.
1190             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1191
1192             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
1193             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1194
1195             /* Hide the system bars.
1196              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1197              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1198              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1199              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1200              */
1201             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1202                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1203         } else if (BuildConfig.FLAVOR.contentEquals("free")) {  // Resume the adView for the free flavor.
1204             // Resume the ad.
1205             AdHelper.resumeAd(findViewById(R.id.adview));
1206         }
1207     }
1208
1209     @Override
1210     public void onPause() {
1211         // Run the default commands.
1212         super.onPause();
1213
1214         // Pause `mainWebView`.
1215         // TODO
1216         currentWebView.onPause();
1217
1218         // Stop all JavaScript.
1219         // TODO
1220         currentWebView.pauseTimers();
1221
1222         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1223         if (BuildConfig.FLAVOR.contentEquals("free")) {
1224             // Pause the ad.
1225             AdHelper.pauseAd(findViewById(R.id.adview));
1226         }
1227     }
1228
1229     @Override
1230     public void onDestroy() {
1231         // Unregister the Orbot status broadcast receiver.
1232         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1233
1234         // Close the bookmarks cursor and database.
1235         bookmarksCursor.close();
1236         bookmarksDatabaseHelper.close();
1237
1238         // Run the default commands.
1239         super.onDestroy();
1240     }
1241
1242     @Override
1243     public boolean onCreateOptionsMenu(Menu menu) {
1244         // Inflate the menu.  This adds items to the action bar if it is present.
1245         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1246
1247         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1248         mainMenu = menu;
1249
1250         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1251         updatePrivacyIcons(false);
1252
1253         // Get handles for the menu items.
1254         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1255         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1256         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1257         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1258         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1259         refreshMenuItem = menu.findItem(R.id.refresh);
1260         blocklistsMenuItem = menu.findItem(R.id.blocklists);
1261         easyListMenuItem = menu.findItem(R.id.easylist);
1262         easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1263         fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1264         fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1265         ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1266         blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1267         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1268
1269         // Only display third-party cookies if API >= 21
1270         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1271
1272         // Only display the form data menu items if the API < 26.
1273         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1274         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1275
1276         // Only show Ad Consent if this is the free flavor.
1277         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1278
1279         // Get the shared preference values.
1280         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1281
1282         // Get the status of the additional AppBar icons.
1283         displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1284
1285         // 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.
1286         if (displayAdditionalAppBarIcons) {
1287             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1288             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1289             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1290         } else { //Do not display the additional icons.
1291             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1292             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1293             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1294         }
1295
1296         // Replace Refresh with Stop if a URL is already loading.
1297         if (urlIsLoading) {
1298             // Set the title.
1299             refreshMenuItem.setTitle(R.string.stop);
1300
1301             // If the icon is displayed in the AppBar, set it according to the theme.
1302             if (displayAdditionalAppBarIcons) {
1303                 if (darkTheme) {
1304                     refreshMenuItem.setIcon(R.drawable.close_dark);
1305                 } else {
1306                     refreshMenuItem.setIcon(R.drawable.close_light);
1307                 }
1308             }
1309         }
1310
1311         return true;
1312     }
1313
1314     @Override
1315     public boolean onPrepareOptionsMenu(Menu menu) {
1316         // Get a handle for the swipe refresh layout.
1317         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1318
1319         // Get handles for the menu items.
1320         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1321         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1322         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1323         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1324         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1325         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1326         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1327         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1328         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1329         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1330         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1331         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1332         MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1333         MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1334
1335         // Set the text for the domain menu item.
1336         if (domainSettingsApplied) {
1337             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1338         } else {
1339             addOrEditDomain.setTitle(R.string.add_domain_settings);
1340         }
1341
1342         // Set the status of the menu item checkboxes.
1343         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1344         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1345         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1346         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1347         easyListMenuItem.setChecked(easyListEnabled);
1348         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1349         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1350         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1351         ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1352         blockAllThirdPartyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1353         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1354         // TODO displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1355         nightModeMenuItem.setChecked(nightMode);
1356         proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1357
1358         // Enable third-party cookies if first-party cookies are enabled.
1359         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1360
1361         // Enable DOM Storage if JavaScript is enabled.
1362         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1363
1364         // Enable Clear Cookies if there are any.
1365         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1366
1367         // Get a count of the number of files in the Local Storage directory.
1368         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1369         int localStorageDirectoryNumberOfFiles = 0;
1370         if (localStorageDirectory.exists()) {
1371             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1372         }
1373
1374         // Get a count of the number of files in the IndexedDB directory.
1375         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1376         int indexedDBDirectoryNumberOfFiles = 0;
1377         if (indexedDBDirectory.exists()) {
1378             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1379         }
1380
1381         // Enable Clear DOM Storage if there is any.
1382         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1383
1384         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1385         if (Build.VERSION.SDK_INT < 26) {
1386             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1387             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1388         } else {
1389             // Disable clear form data because it is not supported on current version of Android.
1390             clearFormDataMenuItem.setEnabled(false);
1391         }
1392
1393         // Enable Clear Data if any of the submenu items are enabled.
1394         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1395
1396         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1397         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1398
1399         // Initialize the display names for the blocklists with the number of blocked requests.
1400         blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
1401         easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1402         easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1403         fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1404         fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1405         ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1406         blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1407
1408         // Get the current user agent.
1409         // TODO String currentUserAgent = mainWebView.getSettings().getUserAgentString();
1410         String currentUserAgent = "";
1411
1412         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1413         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1414             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1415         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1416             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1417         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1418             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1419         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1420             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1421         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1422             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1423         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1424             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1425         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1426             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1427         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1428             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1429         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1430             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1431         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1432             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1433         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1434             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1435         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1436             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1437         } else {  // Custom user agent.
1438             menu.findItem(R.id.user_agent_custom).setChecked(true);
1439         }
1440
1441         // Initialize font size variables.
1442         // TODO int fontSize = mainWebView.getSettings().getTextZoom();
1443         int fontSize = 100;
1444         String fontSizeTitle;
1445         MenuItem selectedFontSizeMenuItem;
1446
1447         // Prepare the font size title and current size menu item.
1448         switch (fontSize) {
1449             case 25:
1450                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1451                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1452                 break;
1453
1454             case 50:
1455                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1456                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1457                 break;
1458
1459             case 75:
1460                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1461                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1462                 break;
1463
1464             case 100:
1465                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1466                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1467                 break;
1468
1469             case 125:
1470                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1471                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1472                 break;
1473
1474             case 150:
1475                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1476                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1477                 break;
1478
1479             case 175:
1480                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1481                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1482                 break;
1483
1484             case 200:
1485                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1486                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1487                 break;
1488
1489             default:
1490                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1491                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1492                 break;
1493         }
1494
1495         // Set the font size title and select the current size menu item.
1496         fontSizeMenuItem.setTitle(fontSizeTitle);
1497         selectedFontSizeMenuItem.setChecked(true);
1498
1499         // Run all the other default commands.
1500         super.onPrepareOptionsMenu(menu);
1501
1502         // Display the menu.
1503         return true;
1504     }
1505
1506     @Override
1507     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1508     @SuppressLint("SetJavaScriptEnabled")
1509     // removeAllCookies is deprecated, but it is required for API < 21.
1510     @SuppressWarnings("deprecation")
1511     public boolean onOptionsItemSelected(MenuItem menuItem) {
1512         // Reenter full screen browsing mode if it was interrupted by the options menu.  <https://redmine.stoutner.com/issues/389>
1513         if (inFullScreenBrowsingMode) {
1514             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
1515             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1516
1517             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1518
1519             /* Hide the system bars.
1520              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1521              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1522              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1523              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1524              */
1525             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1526                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1527         }
1528
1529         // Get the selected menu item ID.
1530         int menuItemId = menuItem.getItemId();
1531
1532         // Run the commands that correlate to the selected menu item.
1533         switch (menuItemId) {
1534             case R.id.toggle_javascript:
1535                 // Switch the status of javaScriptEnabled.
1536                 javaScriptEnabled = !javaScriptEnabled;
1537
1538                 // Apply the new JavaScript status.
1539                 currentWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1540
1541                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1542                 updatePrivacyIcons(true);
1543
1544                 // Display a `Snackbar`.
1545                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1546                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1547                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1548                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1549                 } else {  // Privacy mode.
1550                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1551                 }
1552
1553                 // Reload the current WebView.
1554                 currentWebView.reload();
1555                 return true;
1556
1557             case R.id.add_or_edit_domain:
1558                 if (domainSettingsApplied) {  // Edit the current domain settings.
1559                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1560                     reapplyDomainSettingsOnRestart = true;
1561                     currentDomainName = "";
1562
1563                     // Create an intent to launch the domains activity.
1564                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1565
1566                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1567                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1568                     domainsIntent.putExtra("closeOnBack", true);
1569
1570                     // Make it so.
1571                     startActivity(domainsIntent);
1572                 } else {  // Add a new domain.
1573                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1574                     reapplyDomainSettingsOnRestart = true;
1575                     currentDomainName = "";
1576
1577                     // Get the current domain
1578                     Uri currentUri = Uri.parse(formattedUrlString);
1579                     String currentDomain = currentUri.getHost();
1580
1581                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1582                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1583
1584                     // Create the domain and store the database ID.
1585                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1586
1587                     // Create an intent to launch the domains activity.
1588                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1589
1590                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1591                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1592                     domainsIntent.putExtra("closeOnBack", true);
1593
1594                     // Make it so.
1595                     startActivity(domainsIntent);
1596                 }
1597                 return true;
1598
1599             case R.id.toggle_first_party_cookies:
1600                 // Switch the status of firstPartyCookiesEnabled.
1601                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1602
1603                 // Update the menu checkbox.
1604                 menuItem.setChecked(firstPartyCookiesEnabled);
1605
1606                 // Apply the new cookie status.
1607                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1608
1609                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1610                 updatePrivacyIcons(true);
1611
1612                 // Display a `Snackbar`.
1613                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1614                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1615                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
1616                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1617                 } else {  // Privacy mode.
1618                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1619                 }
1620
1621                 // Reload the current WebView.
1622                 currentWebView.reload();
1623                 return true;
1624
1625             case R.id.toggle_third_party_cookies:
1626                 if (Build.VERSION.SDK_INT >= 21) {
1627                     // Switch the status of thirdPartyCookiesEnabled.
1628                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1629
1630                     // Update the menu checkbox.
1631                     menuItem.setChecked(thirdPartyCookiesEnabled);
1632
1633                     // Apply the new cookie status.
1634                     cookieManager.setAcceptThirdPartyCookies(currentWebView, thirdPartyCookiesEnabled);
1635
1636                     // Display a `Snackbar`.
1637                     if (thirdPartyCookiesEnabled) {
1638                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1639                     } else {
1640                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1641                     }
1642
1643                     // Reload the current WebView.
1644                     currentWebView.reload();
1645                 } // Else do nothing because SDK < 21.
1646                 return true;
1647
1648             case R.id.toggle_dom_storage:
1649                 // Switch the status of domStorageEnabled.
1650                 domStorageEnabled = !domStorageEnabled;
1651
1652                 // Update the menu checkbox.
1653                 menuItem.setChecked(domStorageEnabled);
1654
1655                 // Apply the new DOM Storage status.
1656                 currentWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1657
1658                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1659                 updatePrivacyIcons(true);
1660
1661                 // Display a `Snackbar`.
1662                 if (domStorageEnabled) {
1663                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1664                 } else {
1665                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1666                 }
1667
1668                 // Reload the current WebView.
1669                 currentWebView.reload();
1670                 return true;
1671
1672             // Form data can be removed once the minimum API >= 26.
1673             case R.id.toggle_save_form_data:
1674                 // Switch the status of saveFormDataEnabled.
1675                 saveFormDataEnabled = !saveFormDataEnabled;
1676
1677                 // Update the menu checkbox.
1678                 menuItem.setChecked(saveFormDataEnabled);
1679
1680                 // Apply the new form data status.
1681                 currentWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1682
1683                 // Display a `Snackbar`.
1684                 if (saveFormDataEnabled) {
1685                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1686                 } else {
1687                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1688                 }
1689
1690                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1691                 updatePrivacyIcons(true);
1692
1693                 // Reload the current WebView.
1694                 currentWebView.reload();
1695                 return true;
1696
1697             case R.id.clear_cookies:
1698                 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1699                         .setAction(R.string.undo, v -> {
1700                             // Do nothing because everything will be handled by `onDismissed()` below.
1701                         })
1702                         .addCallback(new Snackbar.Callback() {
1703                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1704                             @Override
1705                             public void onDismissed(Snackbar snackbar, int event) {
1706                                 switch (event) {
1707                                     // The user pushed the undo button.
1708                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1709                                         // Do nothing.
1710                                         break;
1711
1712                                     // The snackbar was dismissed without the undo button being pushed.
1713                                     default:
1714                                         // `cookieManager.removeAllCookie()` varies by SDK.
1715                                         if (Build.VERSION.SDK_INT < 21) {
1716                                             cookieManager.removeAllCookie();
1717                                         } else {
1718                                             cookieManager.removeAllCookies(null);
1719                                         }
1720                                 }
1721                             }
1722                         })
1723                         .show();
1724                 return true;
1725
1726             case R.id.clear_dom_storage:
1727                 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1728                         .setAction(R.string.undo, v -> {
1729                             // Do nothing because everything will be handled by `onDismissed()` below.
1730                         })
1731                         .addCallback(new Snackbar.Callback() {
1732                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1733                             @Override
1734                             public void onDismissed(Snackbar snackbar, int event) {
1735                                 switch (event) {
1736                                     // The user pushed the undo button.
1737                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1738                                         // Do nothing.
1739                                         break;
1740
1741                                     // The snackbar was dismissed without the undo button being pushed.
1742                                     default:
1743                                         // Delete the DOM Storage.
1744                                         WebStorage webStorage = WebStorage.getInstance();
1745                                         webStorage.deleteAllData();
1746
1747                                         // Initialize a handler to manually delete the DOM storage files and directories.
1748                                         Handler deleteDomStorageHandler = new Handler();
1749
1750                                         // Setup a runnable to manually delete the DOM storage files and directories.
1751                                         Runnable deleteDomStorageRunnable = () -> {
1752                                             try {
1753                                                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1754                                                 Process deleteLocalStorageProcess = privacyBrowserRuntime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1755
1756                                                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1757                                                 Process deleteIndexProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1758                                                 Process deleteQuotaManagerProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1759                                                 Process deleteQuotaManagerJournalProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1760                                                 Process deleteDatabasesProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1761
1762                                                 // Wait for the processes to finish.
1763                                                 deleteLocalStorageProcess.waitFor();
1764                                                 deleteIndexProcess.waitFor();
1765                                                 deleteQuotaManagerProcess.waitFor();
1766                                                 deleteQuotaManagerJournalProcess.waitFor();
1767                                                 deleteDatabasesProcess.waitFor();
1768                                             } catch (Exception exception) {
1769                                                 // Do nothing if an error is thrown.
1770                                             }
1771                                         };
1772
1773                                         // Manually delete the DOM storage files after 200 milliseconds.
1774                                         deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1775                                 }
1776                             }
1777                         })
1778                         .show();
1779                 return true;
1780
1781             // Form data can be remove once the minimum API >= 26.
1782             case R.id.clear_form_data:
1783                 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1784                         .setAction(R.string.undo, v -> {
1785                             // Do nothing because everything will be handled by `onDismissed()` below.
1786                         })
1787                         .addCallback(new Snackbar.Callback() {
1788                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1789                             @Override
1790                             public void onDismissed(Snackbar snackbar, int event) {
1791                                 switch (event) {
1792                                     // The user pushed the undo button.
1793                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1794                                         // Do nothing.
1795                                         break;
1796
1797                                     // The snackbar was dismissed without the `Undo` button being pushed.
1798                                     default:
1799                                         // Delete the form data.
1800                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1801                                         mainWebViewDatabase.clearFormData();
1802                                 }
1803                             }
1804                         })
1805                         .show();
1806                 return true;
1807
1808             case R.id.easylist:
1809                 // Toggle the EasyList status.
1810                 easyListEnabled = !easyListEnabled;
1811
1812                 // Update the menu checkbox.
1813                 menuItem.setChecked(easyListEnabled);
1814
1815                 // Reload the current WebView.
1816                 currentWebView.reload();
1817                 return true;
1818
1819             case R.id.easyprivacy:
1820                 // Toggle the EasyPrivacy status.
1821                 easyPrivacyEnabled = !easyPrivacyEnabled;
1822
1823                 // Update the menu checkbox.
1824                 menuItem.setChecked(easyPrivacyEnabled);
1825
1826                 // Reload the current WebView.
1827                 currentWebView.reload();
1828                 return true;
1829
1830             case R.id.fanboys_annoyance_list:
1831                 // Toggle Fanboy's Annoyance List status.
1832                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
1833
1834                 // Update the menu checkbox.
1835                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
1836
1837                 // Update the staus of Fanboy's Social Blocking List.
1838                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
1839                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1840
1841                 // Reload the current WebView.
1842                 currentWebView.reload();
1843                 return true;
1844
1845             case R.id.fanboys_social_blocking_list:
1846                 // Toggle Fanboy's Social Blocking List status.
1847                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
1848
1849                 // Update the menu checkbox.
1850                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
1851
1852                 // Reload the current WebView.
1853                 currentWebView.reload();
1854                 return true;
1855
1856             case R.id.ultraprivacy:
1857                 // Toggle the UltraPrivacy status.
1858                 ultraPrivacyEnabled = !ultraPrivacyEnabled;
1859
1860                 // Update the menu checkbox.
1861                 menuItem.setChecked(ultraPrivacyEnabled);
1862
1863                 // Reload the current WebView.
1864                 currentWebView.reload();
1865                 return true;
1866
1867             case R.id.block_all_third_party_requests:
1868                 //Toggle the third-party requests blocker status.
1869                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
1870
1871                 // Update the menu checkbox.
1872                 menuItem.setChecked(blockAllThirdPartyRequests);
1873
1874                 // Reload the current WebView.
1875                 currentWebView.reload();
1876                 return true;
1877
1878             case R.id.user_agent_privacy_browser:
1879                 // Update the user agent.
1880                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1881
1882                 // Reload the current WebView.
1883                 currentWebView.reload();
1884                 return true;
1885
1886             case R.id.user_agent_webview_default:
1887                 // Update the user agent.
1888                 currentWebView.getSettings().setUserAgentString("");
1889
1890                 // Reload the current WebView.
1891                 currentWebView.reload();
1892                 return true;
1893
1894             case R.id.user_agent_firefox_on_android:
1895                 // Update the user agent.
1896                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1897
1898                 // Reload the current WebView.
1899                 currentWebView.reload();
1900                 return true;
1901
1902             case R.id.user_agent_chrome_on_android:
1903                 // Update the user agent.
1904                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1905
1906                 // Reload the current WebView.
1907                 currentWebView.reload();
1908                 return true;
1909
1910             case R.id.user_agent_safari_on_ios:
1911                 // Update the user agent.
1912                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1913
1914                 // Reload the current WebView.
1915                 currentWebView.reload();
1916                 return true;
1917
1918             case R.id.user_agent_firefox_on_linux:
1919                 // Update the user agent.
1920                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1921
1922                 // Reload the current WebView.
1923                 currentWebView.reload();
1924                 return true;
1925
1926             case R.id.user_agent_chromium_on_linux:
1927                 // Update the user agent.
1928                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1929
1930                 // Reload the current WebView.
1931                 currentWebView.reload();
1932                 return true;
1933
1934             case R.id.user_agent_firefox_on_windows:
1935                 // Update the user agent.
1936                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1937
1938                 // Reload the current WebView.
1939                 currentWebView.reload();
1940                 return true;
1941
1942             case R.id.user_agent_chrome_on_windows:
1943                 // Update the user agent.
1944                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1945
1946                 // Reload the current WebView.
1947                 currentWebView.reload();
1948                 return true;
1949
1950             case R.id.user_agent_edge_on_windows:
1951                 // Update the user agent.
1952                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1953
1954                 // Reload the current WebView.
1955                 currentWebView.reload();
1956                 return true;
1957
1958             case R.id.user_agent_internet_explorer_on_windows:
1959                 // Update the user agent.
1960                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1961
1962                 // Reload the current WebView.
1963                 currentWebView.reload();
1964                 return true;
1965
1966             case R.id.user_agent_safari_on_macos:
1967                 // Update the user agent.
1968                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1969
1970                 // Reload the current WebView.
1971                 currentWebView.reload();
1972                 return true;
1973
1974             case R.id.user_agent_custom:
1975                 // Update the user agent.
1976                 currentWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
1977
1978                 // Reload the current WebView.
1979                 currentWebView.reload();
1980                 return true;
1981
1982             case R.id.font_size_twenty_five_percent:
1983                 currentWebView.getSettings().setTextZoom(25);
1984                 return true;
1985
1986             case R.id.font_size_fifty_percent:
1987                 currentWebView.getSettings().setTextZoom(50);
1988                 return true;
1989
1990             case R.id.font_size_seventy_five_percent:
1991                 currentWebView.getSettings().setTextZoom(75);
1992                 return true;
1993
1994             case R.id.font_size_one_hundred_percent:
1995                 currentWebView.getSettings().setTextZoom(100);
1996                 return true;
1997
1998             case R.id.font_size_one_hundred_twenty_five_percent:
1999                 currentWebView.getSettings().setTextZoom(125);
2000                 return true;
2001
2002             case R.id.font_size_one_hundred_fifty_percent:
2003                 currentWebView.getSettings().setTextZoom(150);
2004                 return true;
2005
2006             case R.id.font_size_one_hundred_seventy_five_percent:
2007                 currentWebView.getSettings().setTextZoom(175);
2008                 return true;
2009
2010             case R.id.font_size_two_hundred_percent:
2011                 currentWebView.getSettings().setTextZoom(200);
2012                 return true;
2013
2014             case R.id.swipe_to_refresh:
2015                 // Get a handle for the swipe refresh layout.
2016                 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
2017
2018                 // Toggle swipe to refresh.
2019                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2020                 return true;
2021
2022             case R.id.display_images:
2023                 if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2024                     // Disable loading of images.
2025                     currentWebView.getSettings().setLoadsImagesAutomatically(false);
2026
2027                     // Reload the website to remove existing images.
2028                     currentWebView.reload();
2029                 } else {  // Images are not currently loaded automatically.
2030                     // Enable loading of images.  Missing images will be loaded without the need for a reload.
2031                     currentWebView.getSettings().setLoadsImagesAutomatically(true);
2032                 }
2033                 return true;
2034
2035             case R.id.night_mode:
2036                 // Toggle night mode.
2037                 nightMode = !nightMode;
2038
2039                 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2040                 if (nightMode) {  // Night mode is enabled.  Enable JavaScript.
2041                     // Update the global variable.
2042                     javaScriptEnabled = true;
2043                 } else if (domainSettingsApplied) {  // Night mode is disabled and domain settings are applied.  Set JavaScript according to the domain settings.
2044                     // Get the JavaScript preference that was stored the last time domain settings were loaded.
2045                     javaScriptEnabled = domainSettingsJavaScriptEnabled;
2046                 } else {  // Night mode is disabled and domain settings are not applied.  Set JavaScript according to the global preference.
2047                     // Get a handle for the shared preference.
2048                     SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2049
2050                     // Get the JavaScript preference.
2051                     javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
2052                 }
2053
2054                 // Apply the JavaScript setting to the WebView.
2055                 currentWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2056
2057                 // Update the privacy icons.
2058                 updatePrivacyIcons(false);
2059
2060                 // Reload the website.
2061                 currentWebView.reload();
2062                 return true;
2063
2064             case R.id.find_on_page:
2065                 // Get a handle for the views.
2066                 Toolbar toolbar = findViewById(R.id.toolbar);
2067                 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2068
2069                 // Hide the toolbar.
2070                 toolbar.setVisibility(View.GONE);
2071
2072                 // Show the find on page linear layout.
2073                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2074
2075                 // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
2076                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2077                 findOnPageEditText.postDelayed(() -> {
2078                     // Set the focus on `findOnPageEditText`.
2079                     findOnPageEditText.requestFocus();
2080
2081                     // Display the keyboard.  `0` sets no input flags.
2082                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2083                 }, 200);
2084                 return true;
2085
2086             case R.id.view_source:
2087                 // Launch the View Source activity.
2088                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2089                 startActivity(viewSourceIntent);
2090                 return true;
2091
2092             case R.id.share_url:
2093                 // Setup the share string.
2094                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2095
2096                 // Create the share intent.
2097                 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2098                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2099                 shareIntent.setType("text/plain");
2100
2101                 // Make it so.
2102                 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
2103                 return true;
2104
2105             case R.id.print:
2106                 // Get a `PrintManager` instance.
2107                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2108
2109                 // Create a print document adapter form the current WebView.
2110                 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
2111
2112                 // Remove the lint error below that `printManager` might be `null`.
2113                 assert printManager != null;
2114
2115                 // Print the document.  The print attributes are `null`.
2116                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2117                 return true;
2118
2119             case R.id.open_with_app:
2120                 openWithApp(formattedUrlString);
2121                 return true;
2122
2123             case R.id.open_with_browser:
2124                 openWithBrowser(formattedUrlString);
2125                 return true;
2126
2127             case R.id.add_to_homescreen:
2128                 // Instantiate the create home screen shortcut dialog.
2129                 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), formattedUrlString, favoriteIconBitmap);
2130
2131                 // Show the create home screen shortcut dialog.
2132                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2133                 return true;
2134
2135             case R.id.proxy_through_orbot:
2136                 // Toggle the proxy through Orbot variable.
2137                 proxyThroughOrbot = !proxyThroughOrbot;
2138
2139                 // Apply the proxy through Orbot settings.
2140                 applyProxyThroughOrbot(true);
2141                 return true;
2142
2143             case R.id.refresh:
2144                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2145                     // Reload the current WebView.
2146                     currentWebView.reload();
2147                 } else {  // The stop button was pushed.
2148                     // Stop the loading of the WebView.
2149                     currentWebView.stopLoading();
2150                 }
2151                 return true;
2152
2153             case R.id.ad_consent:
2154                 // Display the ad consent dialog.
2155                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2156                 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2157                 return true;
2158
2159             default:
2160                 // Don't consume the event.
2161                 return super.onOptionsItemSelected(menuItem);
2162         }
2163     }
2164
2165     // removeAllCookies is deprecated, but it is required for API < 21.
2166     @SuppressWarnings("deprecation")
2167     @Override
2168     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2169         // Get the menu item ID.
2170         int menuItemId = menuItem.getItemId();
2171
2172         // Run the commands that correspond to the selected menu item.
2173         switch (menuItemId) {
2174             case R.id.close_tab:
2175                 // Get a handle for the tab layout.
2176                 TabLayout tabLayout = findViewById(R.id.tablayout);
2177
2178                 // Get the current tab number.
2179                 int currentTabNumber = tabLayout.getSelectedTabPosition();
2180
2181                 // Delete the tab and page.
2182                 webViewPagerAdapter.deletePage(currentTabNumber);
2183                 break;
2184
2185             case R.id.clear_and_exit:
2186                 // Close the bookmarks cursor and database.
2187                 bookmarksCursor.close();
2188                 bookmarksDatabaseHelper.close();
2189
2190                 // Get a handle for the shared preferences.
2191                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2192
2193                 // Get the status of the clear everything preference.
2194                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2195
2196                 // Clear cookies.
2197                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2198                     // The command to remove cookies changed slightly in API 21.
2199                     if (Build.VERSION.SDK_INT >= 21) {
2200                         cookieManager.removeAllCookies(null);
2201                     } else {
2202                         cookieManager.removeAllCookie();
2203                     }
2204
2205                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2206                     try {
2207                         // Two commands must be used because `Runtime.exec()` does not like `*`.
2208                         Process deleteCookiesProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2209                         Process deleteCookiesJournalProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2210
2211                         // Wait until the processes have finished.
2212                         deleteCookiesProcess.waitFor();
2213                         deleteCookiesJournalProcess.waitFor();
2214                     } catch (Exception exception) {
2215                         // Do nothing if an error is thrown.
2216                     }
2217                 }
2218
2219                 // Clear DOM storage.
2220                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2221                     // Ask `WebStorage` to clear the DOM storage.
2222                     WebStorage webStorage = WebStorage.getInstance();
2223                     webStorage.deleteAllData();
2224
2225                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2226                     try {
2227                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2228                         Process deleteLocalStorageProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2229
2230                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2231                         Process deleteIndexProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2232                         Process deleteQuotaManagerProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2233                         Process deleteQuotaManagerJournalProcess = privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2234                         Process deleteDatabaseProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2235
2236                         // Wait until the processes have finished.
2237                         deleteLocalStorageProcess.waitFor();
2238                         deleteIndexProcess.waitFor();
2239                         deleteQuotaManagerProcess.waitFor();
2240                         deleteQuotaManagerJournalProcess.waitFor();
2241                         deleteDatabaseProcess.waitFor();
2242                     } catch (Exception exception) {
2243                         // Do nothing if an error is thrown.
2244                     }
2245                 }
2246
2247                 // Clear form data if the API < 26.
2248                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2249                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2250                     webViewDatabase.clearFormData();
2251
2252                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2253                     try {
2254                         // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2255                         Process deleteWebDataProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2256                         Process deleteWebDataJournalProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2257
2258                         // Wait until the processes have finished.
2259                         deleteWebDataProcess.waitFor();
2260                         deleteWebDataJournalProcess.waitFor();
2261                     } catch (Exception exception) {
2262                         // Do nothing if an error is thrown.
2263                     }
2264                 }
2265
2266                 // Clear the cache.
2267                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2268                     // Clear the cache.
2269                     // TODO
2270                     currentWebView.clearCache(true);
2271
2272                     // Manually delete the cache directories.
2273                     try {
2274                         // Delete the main cache directory.
2275                         Process deleteCacheProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2276
2277                         // Delete the secondary `Service Worker` cache directory.
2278                         // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2279                         Process deleteServiceWorkerProcess = privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2280
2281                         // Wait until the processes have finished.
2282                         deleteCacheProcess.waitFor();
2283                         deleteServiceWorkerProcess.waitFor();
2284                     } catch (Exception exception) {
2285                         // Do nothing if an error is thrown.
2286                     }
2287                 }
2288
2289                 // Clear SSL certificate preferences.
2290                 // TODO
2291                 currentWebView.clearSslPreferences();
2292
2293                 // Clear the back/forward history.
2294                 // TODO
2295                 currentWebView.clearHistory();
2296
2297                 // Clear `formattedUrlString`.
2298                 formattedUrlString = null;
2299
2300                 // Clear `customHeaders`.
2301                 customHeaders.clear();
2302
2303                 // Destroy the internal state of `mainWebView`.
2304                 // TODO
2305                 currentWebView.destroy();
2306
2307                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2308                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2309                 if (clearEverything) {
2310                     try {
2311                         // Delete the folder.
2312                         Process deleteAppWebviewProcess = privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2313
2314                         // Wait until the process has finished.
2315                         deleteAppWebviewProcess.waitFor();
2316                     } catch (Exception exception) {
2317                         // Do nothing if an error is thrown.
2318                     }
2319                 }
2320
2321                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2322                 if (Build.VERSION.SDK_INT >= 21) {
2323                     finishAndRemoveTask();
2324                 } else {
2325                     finish();
2326                 }
2327
2328                 // Remove the terminated program from RAM.  The status code is `0`.
2329                 System.exit(0);
2330                 break;
2331
2332             case R.id.home:
2333                 loadUrl(homepage);
2334                 break;
2335
2336             case R.id.back:
2337                 if (currentWebView.canGoBack()) {
2338                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2339                     formattedUrlString = "";
2340
2341                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2342                     navigatingHistory = true;
2343
2344                     // Load the previous website in the history.
2345                     currentWebView.goBack();
2346                 }
2347                 break;
2348
2349             case R.id.forward:
2350                 if (currentWebView.canGoForward()) {
2351                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2352                     formattedUrlString = "";
2353
2354                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2355                     navigatingHistory = true;
2356
2357                     // Load the next website in the history.
2358                     currentWebView.goForward();
2359                 }
2360                 break;
2361
2362             case R.id.history:
2363                 // Get the `WebBackForwardList`.
2364                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2365
2366                 // Show the URL history dialog and name this instance `R.string.history`.
2367                 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2368                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2369                 break;
2370
2371             case R.id.requests:
2372                 // Launch the requests activity.
2373                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2374                 startActivity(requestsIntent);
2375                 break;
2376
2377             case R.id.downloads:
2378                 // Launch the system Download Manager.
2379                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2380
2381                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2382                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2383
2384                 startActivity(downloadManagerIntent);
2385                 break;
2386
2387             case R.id.domains:
2388                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2389                 reapplyDomainSettingsOnRestart = true;
2390                 currentDomainName = "";
2391
2392                 // Launch the domains activity.
2393                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2394                 startActivity(domainsIntent);
2395                 break;
2396
2397             case R.id.settings:
2398                 // Set the flag to reapply app settings on restart when returning from Settings.
2399                 reapplyAppSettingsOnRestart = true;
2400
2401                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2402                 reapplyDomainSettingsOnRestart = true;
2403                 currentDomainName = "";
2404
2405                 // Launch the settings activity.
2406                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2407                 startActivity(settingsIntent);
2408                 break;
2409
2410             case R.id.import_export:
2411                 // Launch the import/export activity.
2412                 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2413                 startActivity(importExportIntent);
2414                 break;
2415
2416             case R.id.logcat:
2417                 // Launch the logcat activity.
2418                 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2419                 startActivity(logcatIntent);
2420                 break;
2421
2422             case R.id.guide:
2423                 // Launch `GuideActivity`.
2424                 Intent guideIntent = new Intent(this, GuideActivity.class);
2425                 startActivity(guideIntent);
2426                 break;
2427
2428             case R.id.about:
2429                 // Launch `AboutActivity`.
2430                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2431                 startActivity(aboutIntent);
2432                 break;
2433         }
2434
2435         // Get a handle for the drawer layout.
2436         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2437
2438         // Close the navigation drawer.
2439         drawerLayout.closeDrawer(GravityCompat.START);
2440         return true;
2441     }
2442
2443     @Override
2444     public void onPostCreate(Bundle savedInstanceState) {
2445         // Run the default commands.
2446         super.onPostCreate(savedInstanceState);
2447
2448         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2449         actionBarDrawerToggle.syncState();
2450     }
2451
2452     @Override
2453     public void onConfigurationChanged(Configuration newConfig) {
2454         // Run the default commands.
2455         super.onConfigurationChanged(newConfig);
2456
2457         // Get the status bar pixel size.
2458         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2459         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2460
2461         // Get the resource density.
2462         float screenDensity = getResources().getDisplayMetrics().density;
2463
2464         // Recalculate the drawer header padding.
2465         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2466         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2467         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2468
2469         // Reload the ad for the free flavor if not in full screen mode.
2470         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2471             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2472             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2473         }
2474
2475         // `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:
2476         // https://code.google.com/p/android/issues/detail?id=20493#c8
2477         // ActivityCompat.invalidateOptionsMenu(this);
2478     }
2479
2480     @Override
2481     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2482         // Store the `HitTestResult`.
2483         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2484
2485         // Create strings.
2486         final String imageUrl;
2487         final String linkUrl;
2488
2489         // Get a handle for the the clipboard and fragment managers.
2490         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2491         FragmentManager fragmentManager = getSupportFragmentManager();
2492
2493         // Remove the lint errors below that `clipboardManager` might be `null`.
2494         assert clipboardManager != null;
2495
2496         switch (hitTestResult.getType()) {
2497             // `SRC_ANCHOR_TYPE` is a link.
2498             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2499                 // Get the target URL.
2500                 linkUrl = hitTestResult.getExtra();
2501
2502                 // Set the target URL as the title of the `ContextMenu`.
2503                 menu.setHeaderTitle(linkUrl);
2504
2505                 // Add a Load URL entry.
2506                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2507                     loadUrl(linkUrl);
2508                     return false;
2509                 });
2510
2511                 // Add a Copy URL entry.
2512                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2513                     // Save the link URL in a `ClipData`.
2514                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2515
2516                     // Set the `ClipData` as the clipboard's primary clip.
2517                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2518                     return false;
2519                 });
2520
2521                 // Add a Download URL entry.
2522                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2523                     // Check if the download should be processed by an external app.
2524                     if (downloadWithExternalApp) {  // Download with an external app.
2525                         openUrlWithExternalApp(linkUrl);
2526                     } else {  // Download with Android's download manager.
2527                         // Check to see if the storage permission has already been granted.
2528                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2529                             // Store the variables for future use by `onRequestPermissionsResult()`.
2530                             downloadUrl = linkUrl;
2531                             downloadContentDisposition = "none";
2532                             downloadContentLength = -1;
2533
2534                             // Show a dialog if the user has previously denied the permission.
2535                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2536                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2537                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2538
2539                                 // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2540                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2541                             } else {  // Show the permission request directly.
2542                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2543                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2544                             }
2545                         } else {  // The storage permission has already been granted.
2546                             // Get a handle for the download file alert dialog.
2547                             DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2548
2549                             // Show the download file alert dialog.
2550                             downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2551                         }
2552                     }
2553                     return false;
2554                 });
2555
2556                 // Add an Open with App entry.
2557                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2558                     openWithApp(linkUrl);
2559                     return false;
2560                 });
2561
2562                 // Add an Open with Browser entry.
2563                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2564                     openWithBrowser(linkUrl);
2565                     return false;
2566                 });
2567
2568                 // Add a Cancel entry, which by default closes the context menu.
2569                 menu.add(R.string.cancel);
2570                 break;
2571
2572             case WebView.HitTestResult.EMAIL_TYPE:
2573                 // Get the target URL.
2574                 linkUrl = hitTestResult.getExtra();
2575
2576                 // Set the target URL as the title of the `ContextMenu`.
2577                 menu.setHeaderTitle(linkUrl);
2578
2579                 // Add a Write Email entry.
2580                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2581                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2582                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2583
2584                     // Parse the url and set it as the data for the `Intent`.
2585                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2586
2587                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2588                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2589
2590                     // Make it so.
2591                     startActivity(emailIntent);
2592                     return false;
2593                 });
2594
2595                 // Add a Copy Email Address entry.
2596                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2597                     // Save the email address in a `ClipData`.
2598                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2599
2600                     // Set the `ClipData` as the clipboard's primary clip.
2601                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2602                     return false;
2603                 });
2604
2605                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2606                 menu.add(R.string.cancel);
2607                 break;
2608
2609             // `IMAGE_TYPE` is an image.
2610             case WebView.HitTestResult.IMAGE_TYPE:
2611                 // Get the image URL.
2612                 imageUrl = hitTestResult.getExtra();
2613
2614                 // Set the image URL as the title of the `ContextMenu`.
2615                 menu.setHeaderTitle(imageUrl);
2616
2617                 // Add a View Image entry.
2618                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2619                     loadUrl(imageUrl);
2620                     return false;
2621                 });
2622
2623                 // Add a Download Image entry.
2624                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2625                     // Check if the download should be processed by an external app.
2626                     if (downloadWithExternalApp) {  // Download with an external app.
2627                         openUrlWithExternalApp(imageUrl);
2628                     } else {  // Download with Android's download manager.
2629                         // Check to see if the storage permission has already been granted.
2630                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2631                             // Store the image URL for use by `onRequestPermissionResult()`.
2632                             downloadImageUrl = imageUrl;
2633
2634                             // Show a dialog if the user has previously denied the permission.
2635                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2636                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2637                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2638
2639                                 // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2640                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2641                             } else {  // Show the permission request directly.
2642                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2643                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2644                             }
2645                         } else {  // The storage permission has already been granted.
2646                             // Get a handle for the download image alert dialog.
2647                             DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2648
2649                             // Show the download image alert dialog.
2650                             downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2651                         }
2652                     }
2653                     return false;
2654                 });
2655
2656                 // Add a Copy URL entry.