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