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