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