Fix a rare crash on resource requests. https://redmine.stoutner.com/issues/645
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2020 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.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.ContentResolver;
35 import android.content.Context;
36 import android.content.Intent;
37 import android.content.IntentFilter;
38 import android.content.SharedPreferences;
39 import android.content.pm.PackageManager;
40 import android.content.res.Configuration;
41 import android.database.Cursor;
42 import android.graphics.Bitmap;
43 import android.graphics.BitmapFactory;
44 import android.graphics.Typeface;
45 import android.graphics.drawable.BitmapDrawable;
46 import android.graphics.drawable.Drawable;
47 import android.net.Uri;
48 import android.net.http.SslCertificate;
49 import android.net.http.SslError;
50 import android.os.AsyncTask;
51 import android.os.Build;
52 import android.os.Bundle;
53 import android.os.Handler;
54 import android.os.Message;
55 import android.preference.PreferenceManager;
56 import android.print.PrintDocumentAdapter;
57 import android.print.PrintManager;
58 import android.text.Editable;
59 import android.text.Spanned;
60 import android.text.TextWatcher;
61 import android.text.style.ForegroundColorSpan;
62 import android.util.Patterns;
63 import android.util.TypedValue;
64 import android.view.ContextMenu;
65 import android.view.GestureDetector;
66 import android.view.KeyEvent;
67 import android.view.Menu;
68 import android.view.MenuItem;
69 import android.view.MotionEvent;
70 import android.view.View;
71 import android.view.ViewGroup;
72 import android.view.WindowManager;
73 import android.view.inputmethod.InputMethodManager;
74 import android.webkit.CookieManager;
75 import android.webkit.HttpAuthHandler;
76 import android.webkit.SslErrorHandler;
77 import android.webkit.ValueCallback;
78 import android.webkit.WebBackForwardList;
79 import android.webkit.WebChromeClient;
80 import android.webkit.WebResourceResponse;
81 import android.webkit.WebSettings;
82 import android.webkit.WebStorage;
83 import android.webkit.WebView;
84 import android.webkit.WebViewClient;
85 import android.webkit.WebViewDatabase;
86 import android.widget.ArrayAdapter;
87 import android.widget.CursorAdapter;
88 import android.widget.EditText;
89 import android.widget.FrameLayout;
90 import android.widget.ImageView;
91 import android.widget.LinearLayout;
92 import android.widget.ListView;
93 import android.widget.ProgressBar;
94 import android.widget.RadioButton;
95 import android.widget.RelativeLayout;
96 import android.widget.TextView;
97
98 import androidx.annotation.NonNull;
99 import androidx.appcompat.app.ActionBar;
100 import androidx.appcompat.app.ActionBarDrawerToggle;
101 import androidx.appcompat.app.AppCompatActivity;
102 import androidx.appcompat.app.AppCompatDelegate;
103 import androidx.appcompat.widget.Toolbar;
104 import androidx.coordinatorlayout.widget.CoordinatorLayout;
105 import androidx.core.app.ActivityCompat;
106 import androidx.core.content.ContextCompat;
107 import androidx.core.content.FileProvider;
108 import androidx.core.content.res.ResourcesCompat;
109 import androidx.core.view.GravityCompat;
110 import androidx.drawerlayout.widget.DrawerLayout;
111 import androidx.fragment.app.DialogFragment;
112 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
113 import androidx.viewpager.widget.ViewPager;
114 import androidx.webkit.WebSettingsCompat;
115 import androidx.webkit.WebViewFeature;
116
117 import com.google.android.material.appbar.AppBarLayout;
118 import com.google.android.material.floatingactionbutton.FloatingActionButton;
119 import com.google.android.material.navigation.NavigationView;
120 import com.google.android.material.snackbar.Snackbar;
121 import com.google.android.material.tabs.TabLayout;
122
123 import com.stoutner.privacybrowser.BuildConfig;
124 import com.stoutner.privacybrowser.R;
125 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
126 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
127 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
128 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
129 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
130 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
131 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
132 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
133 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
134 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
135 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
136 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
137 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
138 import com.stoutner.privacybrowser.dialogs.OpenDialog;
139 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
140 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
141 import com.stoutner.privacybrowser.dialogs.SaveWebpageDialog;
142 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
143 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
144 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
145 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
146 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
147 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
148 import com.stoutner.privacybrowser.helpers.AdHelper;
149 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
150 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
151 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
152 import com.stoutner.privacybrowser.helpers.FileNameHelper;
153 import com.stoutner.privacybrowser.helpers.ProxyHelper;
154 import com.stoutner.privacybrowser.views.NestedScrollWebView;
155
156 import java.io.ByteArrayInputStream;
157 import java.io.ByteArrayOutputStream;
158 import java.io.File;
159 import java.io.IOException;
160 import java.io.UnsupportedEncodingException;
161 import java.net.MalformedURLException;
162 import java.net.URL;
163 import java.net.URLDecoder;
164 import java.net.URLEncoder;
165 import java.text.NumberFormat;
166 import java.util.ArrayList;
167 import java.util.Date;
168 import java.util.HashMap;
169 import java.util.HashSet;
170 import java.util.List;
171 import java.util.Map;
172 import java.util.Objects;
173 import java.util.Set;
174 import java.util.concurrent.ExecutorService;
175 import java.util.concurrent.Executors;
176
177 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
178         EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
179         PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveWebpageDialog.SaveWebpageListener, StoragePermissionDialog.StoragePermissionDialogListener,
180         UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
181
182     // The executor service handles background tasks.  It is accessed from `ViewSourceActivity`.
183     public static ExecutorService executorService = Executors.newFixedThreadPool(4);
184
185     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
186     public static String orbotStatus = "unknown";
187
188     // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`.  It is also used in `onCreate()`, `onResume()`, and `addTab()`.
189     public static WebViewPagerAdapter webViewPagerAdapter;
190
191     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
192     public static boolean restartFromBookmarksActivity;
193
194     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
195     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
196     public static String currentBookmarksFolder;
197
198     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
199     public final static int UNRECOGNIZED_USER_AGENT = -1;
200     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
201     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
202     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
203     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
204     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
205
206     // Start activity for result request codes.  The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
207     public final static int BROWSE_OPEN_REQUEST_CODE = 0;
208     public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 1;
209     private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 2;
210
211     // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
212     // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
213     // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
214     public static String proxyMode = ProxyHelper.NONE;
215
216     // Define the saved instance state constants.
217     private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
218     private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
219     private final String SAVED_TAB_POSITION = "saved_tab_position";
220     private final String PROXY_MODE = "proxy_mode";
221
222     // Define the saved instance state variables.
223     private ArrayList<Bundle> savedStateArrayList;
224     private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
225     private int savedTabPosition;
226     private String savedProxyMode;
227
228     // Define the class variables.
229     @SuppressWarnings("rawtypes")
230     AsyncTask populateBlocklists;
231
232     // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
233     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
234     private NestedScrollWebView currentWebView;
235
236     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
237     private final Map<String, String> customHeaders = new HashMap<>();
238
239     // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
240     private String searchURL;
241
242     // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
243     private Menu optionsMenu;
244
245     // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
246     private ArrayList<List<String[]>> easyList;
247     private ArrayList<List<String[]>> easyPrivacy;
248     private ArrayList<List<String[]>> fanboysAnnoyanceList;
249     private ArrayList<List<String[]>> fanboysSocialList;
250     private ArrayList<List<String[]>> ultraList;
251     private ArrayList<List<String[]>> ultraPrivacy;
252
253     // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
254     private String webViewDefaultUserAgent;
255
256     // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
257     private boolean incognitoModeEnabled;
258
259     // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
260     private boolean fullScreenBrowsingModeEnabled;
261
262     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
263     private boolean inFullScreenBrowsingMode;
264
265     // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
266     private boolean hideAppBar;
267     private boolean scrollAppBar;
268
269     // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
270     private boolean loadingNewIntent;
271
272     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
273     private boolean reapplyDomainSettingsOnRestart;
274
275     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
276     private boolean reapplyAppSettingsOnRestart;
277
278     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
279     private boolean displayingFullScreenVideo;
280
281     // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
282     private BroadcastReceiver orbotStatusBroadcastReceiver;
283
284     // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
285     private boolean waitingForProxy = false;
286
287     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
288     private ActionBarDrawerToggle actionBarDrawerToggle;
289
290     // The color spans are used in `onCreate()` and `highlightUrlText()`.
291     private ForegroundColorSpan redColorSpan;
292     private ForegroundColorSpan initialGrayColorSpan;
293     private ForegroundColorSpan finalGrayColorSpan;
294
295     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
296     // and `loadBookmarksFolder()`.
297     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
298
299     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
300     private Cursor bookmarksCursor;
301
302     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
303     private CursorAdapter bookmarksCursorAdapter;
304
305     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
306     private String oldFolderNameString;
307
308     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
309     private ValueCallback<Uri[]> fileChooserCallback;
310
311     // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
312     private int appBarHeight;
313     private int defaultProgressViewStartOffset;
314     private int defaultProgressViewEndOffset;
315
316     // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
317     private boolean sanitizeGoogleAnalytics;
318     private boolean sanitizeFacebookClickIds;
319     private boolean sanitizeTwitterAmpRedirects;
320
321     // The file path strings are used in `onSaveWebpage()` and `onRequestPermissionResult()`
322     private String openFilePath;
323     private String saveWebpageUrl;
324     private String saveWebpageFilePath;
325
326     // Declare the class views.
327     private DrawerLayout drawerLayout;
328     private AppBarLayout appBarLayout;
329     private Toolbar toolbar;
330     private LinearLayout findOnPageLinearLayout;
331     private LinearLayout tabsLinearLayout;
332     private TabLayout tabLayout;
333     private SwipeRefreshLayout swipeRefreshLayout;
334     private ViewPager webViewPager;
335     private NavigationView navigationView;
336
337     // Declare the class menus.
338     private Menu navigationMenu;
339
340     // Declare the class menu items.
341     private MenuItem navigationRequestsMenuItem;
342
343     @Override
344     // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
345     @SuppressLint("ClickableViewAccessibility")
346     protected void onCreate(Bundle savedInstanceState) {
347         // Run the default commands.
348         super.onCreate(savedInstanceState);
349
350         // Check to see if the activity has been restarted.
351         if (savedInstanceState != null) {
352             // Store the saved instance state variables.
353             savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
354             savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
355             savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
356             savedProxyMode = savedInstanceState.getString(PROXY_MODE);
357         }
358
359         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
360         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
361
362         // Get a handle for the shared preferences.
363         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
364
365         // Get the screenshot preference.
366         String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
367         boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
368
369         // Get the theme entry values string array.
370         String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
371
372         // Set the app theme according to the preference.  A switch statement cannot be used because the theme entry values string array is not a compile time constant.
373         if (appTheme.equals(appThemeEntryValuesStringArray[1])) {  // The light theme is selected.
374             // Apply the light theme.
375             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
376         } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
377             // Apply the dark theme.
378             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
379         } else {  // The system default theme is selected.
380             if (Build.VERSION.SDK_INT >= 28) {  // The system default theme is supported.
381                 // Follow the system default theme.
382                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
383             } else {  // The system default theme is not supported.
384                 // Follow the battery saver mode.
385                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
386             }
387         }
388
389         // Disable screenshots if not allowed.
390         if (!allowScreenshots) {
391             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
392         }
393
394         // Enable the drawing of the entire webpage.  This makes it possible to save a website image.  This must be done before anything else happens with the WebView.
395         if (Build.VERSION.SDK_INT >= 21) {
396             WebView.enableSlowWholeDocumentDraw();
397         }
398
399         // Set the theme.
400         setTheme(R.style.PrivacyBrowser);
401
402         // Set the content view.
403         setContentView(R.layout.main_framelayout);
404
405         // Get handles for the views.
406         drawerLayout = findViewById(R.id.drawerlayout);
407         appBarLayout = findViewById(R.id.appbar_layout);
408         toolbar = findViewById(R.id.toolbar);
409         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
410         tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
411         tabLayout = findViewById(R.id.tablayout);
412         swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
413         webViewPager = findViewById(R.id.webviewpager);
414         navigationView = findViewById(R.id.navigationview);
415
416         // Get handles for the class menus.
417         navigationMenu = navigationView.getMenu();
418
419         // Get a handle for the navigation requests menu item.
420         navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
421
422         // Get a handle for the app compat delegate.
423         AppCompatDelegate appCompatDelegate = getDelegate();
424
425         // Set the support action bar.
426         appCompatDelegate.setSupportActionBar(toolbar);
427
428         // Get a handle for the action bar.
429         ActionBar actionBar = appCompatDelegate.getSupportActionBar();
430
431         // This is needed to get rid of the Android Studio warning that the action bar might be null.
432         assert actionBar != null;
433
434         // Add the custom layout, which shows the URL text bar.
435         actionBar.setCustomView(R.layout.url_app_bar);
436         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
437
438         // Create the hamburger icon at the start of the AppBar.
439         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
440
441         // Initially disable the sliding drawers.  They will be enabled once the blocklists are loaded.
442         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
443
444         // Initialize the web view pager adapter.
445         webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
446
447         // Set the pager adapter on the web view pager.
448         webViewPager.setAdapter(webViewPagerAdapter);
449
450         // Store up to 100 tabs in memory.
451         webViewPager.setOffscreenPageLimit(100);
452
453         // Initialize the app.
454         initializeApp();
455
456         // Apply the app settings from the shared preferences.
457         applyAppSettings();
458
459         // Populate the blocklists.
460         populateBlocklists = new PopulateBlocklists(this, this).execute();
461     }
462
463     @Override
464     protected void onNewIntent(Intent intent) {
465         // Run the default commands.
466         super.onNewIntent(intent);
467
468         // Replace the intent that started the app with this one.
469         setIntent(intent);
470
471         // Check to see if the app is being restarted from a saved state.
472         if (savedStateArrayList == null || savedStateArrayList.size() == 0) {  // The activity is not being restarted from a saved state.
473             // Get the information from the intent.
474             String intentAction = intent.getAction();
475             Uri intentUriData = intent.getData();
476             String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
477
478             // Determine if this is a web search.
479             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
480
481             // Only process the URI if it contains data or it is a web search.  If the user pressed the desktop icon after the app was already running the URI will be null.
482             if (intentUriData != null || intentStringExtra != null || isWebSearch) {
483                 // Get the shared preferences.
484                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
485
486                 // Create a URL string.
487                 String url;
488
489                 // If the intent action is a web search, perform the search.
490                 if (isWebSearch) {  // The intent is a web search.
491                     // Create an encoded URL string.
492                     String encodedUrlString;
493
494                     // Sanitize the search input and convert it to a search.
495                     try {
496                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
497                     } catch (UnsupportedEncodingException exception) {
498                         encodedUrlString = "";
499                     }
500
501                     // Add the base search URL.
502                     url = searchURL + encodedUrlString;
503                 } else if (intentUriData != null) {  // The intent contains a URL formatted as a URI.
504                     // Set the intent data as the URL.
505                     url = intentUriData.toString();
506                 } else {  // The intent contains a string, which might be a URL.
507                     // Set the intent string as the URL.
508                     url = intentStringExtra;
509                 }
510
511                 // Add a new tab if specified in the preferences.
512                 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) {  // Load the URL in a new tab.
513                     // Set the loading new intent flag.
514                     loadingNewIntent = true;
515
516                     // Add a new tab.
517                     addNewTab(url, true);
518                 } else {  // Load the URL in the current tab.
519                     // Make it so.
520                     loadUrl(currentWebView, url);
521                 }
522
523                 // Close the navigation drawer if it is open.
524                 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
525                     drawerLayout.closeDrawer(GravityCompat.START);
526                 }
527
528                 // Close the bookmarks drawer if it is open.
529                 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
530                     drawerLayout.closeDrawer(GravityCompat.END);
531                 }
532             }
533         }
534     }
535
536     @Override
537     public void onRestart() {
538         // Run the default commands.
539         super.onRestart();
540
541         // Apply the app settings if returning from the Settings activity.
542         if (reapplyAppSettingsOnRestart) {
543             // Reset the reapply app settings on restart tracker.
544             reapplyAppSettingsOnRestart = false;
545
546             // Apply the app settings.
547             applyAppSettings();
548         }
549
550         // Apply the domain settings if returning from the settings or domains activity.
551         if (reapplyDomainSettingsOnRestart) {
552             // Reset the reapply domain settings on restart tracker.
553             reapplyDomainSettingsOnRestart = false;
554
555             // Reapply the domain settings for each tab.
556             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
557                 // Get the WebView tab fragment.
558                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
559
560                 // Get the fragment view.
561                 View fragmentView = webViewTabFragment.getView();
562
563                 // Only reload the WebViews if they exist.
564                 if (fragmentView != null) {
565                     // Get the nested scroll WebView from the tab fragment.
566                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
567
568                     // Reset the current domain name so the domain settings will be reapplied.
569                     nestedScrollWebView.resetCurrentDomainName();
570
571                     // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
572                     if (nestedScrollWebView.getUrl() != null) {
573                         applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
574                     }
575                 }
576             }
577         }
578
579         // Update the bookmarks drawer if returning from the Bookmarks activity.
580         if (restartFromBookmarksActivity) {
581             // Close the bookmarks drawer.
582             drawerLayout.closeDrawer(GravityCompat.END);
583
584             // Reload the bookmarks drawer.
585             loadBookmarksFolder();
586
587             // Reset `restartFromBookmarksActivity`.
588             restartFromBookmarksActivity = false;
589         }
590
591         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
592         updatePrivacyIcons(true);
593     }
594
595     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
596     @Override
597     public void onResume() {
598         // Run the default commands.
599         super.onResume();
600
601         // Resume any WebViews.
602         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
603             // Get the WebView tab fragment.
604             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
605
606             // Get the fragment view.
607             View fragmentView = webViewTabFragment.getView();
608
609             // Only resume the WebViews if they exist (they won't when the app is first created).
610             if (fragmentView != null) {
611                 // Get the nested scroll WebView from the tab fragment.
612                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
613
614                 // Resume the nested scroll WebView.
615                 nestedScrollWebView.onResume();
616             }
617         }
618
619         // Resume the nested scroll WebView JavaScript timers.  This is a global command that resumes JavaScript timers on all WebViews.
620         if (currentWebView != null) {
621             currentWebView.resumeTimers();
622         }
623
624         // Reapply the proxy settings if the system is using a proxy.  This redisplays the appropriate alert dialog.
625         if (!proxyMode.equals(ProxyHelper.NONE)) {
626             applyProxy(false);
627         }
628
629         // Reapply any system UI flags and the ad in the free flavor.
630         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {  // The system is displaying a website or a video in full screen mode.
631             // Get a handle for the root frame layouts.
632             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
633
634             /* Hide the system bars.
635              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
636              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
637              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
638              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
639              */
640             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
641                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
642         } else if (BuildConfig.FLAVOR.contentEquals("free")) {  // The system in not in full screen mode.
643             // Resume the ad.
644             AdHelper.resumeAd(findViewById(R.id.adview));
645         }
646     }
647
648     @Override
649     public void onPause() {
650         // Run the default commands.
651         super.onPause();
652
653         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
654             // Get the WebView tab fragment.
655             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
656
657             // Get the fragment view.
658             View fragmentView = webViewTabFragment.getView();
659
660             // Only pause the WebViews if they exist (they won't when the app is first created).
661             if (fragmentView != null) {
662                 // Get the nested scroll WebView from the tab fragment.
663                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
664
665                 // Pause the nested scroll WebView.
666                 nestedScrollWebView.onPause();
667             }
668         }
669
670         // Pause the WebView JavaScript timers.  This is a global command that pauses JavaScript on all WebViews.
671         if (currentWebView != null) {
672             currentWebView.pauseTimers();
673         }
674
675         // Pause the ad or it will continue to consume resources in the background on the free flavor.
676         if (BuildConfig.FLAVOR.contentEquals("free")) {
677             // Pause the ad.
678             AdHelper.pauseAd(findViewById(R.id.adview));
679         }
680     }
681
682     @Override
683     public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
684         // Run the default commands.
685         super.onSaveInstanceState(savedInstanceState);
686
687         // Create the saved state array lists.
688         ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
689         ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
690
691         // Get the URLs from each tab.
692         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
693             // Get the WebView tab fragment.
694             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
695
696             // Get the fragment view.
697             View fragmentView = webViewTabFragment.getView();
698
699             if (fragmentView != null) {
700                 // Get the nested scroll WebView from the tab fragment.
701                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
702
703                 // Create saved state bundle.
704                 Bundle savedStateBundle = new Bundle();
705
706                 // Get the current states.
707                 nestedScrollWebView.saveState(savedStateBundle);
708                 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
709
710                 // Store the saved states in the array lists.
711                 savedStateArrayList.add(savedStateBundle);
712                 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
713             }
714         }
715
716         // Get the current tab position.
717         int currentTabPosition = tabLayout.getSelectedTabPosition();
718
719         // Store the saved states in the bundle.
720         savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
721         savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
722         savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
723         savedInstanceState.putString(PROXY_MODE, proxyMode);
724     }
725
726     @Override
727     public void onDestroy() {
728         // Unregister the orbot status broadcast receiver if it exists.
729         if (orbotStatusBroadcastReceiver != null) {
730             this.unregisterReceiver(orbotStatusBroadcastReceiver);
731         }
732
733         // Close the bookmarks cursor if it exists.
734         if (bookmarksCursor != null) {
735             bookmarksCursor.close();
736         }
737
738         // Close the bookmarks database if it exists.
739         if (bookmarksDatabaseHelper != null) {
740             bookmarksDatabaseHelper.close();
741         }
742
743         // Stop populating the blocklists if the AsyncTask is running in the background.
744         if (populateBlocklists != null) {
745             populateBlocklists.cancel(true);
746         }
747
748         // Run the default commands.
749         super.onDestroy();
750     }
751
752     @Override
753     public boolean onCreateOptionsMenu(Menu menu) {
754         // Inflate the menu.  This adds items to the action bar if it is present.
755         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
756
757         // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
758         optionsMenu = menu;
759
760         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
761         updatePrivacyIcons(false);
762
763         // Get handles for the menu items.
764         MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
765         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
766         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
767         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
768         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
769         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
770         MenuItem darkWebViewMenuItem = menu.findItem(R.id.dark_webview);
771         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
772
773         // Only display third-party cookies if API >= 21
774         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
775
776         // Only display the form data menu items if the API < 26.
777         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
778         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
779
780         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
781         clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
782
783         // Only display the dark WebView menu item if API >= 21.
784         darkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
785
786         // Only show Ad Consent if this is the free flavor.
787         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
788
789         // Get the shared preferences.
790         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
791
792         // Get the dark theme and app bar preferences.
793         boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
794
795         // 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.
796         if (displayAdditionalAppBarIcons) {
797             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
798             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
799             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
800         } else { //Do not display the additional icons.
801             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
802             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
803             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
804         }
805
806         // Replace Refresh with Stop if a URL is already loading.
807         if (currentWebView != null && currentWebView.getProgress() != 100) {
808             // Set the title.
809             refreshMenuItem.setTitle(R.string.stop);
810
811             // Set the icon if it is displayed in the app bar.
812             if (displayAdditionalAppBarIcons) {
813                 // Get the current theme status.
814                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
815
816                 // Set the icon according to the current theme status.
817                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
818                     refreshMenuItem.setIcon(R.drawable.close_blue_day);
819                 } else {
820                     refreshMenuItem.setIcon(R.drawable.close_blue_night);
821                 }
822             }
823         }
824
825         // Done.
826         return true;
827     }
828
829     @Override
830     public boolean onPrepareOptionsMenu(Menu menu) {
831         // Get handles for the menu items.
832         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
833         MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
834         MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
835         MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
836         MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
837         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
838         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
839         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
840         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
841         MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
842         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
843         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
844         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
845         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
846         MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
847         MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
848         MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
849         MenuItem proxyMenuItem = menu.findItem(R.id.proxy);
850         MenuItem userAgentMenuItem = menu.findItem(R.id.user_agent);
851         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
852         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
853         MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
854         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
855         MenuItem darkWebViewMenuItem = menu.findItem(R.id.dark_webview);
856
857         // Get a handle for the cookie manager.
858         CookieManager cookieManager = CookieManager.getInstance();
859
860         // Initialize the current user agent string and the font size.
861         String currentUserAgent = getString(R.string.user_agent_privacy_browser);
862         int fontSize = 100;
863
864         // Set items that require the current web view to be populated.  It will be null when the program is first opened, as `onPrepareOptionsMenu()` is called before the first WebView is initialized.
865         if (currentWebView != null) {
866             // Set the add or edit domain text.
867             if (currentWebView.getDomainSettingsApplied()) {
868                 addOrEditDomain.setTitle(R.string.edit_domain_settings);
869             } else {
870                 addOrEditDomain.setTitle(R.string.add_domain_settings);
871             }
872
873             // Get the current user agent from the WebView.
874             currentUserAgent = currentWebView.getSettings().getUserAgentString();
875
876             // Get the current font size from the
877             fontSize = currentWebView.getSettings().getTextZoom();
878
879             // Set the status of the menu item checkboxes.
880             domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
881             saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData());  // Form data can be removed once the minimum API >= 26.
882             easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
883             easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
884             fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
885             fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
886             ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
887             ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
888             blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
889             swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
890             wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
891             displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
892
893             // Initialize the display names for the blocklists with the number of blocked requests.
894             blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
895             easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
896             easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
897             fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
898             fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
899             ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
900             ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
901             blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
902
903             // Only modify third-party cookies if the API >= 21.
904             if (Build.VERSION.SDK_INT >= 21) {
905                 // Set the status of the third-party cookies checkbox.
906                 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
907
908                 // Enable third-party cookies if first-party cookies are enabled.
909                 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
910             }
911
912             // Enable DOM Storage if JavaScript is enabled.
913             domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
914
915             // Set the checkbox status for dark WebView if the WebView supports it.
916             if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
917                 darkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
918             }
919         }
920
921         // Set the checked status of the first party cookies menu item.
922         firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
923
924         // Enable Clear Cookies if there are any.
925         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
926
927         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
928         String privateDataDirectoryString = getApplicationInfo().dataDir;
929
930         // Get a count of the number of files in the Local Storage directory.
931         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
932         int localStorageDirectoryNumberOfFiles = 0;
933         if (localStorageDirectory.exists()) {
934             // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
935             localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
936         }
937
938         // Get a count of the number of files in the IndexedDB directory.
939         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
940         int indexedDBDirectoryNumberOfFiles = 0;
941         if (indexedDBDirectory.exists()) {
942             // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
943             indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
944         }
945
946         // Enable Clear DOM Storage if there is any.
947         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
948
949         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
950         if (Build.VERSION.SDK_INT < 26) {
951             // Get the WebView database.
952             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
953
954             // Enable the clear form data menu item if there is anything to clear.
955             clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
956         }
957
958         // Enable Clear Data if any of the submenu items are enabled.
959         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
960
961         // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
962         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
963
964         // Set the proxy title and check the applied proxy.
965         switch (proxyMode) {
966             case ProxyHelper.NONE:
967                 // Set the proxy title.
968                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
969
970                 // Check the proxy None radio button.
971                 menu.findItem(R.id.proxy_none).setChecked(true);
972                 break;
973
974             case ProxyHelper.TOR:
975                 // Set the proxy title.
976                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
977
978                 // Check the proxy Tor radio button.
979                 menu.findItem(R.id.proxy_tor).setChecked(true);
980                 break;
981
982             case ProxyHelper.I2P:
983                 // Set the proxy title.
984                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
985
986                 // Check the proxy I2P radio button.
987                 menu.findItem(R.id.proxy_i2p).setChecked(true);
988                 break;
989
990             case ProxyHelper.CUSTOM:
991                 // Set the proxy title.
992                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
993
994                 // Check the proxy Custom radio button.
995                 menu.findItem(R.id.proxy_custom).setChecked(true);
996                 break;
997         }
998
999         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1000         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1001             // Update the user agent menu item title.
1002             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1003
1004             // Select the Privacy Browser radio box.
1005             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1006         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1007             // Update the user agent menu item title.
1008             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1009
1010             // Select the WebView Default radio box.
1011             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1012         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1013             // Update the user agent menu item title.
1014             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1015
1016             // Select the Firefox on Android radio box.
1017             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1018         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1019             // Update the user agent menu item title.
1020             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1021
1022             // Select the Chrome on Android radio box.
1023             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1024         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1025             // Update the user agent menu item title.
1026             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1027
1028             // Select the Safari on iOS radio box.
1029             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1030         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1031             // Update the user agent menu item title.
1032             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1033
1034             // Select the Firefox on Linux radio box.
1035             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1036         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1037             // Update the user agent menu item title.
1038             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1039
1040             // Select the Chromium on Linux radio box.
1041             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1042         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1043             // Update the user agent menu item title.
1044             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1045
1046             // Select the Firefox on Windows radio box.
1047             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1048         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1049             // Update the user agent menu item title.
1050             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1051
1052             // Select the Chrome on Windows radio box.
1053             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1054         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1055             // Update the user agent menu item title.
1056             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1057
1058             // Select the Edge on Windows radio box.
1059             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1060         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1061             // Update the user agent menu item title.
1062             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1063
1064             // Select the Internet on Windows radio box.
1065             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1066         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1067             // Update the user agent menu item title.
1068             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1069
1070             // Select the Safari on macOS radio box.
1071             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1072         } else {  // Custom user agent.
1073             // Update the user agent menu item title.
1074             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1075
1076             // Select the Custom radio box.
1077             menu.findItem(R.id.user_agent_custom).setChecked(true);
1078         }
1079
1080         // Set the font size title.
1081         fontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1082
1083         // Run all the other default commands.
1084         super.onPrepareOptionsMenu(menu);
1085
1086         // Display the menu.
1087         return true;
1088     }
1089
1090     @Override
1091     public boolean onOptionsItemSelected(MenuItem menuItem) {
1092         // Get a handle for the shared preferences.
1093         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1094
1095         // Get a handle for the cookie manager.
1096         CookieManager cookieManager = CookieManager.getInstance();
1097
1098         // Get the selected menu item ID.
1099         int menuItemId = menuItem.getItemId();
1100
1101         // Run the commands that correlate to the selected menu item.
1102         if (menuItemId == R.id.toggle_javascript) {  // JavaScript.
1103             // Toggle the JavaScript status.
1104             currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1105
1106             // Update the privacy icon.
1107             updatePrivacyIcons(true);
1108
1109             // Display a `Snackbar`.
1110             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
1111                 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1112             } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
1113                 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1114             } else {  // Privacy mode.
1115                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1116             }
1117
1118             // Reload the current WebView.
1119             currentWebView.reload();
1120
1121             // Consume the event.
1122             return true;
1123         } else if (menuItemId == R.id.refresh) {  // Refresh.
1124             // Run the command that correlates to the current status of the menu item.
1125             if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
1126                 // Reload the current WebView.
1127                 currentWebView.reload();
1128             } else {  // The stop button was pushed.
1129                 // Stop the loading of the WebView.
1130                 currentWebView.stopLoading();
1131             }
1132
1133             // Consume the event.
1134             return true;
1135         } else if (menuItemId == R.id.bookmarks) {  // Bookmarks.
1136             // Open the bookmarks drawer.
1137             drawerLayout.openDrawer(GravityCompat.END);
1138
1139             // Consume the event.
1140             return true;
1141         } else if (menuItemId == R.id.toggle_first_party_cookies) {  // First-party cookies.
1142             // Switch the first-party cookie status.
1143             cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1144
1145             // Store the first-party cookie status.
1146             currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1147
1148             // Update the menu checkbox.
1149             menuItem.setChecked(cookieManager.acceptCookie());
1150
1151             // Update the privacy icon.
1152             updatePrivacyIcons(true);
1153
1154             // Display a snackbar.
1155             if (cookieManager.acceptCookie()) {  // First-party cookies are enabled.
1156                 Snackbar.make(webViewPager, R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1157             } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1158                 Snackbar.make(webViewPager, R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1159             } else {  // Privacy mode.
1160                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1161             }
1162
1163             // Reload the current WebView.
1164             currentWebView.reload();
1165
1166             // Consume the event.
1167             return true;
1168         } else if (menuItemId == R.id.toggle_third_party_cookies) {  // Third-party cookies.
1169             // Only act if the API >= 21.  Otherwise, there are no third-party cookie controls.
1170             if (Build.VERSION.SDK_INT >= 21) {
1171                 // Toggle the status of thirdPartyCookiesEnabled.
1172                 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1173
1174                 // Update the menu checkbox.
1175                 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1176
1177                 // Display a snackbar.
1178                 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1179                     Snackbar.make(webViewPager, R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1180                 } else {
1181                     Snackbar.make(webViewPager, R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1182                 }
1183
1184                 // Reload the current WebView.
1185                 currentWebView.reload();
1186             }
1187
1188             // Consume the event.
1189             return true;
1190         } else if (menuItemId == R.id.toggle_dom_storage) {  // DOM storage.
1191             // Toggle the status of domStorageEnabled.
1192             currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1193
1194             // Update the menu checkbox.
1195             menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1196
1197             // Update the privacy icon.
1198             updatePrivacyIcons(true);
1199
1200             // Display a snackbar.
1201             if (currentWebView.getSettings().getDomStorageEnabled()) {
1202                 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1203             } else {
1204                 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1205             }
1206
1207             // Reload the current WebView.
1208             currentWebView.reload();
1209
1210             // Consume the event.
1211             return true;
1212         } else if (menuItemId == R.id.toggle_save_form_data) {  // Form data.  This can be removed once the minimum API >= 26.
1213             // Switch the status of saveFormDataEnabled.
1214             currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1215
1216             // Update the menu checkbox.
1217             menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1218
1219             // Display a snackbar.
1220             if (currentWebView.getSettings().getSaveFormData()) {
1221                 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1222             } else {
1223                 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1224             }
1225
1226             // Update the privacy icon.
1227             updatePrivacyIcons(true);
1228
1229             // Reload the current WebView.
1230             currentWebView.reload();
1231
1232             // Consume the event.
1233             return true;
1234         } else if (menuItemId == R.id.clear_cookies) {  // Clear cookies.
1235             // Create a snackbar.
1236             Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1237                     .setAction(R.string.undo, v -> {
1238                         // Do nothing because everything will be handled by `onDismissed()` below.
1239                     })
1240                     .addCallback(new Snackbar.Callback() {
1241                         @Override
1242                         public void onDismissed(Snackbar snackbar, int event) {
1243                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1244                                 // Delete the cookies, which command varies by SDK.
1245                                 if (Build.VERSION.SDK_INT < 21) {
1246                                     cookieManager.removeAllCookie();
1247                                 } else {
1248                                     cookieManager.removeAllCookies(null);
1249                                 }
1250                             }
1251                         }
1252                     })
1253                     .show();
1254
1255             // Consume the event.
1256             return true;
1257         } else if (menuItemId == R.id.clear_dom_storage) {  // Clear DOM storage.
1258             // Create a snackbar.
1259             Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1260                     .setAction(R.string.undo, v -> {
1261                         // Do nothing because everything will be handled by `onDismissed()` below.
1262                     })
1263                     .addCallback(new Snackbar.Callback() {
1264                         @Override
1265                         public void onDismissed(Snackbar snackbar, int event) {
1266                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1267                                 // Delete the DOM Storage.
1268                                 WebStorage webStorage = WebStorage.getInstance();
1269                                 webStorage.deleteAllData();
1270
1271                                 // Initialize a handler to manually delete the DOM storage files and directories.
1272                                 Handler deleteDomStorageHandler = new Handler();
1273
1274                                 // Setup a runnable to manually delete the DOM storage files and directories.
1275                                 Runnable deleteDomStorageRunnable = () -> {
1276                                     try {
1277                                         // Get a handle for the runtime.
1278                                         Runtime runtime = Runtime.getRuntime();
1279
1280                                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1281                                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1282                                         String privateDataDirectoryString = getApplicationInfo().dataDir;
1283
1284                                         // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1285                                         Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1286
1287                                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1288                                         Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1289                                         Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1290                                         Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1291                                         Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1292
1293                                         // Wait for the processes to finish.
1294                                         deleteLocalStorageProcess.waitFor();
1295                                         deleteIndexProcess.waitFor();
1296                                         deleteQuotaManagerProcess.waitFor();
1297                                         deleteQuotaManagerJournalProcess.waitFor();
1298                                         deleteDatabasesProcess.waitFor();
1299                                     } catch (Exception exception) {
1300                                         // Do nothing if an error is thrown.
1301                                     }
1302                                 };
1303
1304                                 // Manually delete the DOM storage files after 200 milliseconds.
1305                                 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1306                             }
1307                         }
1308                     })
1309                     .show();
1310
1311             // Consume the event.
1312             return true;
1313         } else if (menuItemId == R.id.clear_form_data) {  // Clear form data.  This can be remove once the minimum API >= 26.
1314             // Create a snackbar.
1315             Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1316                     .setAction(R.string.undo, v -> {
1317                         // Do nothing because everything will be handled by `onDismissed()` below.
1318                     })
1319                     .addCallback(new Snackbar.Callback() {
1320                         @Override
1321                         public void onDismissed(Snackbar snackbar, int event) {
1322                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1323                                 // Get a handle for the webView database.
1324                                 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1325
1326                                 // Delete the form data.
1327                                 webViewDatabase.clearFormData();
1328                             }
1329                         }
1330                     })
1331                     .show();
1332
1333             // Consume the event.
1334             return true;
1335         } else if (menuItemId == R.id.easylist) {  // EasyList.
1336             // Toggle the EasyList status.
1337             currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1338
1339             // Update the menu checkbox.
1340             menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1341
1342             // Reload the current WebView.
1343             currentWebView.reload();
1344
1345             // Consume the event.
1346             return true;
1347         } else if (menuItemId == R.id.easyprivacy) {  // EasyPrivacy.
1348             // Toggle the EasyPrivacy status.
1349             currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1350
1351             // Update the menu checkbox.
1352             menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1353
1354             // Reload the current WebView.
1355             currentWebView.reload();
1356
1357             // Consume the event.
1358             return true;
1359         } else if (menuItemId == R.id.fanboys_annoyance_list) {  // Fanboy's Annoyance List.
1360             // Toggle Fanboy's Annoyance List status.
1361             currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1362
1363             // Update the menu checkbox.
1364             menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1365
1366             // Get a handle for the Fanboy's Social Block List menu item.
1367             MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1368
1369             // Update the staus of Fanboy's Social Blocking List.
1370             fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1371
1372             // Reload the current WebView.
1373             currentWebView.reload();
1374
1375             // Consume the event.
1376             return true;
1377         } else if (menuItemId == R.id.fanboys_social_blocking_list) {  // Fanboy's Social Blocking List.
1378             // Toggle Fanboy's Social Blocking List status.
1379             currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1380
1381             // Update the menu checkbox.
1382             menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1383
1384             // Reload the current WebView.
1385             currentWebView.reload();
1386
1387             // Consume the event.
1388             return true;
1389         } else if (menuItemId == R.id.ultralist) {  // UltraList.
1390             // Toggle the UltraList status.
1391             currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1392
1393             // Update the menu checkbox.
1394             menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1395
1396             // Reload the current WebView.
1397             currentWebView.reload();
1398
1399             // Consume the event.
1400             return true;
1401         } else if (menuItemId == R.id.ultraprivacy) {  // UltraPrivacy.
1402             // Toggle the UltraPrivacy status.
1403             currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1404
1405             // Update the menu checkbox.
1406             menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1407
1408             // Reload the current WebView.
1409             currentWebView.reload();
1410
1411             // Consume the event.
1412             return true;
1413         } else if (menuItemId == R.id.block_all_third_party_requests) {  // Block all third-party requests.
1414             //Toggle the third-party requests blocker status.
1415             currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1416
1417             // Update the menu checkbox.
1418             menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1419
1420             // Reload the current WebView.
1421             currentWebView.reload();
1422
1423             // Consume the event.
1424             return true;
1425         } else if (menuItemId == R.id.proxy_none) {  // Proxy - None.
1426             // Update the proxy mode.
1427             proxyMode = ProxyHelper.NONE;
1428
1429             // Apply the proxy mode.
1430             applyProxy(true);
1431
1432             // Consume the event.
1433             return true;
1434         } else if (menuItemId == R.id.proxy_tor) {  // Proxy - Tor.
1435             // Update the proxy mode.
1436             proxyMode = ProxyHelper.TOR;
1437
1438             // Apply the proxy mode.
1439             applyProxy(true);
1440
1441             // Consume the event.
1442             return true;
1443         } else if (menuItemId == R.id.proxy_i2p) {  // Proxy - I2P.
1444             // Update the proxy mode.
1445             proxyMode = ProxyHelper.I2P;
1446
1447             // Apply the proxy mode.
1448             applyProxy(true);
1449
1450             // Consume the event.
1451             return true;
1452         } else if (menuItemId == R.id.proxy_custom) {  // Proxy - Custom.
1453             // Update the proxy mode.
1454             proxyMode = ProxyHelper.CUSTOM;
1455
1456             // Apply the proxy mode.
1457             applyProxy(true);
1458
1459             // Consume the event.
1460             return true;
1461         } else if (menuItemId == R.id.user_agent_privacy_browser) {  // User Agent - Privacy Browser.
1462             // Update the user agent.
1463             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1464
1465             // Reload the current WebView.
1466             currentWebView.reload();
1467
1468             // Consume the event.
1469             return true;
1470         } else if (menuItemId == R.id.user_agent_webview_default) {  // User Agent - WebView Default.
1471             // Update the user agent.
1472             currentWebView.getSettings().setUserAgentString("");
1473
1474             // Reload the current WebView.
1475             currentWebView.reload();
1476
1477             // Consume the event.
1478             return true;
1479         } else if (menuItemId == R.id.user_agent_firefox_on_android) {  // User Agent - Firefox on Android.
1480             // Update the user agent.
1481             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1482
1483             // Reload the current WebView.
1484             currentWebView.reload();
1485
1486             // Consume the event.
1487             return true;
1488         } else if (menuItemId == R.id.user_agent_chrome_on_android) {  // User Agent - Chrome on Android.
1489             // Update the user agent.
1490             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1491
1492             // Reload the current WebView.
1493             currentWebView.reload();
1494
1495             // Consume the event.
1496             return true;
1497         } else if (menuItemId == R.id.user_agent_safari_on_ios) {  // User Agent - Safari on iOS.
1498             // Update the user agent.
1499             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1500
1501             // Reload the current WebView.
1502             currentWebView.reload();
1503
1504             // Consume the event.
1505             return true;
1506         } else if (menuItemId == R.id.user_agent_firefox_on_linux) {  // User Agent - Firefox on Linux.
1507             // Update the user agent.
1508             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1509
1510             // Reload the current WebView.
1511             currentWebView.reload();
1512
1513             // Consume the event.
1514             return true;
1515         } else if (menuItemId == R.id.user_agent_chromium_on_linux) {  // User Agent - Chromium on Linux.
1516             // Update the user agent.
1517             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1518
1519             // Reload the current WebView.
1520             currentWebView.reload();
1521
1522             // Consume the event.
1523             return true;
1524         } else if (menuItemId == R.id.user_agent_firefox_on_windows) {  // User Agent - Firefox on Windows.
1525             // Update the user agent.
1526             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1527
1528             // Reload the current WebView.
1529             currentWebView.reload();
1530
1531             // Consume the event.
1532             return true;
1533         } else if (menuItemId == R.id.user_agent_chrome_on_windows) {  // User Agent - Chrome on Windows.
1534             // Update the user agent.
1535             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1536
1537             // Reload the current WebView.
1538             currentWebView.reload();
1539
1540             // Consume the event.
1541             return true;
1542         } else if (menuItemId == R.id.user_agent_edge_on_windows) {  // User Agent - Edge on Windows.
1543             // Update the user agent.
1544             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1545
1546             // Reload the current WebView.
1547             currentWebView.reload();
1548
1549             // Consume the event.
1550             return true;
1551         } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) {  // User Agent - Internet Explorer on Windows.
1552             // Update the user agent.
1553             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1554
1555             // Reload the current WebView.
1556             currentWebView.reload();
1557
1558             // Consume the event.
1559             return true;
1560         } else if (menuItemId == R.id.user_agent_safari_on_macos) {  // User Agent - Safari on macOS.
1561             // Update the user agent.
1562             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1563
1564             // Reload the current WebView.
1565             currentWebView.reload();
1566
1567             // Consume the event.
1568             return true;
1569         } else if (menuItemId == R.id.user_agent_custom) {  // User Agent - Custom.
1570             // Update the user agent.
1571             currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1572
1573             // Reload the current WebView.
1574             currentWebView.reload();
1575
1576             // Consume the event.
1577             return true;
1578         } else if (menuItemId == R.id.font_size) {  // Font size.
1579             // Instantiate the font size dialog.
1580             DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1581
1582             // Show the font size dialog.
1583             fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1584
1585             // Consume the event.
1586             return true;
1587         } else if (menuItemId == R.id.swipe_to_refresh) {  // Swipe to refresh.
1588             // Toggle the stored status of swipe to refresh.
1589             currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1590
1591             // Get a handle for the swipe refresh layout.
1592             SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1593
1594             // Update the swipe refresh layout.
1595             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1596                 // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
1597                 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1598             } else {  // Swipe to refresh is disabled.
1599                 // Disable the swipe refresh layout.
1600                 swipeRefreshLayout.setEnabled(false);
1601             }
1602
1603             // Consume the event.
1604             return true;
1605         } else if (menuItemId == R.id.wide_viewport) {  // Wide viewport.
1606             // Toggle the viewport.
1607             currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1608
1609             // Consume the event.
1610             return true;
1611         } else if (menuItemId == R.id.display_images) {  // Display images.
1612             // Toggle the displaying of images.
1613             if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1614                 // Disable loading of images.
1615                 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1616
1617                 // Reload the website to remove existing images.
1618                 currentWebView.reload();
1619             } else {  // Images are not currently loaded automatically.
1620                 // Enable loading of images.  Missing images will be loaded without the need for a reload.
1621                 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1622             }
1623
1624             // Consume the event.
1625             return true;
1626         } else if (menuItemId == R.id.dark_webview) {  // Dark WebView.
1627             // Check to see if dark WebView is supported by this WebView.
1628             if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1629                 // Toggle the dark WebView setting.
1630                 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) {  // Dark WebView is currently enabled.
1631                     // Turn off dark WebView.
1632                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1633                 } else {  // Dark WebView is currently disabled.
1634                     // Turn on dark WebView.
1635                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1636                 }
1637             }
1638
1639             // Consume the event.
1640             return true;
1641         } else if (menuItemId == R.id.find_on_page) {  // Find on page.
1642             // Get a handle for the views.
1643             Toolbar toolbar = findViewById(R.id.toolbar);
1644             LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1645             EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1646
1647             // Set the minimum height of the find on page linear layout to match the toolbar.
1648             findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1649
1650             // Hide the toolbar.
1651             toolbar.setVisibility(View.GONE);
1652
1653             // Show the find on page linear layout.
1654             findOnPageLinearLayout.setVisibility(View.VISIBLE);
1655
1656             // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1657             // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1658             findOnPageEditText.postDelayed(() -> {
1659                 // Set the focus on the find on page edit text.
1660                 findOnPageEditText.requestFocus();
1661
1662                 // Get a handle for the input method manager.
1663                 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1664
1665                 // Remove the lint warning below that the input method manager might be null.
1666                 assert inputMethodManager != null;
1667
1668                 // Display the keyboard.  `0` sets no input flags.
1669                 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1670             }, 200);
1671
1672             // Consume the event.
1673             return true;
1674         } else if (menuItemId == R.id.print) {  // Print.
1675             // Get a print manager instance.
1676             PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1677
1678             // Remove the lint error below that print manager might be null.
1679             assert printManager != null;
1680
1681             // Create a print document adapter from the current WebView.
1682             PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1683
1684             // Print the document.
1685             printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1686
1687             // Consume the event.
1688             return true;
1689         } else if (menuItemId == R.id.save_url) {  // Save URL.
1690             // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
1691             new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1692                     currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1693
1694             // Consume the event.
1695             return true;
1696         } else if (menuItemId == R.id.save_archive) {  // Save archive.
1697             // Instantiate the save dialog.
1698             DialogFragment saveArchiveFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_ARCHIVE, null, null, getString(R.string.webpage_mht), null,
1699                     false);
1700
1701             // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
1702             saveArchiveFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1703
1704             // Consume the event.
1705             return true;
1706         } else if (menuItemId == R.id.save_image) {  // Save image.
1707             // Instantiate the save dialog.
1708             DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_IMAGE, null, null, getString(R.string.webpage_png), null,
1709                     false);
1710
1711             // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
1712             saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1713
1714             // Consume the event.
1715             return true;
1716         } else if (menuItemId == R.id.add_to_homescreen) {  // Add to homescreen.
1717             // Instantiate the create home screen shortcut dialog.
1718             DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1719                     currentWebView.getFavoriteOrDefaultIcon());
1720
1721             // Show the create home screen shortcut dialog.
1722             createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1723
1724             // Consume the event.
1725             return true;
1726         } else if (menuItemId == R.id.view_source) {  // View source.
1727             // Create an intent to launch the view source activity.
1728             Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1729
1730             // Add the variables to the intent.
1731             viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1732             viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1733
1734             // Make it so.
1735             startActivity(viewSourceIntent);
1736
1737             // Consume the event.
1738             return true;
1739         } else if (menuItemId == R.id.share_url) {  // Share URL.
1740             // Setup the share string.
1741             String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1742
1743             // Create the share intent.
1744             Intent shareIntent = new Intent(Intent.ACTION_SEND);
1745
1746             // Add the share string to the intent.
1747             shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1748
1749             // Set the MIME type.
1750             shareIntent.setType("text/plain");
1751
1752             // Set the intent to open in a new task.
1753             shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1754
1755             // Make it so.
1756             startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1757
1758             // Consume the event.
1759             return true;
1760         } else if (menuItemId == R.id.open_with_app) {  // Open with app.
1761             // Open the URL with an outside app.
1762             openWithApp(currentWebView.getUrl());
1763
1764             // Consume the event.
1765             return true;
1766         } else if (menuItemId == R.id.open_with_browser) {  // Open with browser.
1767             // Open the URL with an outside browser.
1768             openWithBrowser(currentWebView.getUrl());
1769
1770             // Consume the event.
1771             return true;
1772         } else if (menuItemId == R.id.add_or_edit_domain) {  // Add or edit domain.
1773             // Check if domain settings currently exist.
1774             if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1775                 // Reapply the domain settings on returning to `MainWebViewActivity`.
1776                 reapplyDomainSettingsOnRestart = true;
1777
1778                 // Create an intent to launch the domains activity.
1779                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1780
1781                 // Add the extra information to the intent.
1782                 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1783                 domainsIntent.putExtra("close_on_back", true);
1784                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1785
1786                 // Get the current certificate.
1787                 SslCertificate sslCertificate = currentWebView.getCertificate();
1788
1789                 // Check to see if the SSL certificate is populated.
1790                 if (sslCertificate != null) {
1791                     // Extract the certificate to strings.
1792                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
1793                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
1794                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
1795                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
1796                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
1797                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
1798                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1799                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1800
1801                     // Add the certificate to the intent.
1802                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1803                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1804                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1805                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1806                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1807                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1808                     domainsIntent.putExtra("ssl_start_date", startDateLong);
1809                     domainsIntent.putExtra("ssl_end_date", endDateLong);
1810                 }
1811
1812                 // Check to see if the current IP addresses have been received.
1813                 if (currentWebView.hasCurrentIpAddresses()) {
1814                     // Add the current IP addresses to the intent.
1815                     domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1816                 }
1817
1818                 // Make it so.
1819                 startActivity(domainsIntent);
1820             } else {  // Add a new domain.
1821                 // Apply the new domain settings on returning to `MainWebViewActivity`.
1822                 reapplyDomainSettingsOnRestart = true;
1823
1824                 // Get the current domain
1825                 Uri currentUri = Uri.parse(currentWebView.getUrl());
1826                 String currentDomain = currentUri.getHost();
1827
1828                 // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1829                 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1830
1831                 // Create the domain and store the database ID.
1832                 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1833
1834                 // Create an intent to launch the domains activity.
1835                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1836
1837                 // Add the extra information to the intent.
1838                 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1839                 domainsIntent.putExtra("close_on_back", true);
1840                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1841
1842                 // Get the current certificate.
1843                 SslCertificate sslCertificate = currentWebView.getCertificate();
1844
1845                 // Check to see if the SSL certificate is populated.
1846                 if (sslCertificate != null) {
1847                     // Extract the certificate to strings.
1848                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
1849                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
1850                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
1851                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
1852                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
1853                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
1854                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1855                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1856
1857                     // Add the certificate to the intent.
1858                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1859                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1860                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1861                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1862                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1863                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1864                     domainsIntent.putExtra("ssl_start_date", startDateLong);
1865                     domainsIntent.putExtra("ssl_end_date", endDateLong);
1866                 }
1867
1868                 // Check to see if the current IP addresses have been received.
1869                 if (currentWebView.hasCurrentIpAddresses()) {
1870                     // Add the current IP addresses to the intent.
1871                     domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1872                 }
1873
1874                 // Make it so.
1875                 startActivity(domainsIntent);
1876             }
1877
1878             // Consume the event.
1879             return true;
1880         } else if (menuItemId == R.id.ad_consent) {  // Ad consent.
1881             // Instantiate the ad consent dialog.
1882             DialogFragment adConsentDialogFragment = new AdConsentDialog();
1883
1884             // Display the ad consent dialog.
1885             adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1886
1887             // Consume the event.
1888             return true;
1889         } else {  // There is no match with the options menu.  Pass the event up to the parent method.
1890             // Don't consume the event.
1891             return super.onOptionsItemSelected(menuItem);
1892         }
1893     }
1894
1895     // removeAllCookies is deprecated, but it is required for API < 21.
1896     @Override
1897     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1898         // Get a handle for the shared preferences.
1899         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1900
1901         // Get the menu item ID.
1902         int menuItemId = menuItem.getItemId();
1903
1904         // Run the commands that correspond to the selected menu item.
1905         if (menuItemId == R.id.clear_and_exit) {  // Clear and exit.
1906             // Clear and exit Privacy Browser.
1907             clearAndExit();
1908         } else if (menuItemId == R.id.home) {  // Home.
1909             // Load the homepage.
1910             loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1911         } else if (menuItemId == R.id.back) {  // Back.
1912             // Check if the WebView can go back.
1913             if (currentWebView.canGoBack()) {
1914                 // Get the current web back forward list.
1915                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1916
1917                 // Get the previous entry URL.
1918                 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1919
1920                 // Apply the domain settings.
1921                 applyDomainSettings(currentWebView, previousUrl, false, false, false);
1922
1923                 // Load the previous website in the history.
1924                 currentWebView.goBack();
1925             }
1926         } else if (menuItemId == R.id.forward) {  // Forward.
1927             // Check if the WebView can go forward.
1928             if (currentWebView.canGoForward()) {
1929                 // Get the current web back forward list.
1930                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1931
1932                 // Get the next entry URL.
1933                 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1934
1935                 // Apply the domain settings.
1936                 applyDomainSettings(currentWebView, nextUrl, false, false, false);
1937
1938                 // Load the next website in the history.
1939                 currentWebView.goForward();
1940             }
1941         } else if (menuItemId == R.id.history) {  // History.
1942             // Instantiate the URL history dialog.
1943             DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1944
1945             // Show the URL history dialog.
1946             urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1947         } else if (menuItemId == R.id.open) {  // Open.
1948             // Instantiate the open file dialog.
1949             DialogFragment openDialogFragment = new OpenDialog();
1950
1951             // Show the open file dialog.
1952             openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1953         } else if (menuItemId == R.id.requests) {  // Requests.
1954             // Populate the resource requests.
1955             RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1956
1957             // Create an intent to launch the Requests activity.
1958             Intent requestsIntent = new Intent(this, RequestsActivity.class);
1959
1960             // Add the block third-party requests status to the intent.
1961             requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1962
1963             // Make it so.
1964             startActivity(requestsIntent);
1965         } else if (menuItemId == R.id.downloads) {  // Downloads.
1966             // Launch the system Download Manager.
1967             Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1968
1969             // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1970             downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1971
1972             // Make it so.
1973             startActivity(downloadManagerIntent);
1974         } else if (menuItemId == R.id.domains) {  // Domains.
1975             // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1976             reapplyDomainSettingsOnRestart = true;
1977
1978             // Launch the domains activity.
1979             Intent domainsIntent = new Intent(this, DomainsActivity.class);
1980
1981             // Add the extra information to the intent.
1982             domainsIntent.putExtra("current_url", currentWebView.getUrl());
1983
1984             // Get the current certificate.
1985             SslCertificate sslCertificate = currentWebView.getCertificate();
1986
1987             // Check to see if the SSL certificate is populated.
1988             if (sslCertificate != null) {
1989                 // Extract the certificate to strings.
1990                 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1991                 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1992                 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1993                 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1994                 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1995                 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1996                 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1997                 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1998
1999                 // Add the certificate to the intent.
2000                 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2001                 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2002                 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2003                 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2004                 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2005                 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2006                 domainsIntent.putExtra("ssl_start_date", startDateLong);
2007                 domainsIntent.putExtra("ssl_end_date", endDateLong);
2008             }
2009
2010             // Check to see if the current IP addresses have been received.
2011             if (currentWebView.hasCurrentIpAddresses()) {
2012                 // Add the current IP addresses to the intent.
2013                 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2014             }
2015
2016             // Make it so.
2017             startActivity(domainsIntent);
2018         } else if (menuItemId == R.id.settings) {  // Settings.
2019             // Set the flag to reapply app settings on restart when returning from Settings.
2020             reapplyAppSettingsOnRestart = true;
2021
2022             // Set the flag to reapply the domain settings on restart when returning from Settings.
2023             reapplyDomainSettingsOnRestart = true;
2024
2025             // Launch the settings activity.
2026             Intent settingsIntent = new Intent(this, SettingsActivity.class);
2027             startActivity(settingsIntent);
2028         } else if (menuItemId == R.id.import_export) { // Import/Export.
2029             // Create an intent to launch the import/export activity.
2030             Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2031
2032             // Make it so.
2033             startActivity(importExportIntent);
2034         } else if (menuItemId == R.id.logcat) {  // Logcat.
2035             // Create an intent to launch the logcat activity.
2036             Intent logcatIntent = new Intent(this, LogcatActivity.class);
2037
2038             // Make it so.
2039             startActivity(logcatIntent);
2040         } else if (menuItemId == R.id.guide) {  // Guide.
2041             // Create an intent to launch the guide activity.
2042             Intent guideIntent = new Intent(this, GuideActivity.class);
2043
2044             // Make it so.
2045             startActivity(guideIntent);
2046         } else if (menuItemId == R.id.about) {  // About
2047             // Create an intent to launch the about activity.
2048             Intent aboutIntent = new Intent(this, AboutActivity.class);
2049
2050             // Create a string array for the blocklist versions.
2051             String[] blocklistVersions = new String[]{easyList.get(0).get(0)[0], easyPrivacy.get(0).get(0)[0], fanboysAnnoyanceList.get(0).get(0)[0], fanboysSocialList.get(0).get(0)[0],
2052                     ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2053
2054             // Add the blocklist versions to the intent.
2055             aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2056
2057             // Make it so.
2058             startActivity(aboutIntent);
2059         }
2060
2061         // Close the navigation drawer.
2062         drawerLayout.closeDrawer(GravityCompat.START);
2063         return true;
2064     }
2065
2066     @Override
2067     public void onPostCreate(Bundle savedInstanceState) {
2068         // Run the default commands.
2069         super.onPostCreate(savedInstanceState);
2070
2071         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2072         actionBarDrawerToggle.syncState();
2073     }
2074
2075     @Override
2076     public void onConfigurationChanged(@NonNull Configuration newConfig) {
2077         // Run the default commands.
2078         super.onConfigurationChanged(newConfig);
2079
2080         // Reload the ad for the free flavor if not in full screen mode.
2081         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2082             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2083             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2084         }
2085
2086         // `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:
2087         // https://code.google.com/p/android/issues/detail?id=20493#c8
2088         // ActivityCompat.invalidateOptionsMenu(this);
2089     }
2090
2091     @Override
2092     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2093         // Get the hit test result.
2094         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2095
2096         // Define the URL strings.
2097         final String imageUrl;
2098         final String linkUrl;
2099
2100         // Get handles for the system managers.
2101         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2102
2103         // Remove the lint errors below that the clipboard manager might be null.
2104         assert clipboardManager != null;
2105
2106         // Process the link according to the type.
2107         switch (hitTestResult.getType()) {
2108             // `SRC_ANCHOR_TYPE` is a link.
2109             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2110                 // Get the target URL.
2111                 linkUrl = hitTestResult.getExtra();
2112
2113                 // Set the target URL as the title of the `ContextMenu`.
2114                 menu.setHeaderTitle(linkUrl);
2115
2116                 // Add an Open in New Tab entry.
2117                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2118                     // Load the link URL in a new tab and move to it.
2119                     addNewTab(linkUrl, true);
2120
2121                     // Consume the event.
2122                     return true;
2123                 });
2124
2125                 // Add an Open in Background entry.
2126                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2127                     // Load the link URL in a new tab but do not move to it.
2128                     addNewTab(linkUrl, false);
2129
2130                     // Consume the event.
2131                     return true;
2132                 });
2133
2134                 // Add an Open with App entry.
2135                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2136                     openWithApp(linkUrl);
2137
2138                     // Consume the event.
2139                     return true;
2140                 });
2141
2142                 // Add an Open with Browser entry.
2143                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2144                     openWithBrowser(linkUrl);
2145
2146                     // Consume the event.
2147                     return true;
2148                 });
2149
2150                 // Add a Copy URL entry.
2151                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2152                     // Save the link URL in a `ClipData`.
2153                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2154
2155                     // Set the `ClipData` as the clipboard's primary clip.
2156                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2157
2158                     // Consume the event.
2159                     return true;
2160                 });
2161
2162                 // Add a Save URL entry.
2163                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2164                     // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2165                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2166                             currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2167
2168                     // Consume the event.
2169                     return true;
2170                 });
2171
2172                 // Add an empty Cancel entry, which by default closes the context menu.
2173                 menu.add(R.string.cancel);
2174                 break;
2175
2176             // `IMAGE_TYPE` is an image.
2177             case WebView.HitTestResult.IMAGE_TYPE:
2178                 // Get the image URL.
2179                 imageUrl = hitTestResult.getExtra();
2180
2181                 // Remove the incorrect lint warning below that the image URL might be null.
2182                 assert imageUrl != null;
2183
2184                 // Set the context menu title.
2185                 if (imageUrl.startsWith("data:")) {  // The image data is contained in within the URL, making it exceedingly long.
2186                     // Truncate the image URL before making it the title.
2187                     menu.setHeaderTitle(imageUrl.substring(0, 100));
2188                 } else {  // The image URL does not contain the full image data.
2189                     // Set the image URL as the title of the context menu.
2190                     menu.setHeaderTitle(imageUrl);
2191                 }
2192
2193                 // Add an Open in New Tab entry.
2194                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2195                     // Load the image in a new tab.
2196                     addNewTab(imageUrl, true);
2197
2198                     // Consume the event.
2199                     return true;
2200                 });
2201
2202                 // Add an Open with App entry.
2203                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2204                     // Open the image URL with an external app.
2205                     openWithApp(imageUrl);
2206
2207                     // Consume the event.
2208                     return true;
2209                 });
2210
2211                 // Add an Open with Browser entry.
2212                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2213                     // Open the image URL with an external browser.
2214                     openWithBrowser(imageUrl);
2215
2216                     // Consume the event.
2217                     return true;
2218                 });
2219
2220                 // Add a View Image entry.
2221                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2222                     // Load the image in the current tab.
2223                     loadUrl(currentWebView, imageUrl);
2224
2225                     // Consume the event.
2226                     return true;
2227                 });
2228
2229                 // Add a Save Image entry.
2230                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2231                    // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2232                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2233                             currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2234
2235                     // Consume the event.
2236                     return true;
2237                 });
2238
2239                 // Add a Copy URL entry.
2240                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2241                     // Save the image URL in a clip data.
2242                     ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2243
2244                     // Set the clip data as the clipboard's primary clip.
2245                     clipboardManager.setPrimaryClip(imageTypeClipData);
2246
2247                     // Consume the event.
2248                     return true;
2249                 });
2250
2251                 // Add an empty Cancel entry, which by default closes the context menu.
2252                 menu.add(R.string.cancel);
2253                 break;
2254
2255             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2256             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2257                 // Get the image URL.
2258                 imageUrl = hitTestResult.getExtra();
2259
2260                 // Instantiate a handler.
2261                 Handler handler = new Handler();
2262
2263                 // Get a message from the handler.
2264                 Message message = handler.obtainMessage();
2265
2266                 // Request the image details from the last touched node be returned in the message.
2267                 currentWebView.requestFocusNodeHref(message);
2268
2269                 // Get the link URL from the message data.
2270                 linkUrl = message.getData().getString("url");
2271
2272                 // Set the link URL as the title of the context menu.
2273                 menu.setHeaderTitle(linkUrl);
2274
2275                 // Add an Open in New Tab entry.
2276                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2277                     // Load the link URL in a new tab and move to it.
2278                     addNewTab(linkUrl, true);
2279
2280                     // Consume the event.
2281                     return true;
2282                 });
2283
2284                 // Add an Open in Background entry.
2285                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2286                     // Lod the link URL in a new tab but do not move to it.
2287                     addNewTab(linkUrl, false);
2288
2289                     // Consume the event.
2290                     return true;
2291                 });
2292
2293                 // Add an Open Image in New Tab entry.
2294                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2295                     // Load the image in a new tab and move to it.
2296                     addNewTab(imageUrl, true);
2297
2298                     // Consume the event.
2299                     return true;
2300                 });
2301
2302                 // Add an Open with App entry.
2303                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2304                     // Open the link URL with an external app.
2305                     openWithApp(linkUrl);
2306
2307                     // Consume the event.
2308                     return true;
2309                 });
2310
2311                 // Add an Open with Browser entry.
2312                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2313                     // Open the link URL with an external browser.
2314                     openWithBrowser(linkUrl);
2315
2316                     // Consume the event.
2317                     return true;
2318                 });
2319
2320                 // Add a View Image entry.
2321                 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2322                    // View the image in the current tab.
2323                    loadUrl(currentWebView, imageUrl);
2324
2325                    // Consume the event.
2326                    return true;
2327                 });
2328
2329                 // Add a Save Image entry.
2330                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2331                     // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2332                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2333                             currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2334
2335                     // Consume the event.
2336                     return true;
2337                 });
2338
2339                 // Add a Copy URL entry.
2340                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2341                     // Save the link URL in a clip data.
2342                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2343
2344                     // Set the clip data as the clipboard's primary clip.
2345                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2346
2347                     // Consume the event.
2348                     return true;
2349                 });
2350
2351                 // Add a Save URL entry.
2352                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2353                     // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2354                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2355                             currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2356
2357                     // Consume the event.
2358                     return true;
2359                 });
2360
2361                 // Add an empty Cancel entry, which by default closes the context menu.
2362                 menu.add(R.string.cancel);
2363                 break;
2364
2365             case WebView.HitTestResult.EMAIL_TYPE:
2366                 // Get the target URL.
2367                 linkUrl = hitTestResult.getExtra();
2368
2369                 // Set the target URL as the title of the `ContextMenu`.
2370                 menu.setHeaderTitle(linkUrl);
2371
2372                 // Add a Write Email entry.
2373                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2374                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2375                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2376
2377                     // Parse the url and set it as the data for the `Intent`.
2378                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2379
2380                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2381                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2382
2383                     try {
2384                         // Make it so.
2385                         startActivity(emailIntent);
2386                     } catch (ActivityNotFoundException exception) {
2387                         // Display a snackbar.
2388                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
2389                     }
2390
2391                     // Consume the event.
2392                     return true;
2393                 });
2394
2395                 // Add a Copy Email Address entry.
2396                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2397                     // Save the email address in a `ClipData`.
2398                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2399
2400                     // Set the `ClipData` as the clipboard's primary clip.
2401                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2402
2403                     // Consume the event.
2404                     return true;
2405                 });
2406
2407                 // Add an empty Cancel entry, which by default closes the context menu.
2408                 menu.add(R.string.cancel);
2409                 break;
2410         }
2411     }
2412
2413     @Override
2414     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2415         // Get a handle for the bookmarks list view.
2416         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2417
2418         // Get the dialog.
2419         Dialog dialog = dialogFragment.getDialog();
2420
2421         // Remove the incorrect lint warning below that the dialog might be null.
2422         assert dialog != null;
2423
2424         // Get the views from the dialog fragment.
2425         EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2426         EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2427
2428         // Extract the strings from the edit texts.
2429         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2430         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2431
2432         // Create a favorite icon byte array output stream.
2433         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2434
2435         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2436         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2437
2438         // Convert the favorite icon byte array stream to a byte array.
2439         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2440
2441         // Display the new bookmark below the current items in the (0 indexed) list.
2442         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2443
2444         // Create the bookmark.
2445         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2446
2447         // Update the bookmarks cursor with the current contents of this folder.
2448         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2449
2450         // Update the list view.
2451         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2452
2453         // Scroll to the new bookmark.
2454         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2455     }
2456
2457     @Override
2458     public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2459         // Get a handle for the bookmarks list view.
2460         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2461
2462         // Get the dialog.
2463         Dialog dialog = dialogFragment.getDialog();
2464
2465         // Remove the incorrect lint warning below that the dialog might be null.
2466         assert dialog != null;
2467
2468         // Get handles for the views in the dialog fragment.
2469         EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2470         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2471         ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2472
2473         // Get new folder name string.
2474         String folderNameString = createFolderNameEditText.getText().toString();
2475
2476         // Create a folder icon bitmap.
2477         Bitmap folderIconBitmap;
2478
2479         // Set the folder icon bitmap according to the dialog.
2480         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2481             // Get the default folder icon drawable.
2482             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2483
2484             // Convert the folder icon drawable to a bitmap drawable.
2485             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2486
2487             // Convert the folder icon bitmap drawable to a bitmap.
2488             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2489         } else {  // Use the WebView favorite icon.
2490             // Copy the favorite icon bitmap to the folder icon bitmap.
2491             folderIconBitmap = favoriteIconBitmap;
2492         }
2493
2494         // Create a folder icon byte array output stream.
2495         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2496
2497         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2498         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2499
2500         // Convert the folder icon byte array stream to a byte array.
2501         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2502
2503         // Move all the bookmarks down one in the display order.
2504         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2505             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2506             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2507         }
2508
2509         // Create the folder, which will be placed at the top of the `ListView`.
2510         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2511
2512         // Update the bookmarks cursor with the current contents of this folder.
2513         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2514
2515         // Update the `ListView`.
2516         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2517
2518         // Scroll to the new folder.
2519         bookmarksListView.setSelection(0);
2520     }
2521
2522     @Override
2523     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2524         // Remove the incorrect lint warning below that the dialog fragment might be null.
2525         assert dialogFragment != null;
2526
2527         // Get the dialog.
2528         Dialog dialog = dialogFragment.getDialog();
2529
2530         // Remove the incorrect lint warning below that the dialog might be null.
2531         assert dialog != null;
2532
2533         // Get handles for the views from the dialog.
2534         EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2535         RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2536         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2537         ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2538
2539         // Get the new folder name.
2540         String newFolderNameString = editFolderNameEditText.getText().toString();
2541
2542         // Check if the favorite icon has changed.
2543         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
2544             // Update the name in the database.
2545             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2546         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
2547             // Create the new folder icon Bitmap.
2548             Bitmap folderIconBitmap;
2549
2550             // Populate the new folder icon bitmap.
2551             if (defaultFolderIconRadioButton.isChecked()) {
2552                 // Get the default folder icon drawable.
2553                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2554
2555                 // Convert the folder icon drawable to a bitmap drawable.
2556                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2557
2558                 // Convert the folder icon bitmap drawable to a bitmap.
2559                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2560             } else {  // Use the `WebView` favorite icon.
2561                 // Copy the favorite icon bitmap to the folder icon bitmap.
2562                 folderIconBitmap = favoriteIconBitmap;
2563             }
2564
2565             // Create a folder icon byte array output stream.
2566             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2567
2568             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2569             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2570
2571             // Convert the folder icon byte array stream to a byte array.
2572             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2573
2574             // Update the folder icon in the database.
2575             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2576         } else {  // The folder icon and the name have changed.
2577             // Get the new folder icon `Bitmap`.
2578             Bitmap folderIconBitmap;
2579             if (defaultFolderIconRadioButton.isChecked()) {
2580                 // Get the default folder icon drawable.
2581                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2582
2583                 // Convert the folder icon drawable to a bitmap drawable.
2584                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2585
2586                 // Convert the folder icon bitmap drawable to a bitmap.
2587                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2588             } else {  // Use the `WebView` favorite icon.
2589                 // Copy the favorite icon bitmap to the folder icon bitmap.
2590                 folderIconBitmap = favoriteIconBitmap;
2591             }
2592
2593             // Create a folder icon byte array output stream.
2594             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2595
2596             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2597             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2598
2599             // Convert the folder icon byte array stream to a byte array.
2600             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2601
2602             // Update the folder name and icon in the database.
2603             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2604         }
2605
2606         // Update the bookmarks cursor with the current contents of this folder.
2607         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2608
2609         // Update the `ListView`.
2610         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2611     }
2612
2613     // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2614     @Override
2615     public void onBackPressed() {
2616         // Check the different options for processing `back`.
2617         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
2618             // Close the navigation drawer.
2619             drawerLayout.closeDrawer(GravityCompat.START);
2620         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
2621             // close the bookmarks drawer.
2622             drawerLayout.closeDrawer(GravityCompat.END);
2623         } else if (displayingFullScreenVideo) {  // A full screen video is shown.
2624             // Get a handle for the layouts.
2625             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2626             RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2627             FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2628
2629             // Re-enable the screen timeout.
2630             fullScreenVideoFrameLayout.setKeepScreenOn(false);
2631
2632             // Unset the full screen video flag.
2633             displayingFullScreenVideo = false;
2634
2635             // Remove all the views from the full screen video frame layout.
2636             fullScreenVideoFrameLayout.removeAllViews();
2637
2638             // Hide the full screen video frame layout.
2639             fullScreenVideoFrameLayout.setVisibility(View.GONE);
2640
2641             // Enable the sliding drawers.
2642             drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2643
2644             // Show the main content relative layout.
2645             mainContentRelativeLayout.setVisibility(View.VISIBLE);
2646
2647             // Apply the appropriate full screen mode flags.
2648             if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
2649                 // Hide the banner ad in the free flavor.
2650                 if (BuildConfig.FLAVOR.contentEquals("free")) {
2651                     AdHelper.hideAd(findViewById(R.id.adview));
2652                 }
2653
2654                 /* Hide the system bars.
2655                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2656                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2657                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2658                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2659                  */
2660                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2661                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2662
2663                 // Reload the website if the app bar is hidden.  Otherwise, there is some bug in Android that causes the WebView to be entirely black.
2664                 if (hideAppBar) {
2665                     // Reload the WebView.
2666                     currentWebView.reload();
2667                 }
2668             } else {  // Switch to normal viewing mode.
2669                 // Remove the `SYSTEM_UI` flags from the root frame layout.
2670                 rootFrameLayout.setSystemUiVisibility(0);
2671             }
2672
2673             // Reload the ad for the free flavor if not in full screen mode.
2674             if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2675                 // Reload the ad.
2676                 AdHelper.loadAd(findViewById(R.id.ad