Fix incorrect pinned mismatch errors. https://redmine.stoutner.com/issues/591
[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     // Remove Android Studio's warning about the dangers of enabling JavaScript.  We know.  Oh, how we know.
1063     @SuppressLint("SetJavaScriptEnabled")
1064     public boolean onOptionsItemSelected(MenuItem menuItem) {
1065         // Get the selected menu item ID.
1066         int menuItemId = menuItem.getItemId();
1067
1068         // Get a handle for the shared preferences.
1069         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1070
1071         // Get a handle for the cookie manager.
1072         CookieManager cookieManager = CookieManager.getInstance();
1073
1074         // Run the commands that correlate to the selected menu item.
1075         switch (menuItemId) {
1076             case R.id.toggle_javascript:
1077                 // Toggle the JavaScript status.
1078                 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1079
1080                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1081                 updatePrivacyIcons(true);
1082
1083                 // Display a `Snackbar`.
1084                 if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
1085                     Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1086                 } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
1087                     Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1088                 } else {  // Privacy mode.
1089                     Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1090                 }
1091
1092                 // Reload the current WebView.
1093                 currentWebView.reload();
1094
1095                 // Consume the event.
1096                 return true;
1097
1098             case R.id.refresh:
1099                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
1100                     // Reload the current WebView.
1101                     currentWebView.reload();
1102                 } else {  // The stop button was pushed.
1103                     // Stop the loading of the WebView.
1104                     currentWebView.stopLoading();
1105                 }
1106
1107                 // Consume the event.
1108                 return true;
1109
1110             case R.id.bookmarks:
1111                 // Open the bookmarks drawer.
1112                 drawerLayout.openDrawer(GravityCompat.END);
1113
1114                 // Consume the event.
1115                 return true;
1116
1117             case R.id.toggle_first_party_cookies:
1118                 // Switch the first-party cookie status.
1119                 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1120
1121                 // Store the first-party cookie status.
1122                 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1123
1124                 // Update the menu checkbox.
1125                 menuItem.setChecked(cookieManager.acceptCookie());
1126
1127                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1128                 updatePrivacyIcons(true);
1129
1130                 // Display a snackbar.
1131                 if (cookieManager.acceptCookie()) {  // First-party cookies are enabled.
1132                     Snackbar.make(webViewPager, R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1133                 } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1134                     Snackbar.make(webViewPager, R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1135                 } else {  // Privacy mode.
1136                     Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1137                 }
1138
1139                 // Reload the current WebView.
1140                 currentWebView.reload();
1141
1142                 // Consume the event.
1143                 return true;
1144
1145             case R.id.toggle_third_party_cookies:
1146                 if (Build.VERSION.SDK_INT >= 21) {
1147                     // Switch the status of thirdPartyCookiesEnabled.
1148                     cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1149
1150                     // Update the menu checkbox.
1151                     menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1152
1153                     // Display a snackbar.
1154                     if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1155                         Snackbar.make(webViewPager, R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1156                     } else {
1157                         Snackbar.make(webViewPager, R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1158                     }
1159
1160                     // Reload the current WebView.
1161                     currentWebView.reload();
1162                 } // Else do nothing because SDK < 21.
1163
1164                 // Consume the event.
1165                 return true;
1166
1167             case R.id.toggle_dom_storage:
1168                 // Toggle the status of domStorageEnabled.
1169                 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1170
1171                 // Update the menu checkbox.
1172                 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1173
1174                 // Update the privacy icon.  `true` refreshes the app bar icons.
1175                 updatePrivacyIcons(true);
1176
1177                 // Display a snackbar.
1178                 if (currentWebView.getSettings().getDomStorageEnabled()) {
1179                     Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1180                 } else {
1181                     Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1182                 }
1183
1184                 // Reload the current WebView.
1185                 currentWebView.reload();
1186
1187                 // Consume the event.
1188                 return true;
1189
1190             // Form data can be removed once the minimum API >= 26.
1191             case R.id.toggle_save_form_data:
1192                 // Switch the status of saveFormDataEnabled.
1193                 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1194
1195                 // Update the menu checkbox.
1196                 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1197
1198                 // Display a snackbar.
1199                 if (currentWebView.getSettings().getSaveFormData()) {
1200                     Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1201                 } else {
1202                     Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1203                 }
1204
1205                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1206                 updatePrivacyIcons(true);
1207
1208                 // Reload the current WebView.
1209                 currentWebView.reload();
1210
1211                 // Consume the event.
1212                 return true;
1213
1214             case R.id.clear_cookies:
1215                 Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1216                         .setAction(R.string.undo, v -> {
1217                             // Do nothing because everything will be handled by `onDismissed()` below.
1218                         })
1219                         .addCallback(new Snackbar.Callback() {
1220                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1221                             @Override
1222                             public void onDismissed(Snackbar snackbar, int event) {
1223                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1224                                     // Delete the cookies, which command varies by SDK.
1225                                     if (Build.VERSION.SDK_INT < 21) {
1226                                         cookieManager.removeAllCookie();
1227                                     } else {
1228                                         cookieManager.removeAllCookies(null);
1229                                     }
1230                                 }
1231                             }
1232                         })
1233                         .show();
1234
1235                 // Consume the event.
1236                 return true;
1237
1238             case R.id.clear_dom_storage:
1239                 Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1240                         .setAction(R.string.undo, v -> {
1241                             // Do nothing because everything will be handled by `onDismissed()` below.
1242                         })
1243                         .addCallback(new Snackbar.Callback() {
1244                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1245                             @Override
1246                             public void onDismissed(Snackbar snackbar, int event) {
1247                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1248                                     // Delete the DOM Storage.
1249                                     WebStorage webStorage = WebStorage.getInstance();
1250                                     webStorage.deleteAllData();
1251
1252                                     // Initialize a handler to manually delete the DOM storage files and directories.
1253                                     Handler deleteDomStorageHandler = new Handler();
1254
1255                                     // Setup a runnable to manually delete the DOM storage files and directories.
1256                                     Runnable deleteDomStorageRunnable = () -> {
1257                                         try {
1258                                             // Get a handle for the runtime.
1259                                             Runtime runtime = Runtime.getRuntime();
1260
1261                                             // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1262                                             // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1263                                             String privateDataDirectoryString = getApplicationInfo().dataDir;
1264
1265                                             // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1266                                             Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1267
1268                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1269                                             Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1270                                             Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1271                                             Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1272                                             Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1273
1274                                             // Wait for the processes to finish.
1275                                             deleteLocalStorageProcess.waitFor();
1276                                             deleteIndexProcess.waitFor();
1277                                             deleteQuotaManagerProcess.waitFor();
1278                                             deleteQuotaManagerJournalProcess.waitFor();
1279                                             deleteDatabasesProcess.waitFor();
1280                                         } catch (Exception exception) {
1281                                             // Do nothing if an error is thrown.
1282                                         }
1283                                     };
1284
1285                                     // Manually delete the DOM storage files after 200 milliseconds.
1286                                     deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1287                                 }
1288                             }
1289                         })
1290                         .show();
1291
1292                 // Consume the event.
1293                 return true;
1294
1295             // Form data can be remove once the minimum API >= 26.
1296             case R.id.clear_form_data:
1297                 Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1298                         .setAction(R.string.undo, v -> {
1299                             // Do nothing because everything will be handled by `onDismissed()` below.
1300                         })
1301                         .addCallback(new Snackbar.Callback() {
1302                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1303                             @Override
1304                             public void onDismissed(Snackbar snackbar, int event) {
1305                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1306                                     // Delete the form data.
1307                                     WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1308                                     mainWebViewDatabase.clearFormData();
1309                                 }
1310                             }
1311                         })
1312                         .show();
1313
1314                 // Consume the event.
1315                 return true;
1316
1317             case R.id.easylist:
1318                 // Toggle the EasyList status.
1319                 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1320
1321                 // Update the menu checkbox.
1322                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1323
1324                 // Reload the current WebView.
1325                 currentWebView.reload();
1326
1327                 // Consume the event.
1328                 return true;
1329
1330             case R.id.easyprivacy:
1331                 // Toggle the EasyPrivacy status.
1332                 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1333
1334                 // Update the menu checkbox.
1335                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1336
1337                 // Reload the current WebView.
1338                 currentWebView.reload();
1339
1340                 // Consume the event.
1341                 return true;
1342
1343             case R.id.fanboys_annoyance_list:
1344                 // Toggle Fanboy's Annoyance List status.
1345                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1346
1347                 // Update the menu checkbox.
1348                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1349
1350                 // Update the staus of Fanboy's Social Blocking List.
1351                 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1352                 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1353
1354                 // Reload the current WebView.
1355                 currentWebView.reload();
1356
1357                 // Consume the event.
1358                 return true;
1359
1360             case R.id.fanboys_social_blocking_list:
1361                 // Toggle Fanboy's Social Blocking List status.
1362                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1363
1364                 // Update the menu checkbox.
1365                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1366
1367                 // Reload the current WebView.
1368                 currentWebView.reload();
1369
1370                 // Consume the event.
1371                 return true;
1372
1373             case R.id.ultralist:
1374                 // Toggle the UltraList status.
1375                 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1376
1377                 // Update the menu checkbox.
1378                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1379
1380                 // Reload the current WebView.
1381                 currentWebView.reload();
1382
1383                 // Consume the event.
1384                 return true;
1385
1386             case R.id.ultraprivacy:
1387                 // Toggle the UltraPrivacy status.
1388                 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1389
1390                 // Update the menu checkbox.
1391                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1392
1393                 // Reload the current WebView.
1394                 currentWebView.reload();
1395
1396                 // Consume the event.
1397                 return true;
1398
1399             case R.id.block_all_third_party_requests:
1400                 //Toggle the third-party requests blocker status.
1401                 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1402
1403                 // Update the menu checkbox.
1404                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1405
1406                 // Reload the current WebView.
1407                 currentWebView.reload();
1408
1409                 // Consume the event.
1410                 return true;
1411
1412             case R.id.proxy_none:
1413                 // Update the proxy mode.
1414                 proxyMode = ProxyHelper.NONE;
1415
1416                 // Apply the proxy mode.
1417                 applyProxy(true);
1418
1419                 // Consume the event.
1420                 return true;
1421
1422             case R.id.proxy_tor:
1423                 // Update the proxy mode.
1424                 proxyMode = ProxyHelper.TOR;
1425
1426                 // Apply the proxy mode.
1427                 applyProxy(true);
1428
1429                 // Consume the event.
1430                 return true;
1431
1432             case R.id.proxy_i2p:
1433                 // Update the proxy mode.
1434                 proxyMode = ProxyHelper.I2P;
1435
1436                 // Apply the proxy mode.
1437                 applyProxy(true);
1438
1439                 // Consume the event.
1440                 return true;
1441
1442             case R.id.proxy_custom:
1443                 // Update the proxy mode.
1444                 proxyMode = ProxyHelper.CUSTOM;
1445
1446                 // Apply the proxy mode.
1447                 applyProxy(true);
1448
1449                 // Consume the event.
1450                 return true;
1451
1452             case R.id.user_agent_privacy_browser:
1453                 // Update the user agent.
1454                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1455
1456                 // Reload the current WebView.
1457                 currentWebView.reload();
1458
1459                 // Consume the event.
1460                 return true;
1461
1462             case R.id.user_agent_webview_default:
1463                 // Update the user agent.
1464                 currentWebView.getSettings().setUserAgentString("");
1465
1466                 // Reload the current WebView.
1467                 currentWebView.reload();
1468
1469                 // Consume the event.
1470                 return true;
1471
1472             case R.id.user_agent_firefox_on_android:
1473                 // Update the user agent.
1474                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1475
1476                 // Reload the current WebView.
1477                 currentWebView.reload();
1478
1479                 // Consume the event.
1480                 return true;
1481
1482             case R.id.user_agent_chrome_on_android:
1483                 // Update the user agent.
1484                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1485
1486                 // Reload the current WebView.
1487                 currentWebView.reload();
1488
1489                 // Consume the event.
1490                 return true;
1491
1492             case R.id.user_agent_safari_on_ios:
1493                 // Update the user agent.
1494                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1495
1496                 // Reload the current WebView.
1497                 currentWebView.reload();
1498
1499                 // Consume the event.
1500                 return true;
1501
1502             case R.id.user_agent_firefox_on_linux:
1503                 // Update the user agent.
1504                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1505
1506                 // Reload the current WebView.
1507                 currentWebView.reload();
1508
1509                 // Consume the event.
1510                 return true;
1511
1512             case R.id.user_agent_chromium_on_linux:
1513                 // Update the user agent.
1514                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1515
1516                 // Reload the current WebView.
1517                 currentWebView.reload();
1518
1519                 // Consume the event.
1520                 return true;
1521
1522             case R.id.user_agent_firefox_on_windows:
1523                 // Update the user agent.
1524                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1525
1526                 // Reload the current WebView.
1527                 currentWebView.reload();
1528
1529                 // Consume the event.
1530                 return true;
1531
1532             case R.id.user_agent_chrome_on_windows:
1533                 // Update the user agent.
1534                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1535
1536                 // Reload the current WebView.
1537                 currentWebView.reload();
1538
1539                 // Consume the event.
1540                 return true;
1541
1542             case R.id.user_agent_edge_on_windows:
1543                 // Update the user agent.
1544                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1545
1546                 // Reload the current WebView.
1547                 currentWebView.reload();
1548
1549                 // Consume the event.
1550                 return true;
1551
1552             case R.id.user_agent_internet_explorer_on_windows:
1553                 // Update the user agent.
1554                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1555
1556                 // Reload the current WebView.
1557                 currentWebView.reload();
1558
1559                 // Consume the event.
1560                 return true;
1561
1562             case R.id.user_agent_safari_on_macos:
1563                 // Update the user agent.
1564                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1565
1566                 // Reload the current WebView.
1567                 currentWebView.reload();
1568
1569                 // Consume the event.
1570                 return true;
1571
1572             case R.id.user_agent_custom:
1573                 // Update the user agent.
1574                 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1575
1576                 // Reload the current WebView.
1577                 currentWebView.reload();
1578
1579                 // Consume the event.
1580                 return true;
1581
1582             case R.id.font_size:
1583                 // Instantiate the font size dialog.
1584                 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1585
1586                 // Show the font size dialog.
1587                 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1588
1589                 // Consume the event.
1590                 return true;
1591
1592             case R.id.swipe_to_refresh:
1593                 // Toggle the stored status of swipe to refresh.
1594                 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1595
1596                 // Get a handle for the swipe refresh layout.
1597                 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1598
1599                 // Update the swipe refresh layout.
1600                 if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1601                     // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
1602                     swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1603                 } else {  // Swipe to refresh is disabled.
1604                     // Disable the swipe refresh layout.
1605                     swipeRefreshLayout.setEnabled(false);
1606                 }
1607
1608                 // Consume the event.
1609                 return true;
1610
1611             case R.id.wide_viewport:
1612                 // Toggle the viewport.
1613                 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1614
1615                 // Consume the event.
1616                 return true;
1617
1618             case R.id.display_images:
1619                 if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1620                     // Disable loading of images.
1621                     currentWebView.getSettings().setLoadsImagesAutomatically(false);
1622
1623                     // Reload the website to remove existing images.
1624                     currentWebView.reload();
1625                 } else {  // Images are not currently loaded automatically.
1626                     // Enable loading of images.  Missing images will be loaded without the need for a reload.
1627                     currentWebView.getSettings().setLoadsImagesAutomatically(true);
1628                 }
1629
1630                 // Consume the event.
1631                 return true;
1632
1633             case R.id.dark_webview:
1634                 // Check to see if dark WebView is supported by this WebView.
1635                 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1636                     // Toggle the dark WebView setting.
1637                     if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) {  // Dark WebView is currently enabled.
1638                         // Turn off dark WebView.
1639                         WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1640                     } else {  // Dark WebView is currently disabled.
1641                         // turn on dark WebView.
1642                         WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1643                     }
1644                 }
1645
1646                 // Consume the event.
1647                 return true;
1648
1649             case R.id.find_on_page:
1650                 // Get a handle for the views.
1651                 Toolbar toolbar = findViewById(R.id.toolbar);
1652                 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1653                 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1654
1655                 // Set the minimum height of the find on page linear layout to match the toolbar.
1656                 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1657
1658                 // Hide the toolbar.
1659                 toolbar.setVisibility(View.GONE);
1660
1661                 // Show the find on page linear layout.
1662                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1663
1664                 // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1665                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1666                 findOnPageEditText.postDelayed(() -> {
1667                     // Set the focus on `findOnPageEditText`.
1668                     findOnPageEditText.requestFocus();
1669
1670                     // Get a handle for the input method manager.
1671                     InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1672
1673                     // Remove the lint warning below that the input method manager might be null.
1674                     assert inputMethodManager != null;
1675
1676                     // Display the keyboard.  `0` sets no input flags.
1677                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
1678                 }, 200);
1679
1680                 // Consume the event.
1681                 return true;
1682
1683             case R.id.print:
1684                 // Get a print manager instance.
1685                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1686
1687                 // Remove the lint error below that print manager might be null.
1688                 assert printManager != null;
1689
1690                 // Create a print document adapter from the current WebView.
1691                 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1692
1693                 // Print the document.
1694                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1695
1696                 // Consume the event.
1697                 return true;
1698
1699             case R.id.save_url:
1700                 // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
1701                 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1702                         currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1703
1704                 // Consume the event.
1705                 return true;
1706
1707             case R.id.save_archive:
1708                 // Instantiate the save dialog.
1709                 DialogFragment saveArchiveFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_ARCHIVE, null, null, getString(R.string.webpage_mht), null,
1710                         false);
1711
1712                 // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
1713                 saveArchiveFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1714
1715                 // Consume the event.
1716                 return true;
1717
1718             case R.id.save_image:
1719                 // Instantiate the save dialog.
1720                 DialogFragment saveImageFragment = SaveWebpageDialog.saveWebpage(StoragePermissionDialog.SAVE_IMAGE, null, null, getString(R.string.webpage_png), null,
1721                         false);
1722
1723                 // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
1724                 saveImageFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1725
1726                 // Consume the event.
1727                 return true;
1728
1729             case R.id.add_to_homescreen:
1730                 // Instantiate the create home screen shortcut dialog.
1731                 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1732                         currentWebView.getFavoriteOrDefaultIcon());
1733
1734                 // Show the create home screen shortcut dialog.
1735                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1736
1737                 // Consume the event.
1738                 return true;
1739
1740             case R.id.view_source:
1741                 // Create an intent to launch the view source activity.
1742                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1743
1744                 // Add the variables to the intent.
1745                 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1746                 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1747
1748                 // Make it so.
1749                 startActivity(viewSourceIntent);
1750
1751                 // Consume the event.
1752                 return true;
1753
1754             case R.id.share_url:
1755                 // Setup the share string.
1756                 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1757
1758                 // Create the share intent.
1759                 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1760
1761                 // Add the share string to the intent.
1762                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1763
1764                 // Set the MIME type.
1765                 shareIntent.setType("text/plain");
1766
1767                 // Set the intent to open in a new task.
1768                 shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1769
1770                 // Make it so.
1771                 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1772
1773                 // Consume the event.
1774                 return true;
1775
1776             case R.id.open_with_app:
1777                 // Open the URL with an outside app.
1778                 openWithApp(currentWebView.getUrl());
1779
1780                 // Consume the event.
1781                 return true;
1782
1783             case R.id.open_with_browser:
1784                 // Open the URL with an outside browser.
1785                 openWithBrowser(currentWebView.getUrl());
1786
1787                 // Consume the event.
1788                 return true;
1789
1790             case R.id.add_or_edit_domain:
1791                 if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1792                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1793                     reapplyDomainSettingsOnRestart = true;
1794
1795                     // Create an intent to launch the domains activity.
1796                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1797
1798                     // Add the extra information to the intent.
1799                     domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1800                     domainsIntent.putExtra("close_on_back", true);
1801                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1802
1803                     // Get the current certificate.
1804                     SslCertificate sslCertificate = currentWebView.getCertificate();
1805
1806                     // Check to see if the SSL certificate is populated.
1807                     if (sslCertificate != null) {
1808                         // Extract the certificate to strings.
1809                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1810                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1811                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1812                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1813                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1814                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1815                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1816                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1817
1818                         // Add the certificate to the intent.
1819                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1820                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1821                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1822                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1823                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1824                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1825                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1826                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1827                     }
1828
1829                     // Check to see if the current IP addresses have been received.
1830                     if (currentWebView.hasCurrentIpAddresses()) {
1831                         // Add the current IP addresses to the intent.
1832                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1833                     }
1834
1835                     // Make it so.
1836                     startActivity(domainsIntent);
1837                 } else {  // Add a new domain.
1838                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1839                     reapplyDomainSettingsOnRestart = true;
1840
1841                     // Get the current domain
1842                     Uri currentUri = Uri.parse(currentWebView.getUrl());
1843                     String currentDomain = currentUri.getHost();
1844
1845                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1846                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1847
1848                     // Create the domain and store the database ID.
1849                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1850
1851                     // Create an intent to launch the domains activity.
1852                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1853
1854                     // Add the extra information to the intent.
1855                     domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1856                     domainsIntent.putExtra("close_on_back", true);
1857                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1858
1859                     // Get the current certificate.
1860                     SslCertificate sslCertificate = currentWebView.getCertificate();
1861
1862                     // Check to see if the SSL certificate is populated.
1863                     if (sslCertificate != null) {
1864                         // Extract the certificate to strings.
1865                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1866                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1867                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1868                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1869                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1870                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1871                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1872                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1873
1874                         // Add the certificate to the intent.
1875                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1876                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1877                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1878                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1879                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1880                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1881                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1882                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1883                     }
1884
1885                     // Check to see if the current IP addresses have been received.
1886                     if (currentWebView.hasCurrentIpAddresses()) {
1887                         // Add the current IP addresses to the intent.
1888                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1889                     }
1890
1891                     // Make it so.
1892                     startActivity(domainsIntent);
1893                 }
1894
1895                 // Consume the event.
1896                 return true;
1897
1898             case R.id.ad_consent:
1899                 // Instantiate the ad consent dialog.
1900                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1901
1902                 // Display the ad consent dialog.
1903                 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1904
1905                 // Consume the event.
1906                 return true;
1907
1908             default:
1909                 // Don't consume the event.
1910                 return super.onOptionsItemSelected(menuItem);
1911         }
1912     }
1913
1914     // removeAllCookies is deprecated, but it is required for API < 21.
1915     @Override
1916     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1917         // Get the menu item ID.
1918         int menuItemId = menuItem.getItemId();
1919
1920         // Get a handle for the shared preferences.
1921         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1922
1923         // Run the commands that correspond to the selected menu item.
1924         switch (menuItemId) {
1925             case R.id.clear_and_exit:
1926                 // Clear and exit Privacy Browser.
1927                 clearAndExit();
1928                 break;
1929
1930             case R.id.home:
1931                 // Load the homepage.
1932                 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1933                 break;
1934
1935             case R.id.back:
1936                 if (currentWebView.canGoBack()) {
1937                     // Get the current web back forward list.
1938                     WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1939
1940                     // Get the previous entry URL.
1941                     String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1942
1943                     // Apply the domain settings.
1944                     applyDomainSettings(currentWebView, previousUrl, false, false, false);
1945
1946                     // Load the previous website in the history.
1947                     currentWebView.goBack();
1948                 }
1949                 break;
1950
1951             case R.id.forward:
1952                 if (currentWebView.canGoForward()) {
1953                     // Get the current web back forward list.
1954                     WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1955
1956                     // Get the next entry URL.
1957                     String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1958
1959                     // Apply the domain settings.
1960                     applyDomainSettings(currentWebView, nextUrl, false, false, false);
1961
1962                     // Load the next website in the history.
1963                     currentWebView.goForward();
1964                 }
1965                 break;
1966
1967             case R.id.history:
1968                 // Instantiate the URL history dialog.
1969                 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1970
1971                 // Show the URL history dialog.
1972                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1973                 break;
1974
1975             case R.id.open:
1976                 // Instantiate the open file dialog.
1977                 DialogFragment openDialogFragment = new OpenDialog();
1978
1979                 // Show the open file dialog.
1980                 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1981                 break;
1982
1983             case R.id.requests:
1984                 // Populate the resource requests.
1985                 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1986
1987                 // Create an intent to launch the Requests activity.
1988                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1989
1990                 // Add the block third-party requests status to the intent.
1991                 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1992
1993                 // Make it so.
1994                 startActivity(requestsIntent);
1995                 break;
1996
1997             case R.id.downloads:
1998                 // Launch the system Download Manager.
1999                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2000
2001                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2002                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2003
2004                 // Make it so.
2005                 startActivity(downloadManagerIntent);
2006                 break;
2007
2008             case R.id.domains:
2009                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2010                 reapplyDomainSettingsOnRestart = true;
2011
2012                 // Launch the domains activity.
2013                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2014
2015                 // Add the extra information to the intent.
2016                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2017
2018                 // Get the current certificate.
2019                 SslCertificate sslCertificate = currentWebView.getCertificate();
2020
2021                 // Check to see if the SSL certificate is populated.
2022                 if (sslCertificate != null) {
2023                     // Extract the certificate to strings.
2024                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
2025                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
2026                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
2027                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
2028                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
2029                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
2030                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2031                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2032
2033                     // Add the certificate to the intent.
2034                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2035                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2036                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2037                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2038                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2039                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2040                     domainsIntent.putExtra("ssl_start_date", startDateLong);
2041                     domainsIntent.putExtra("ssl_end_date", endDateLong);
2042                 }
2043
2044                 // Check to see if the current IP addresses have been received.
2045                 if (currentWebView.hasCurrentIpAddresses()) {
2046                     // Add the current IP addresses to the intent.
2047                     domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2048                 }
2049
2050                 // Make it so.
2051                 startActivity(domainsIntent);
2052                 break;
2053
2054             case R.id.settings:
2055                 // Set the flag to reapply app settings on restart when returning from Settings.
2056                 reapplyAppSettingsOnRestart = true;
2057
2058                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2059                 reapplyDomainSettingsOnRestart = true;
2060
2061                 // Launch the settings activity.
2062                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2063                 startActivity(settingsIntent);
2064                 break;
2065
2066             case R.id.import_export:
2067                 // Launch the import/export activity.
2068                 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2069                 startActivity(importExportIntent);
2070                 break;
2071
2072             case R.id.logcat:
2073                 // Launch the logcat activity.
2074                 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2075                 startActivity(logcatIntent);
2076                 break;
2077
2078             case R.id.guide:
2079                 // Launch `GuideActivity`.
2080                 Intent guideIntent = new Intent(this, GuideActivity.class);
2081                 startActivity(guideIntent);
2082                 break;
2083
2084             case R.id.about:
2085                 // Create an intent to launch the about activity.
2086                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2087
2088                 // Create a string array for the blocklist versions.
2089                 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],
2090                         ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2091
2092                 // Add the blocklist versions to the intent.
2093                 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2094
2095                 // Make it so.
2096                 startActivity(aboutIntent);
2097                 break;
2098         }
2099
2100         // Close the navigation drawer.
2101         drawerLayout.closeDrawer(GravityCompat.START);
2102         return true;
2103     }
2104
2105     @Override
2106     public void onPostCreate(Bundle savedInstanceState) {
2107         // Run the default commands.
2108         super.onPostCreate(savedInstanceState);
2109
2110         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2111         actionBarDrawerToggle.syncState();
2112     }
2113
2114     @Override
2115     public void onConfigurationChanged(@NonNull Configuration newConfig) {
2116         // Run the default commands.
2117         super.onConfigurationChanged(newConfig);
2118
2119         // Reload the ad for the free flavor if not in full screen mode.
2120         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2121             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2122             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2123         }
2124
2125         // `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:
2126         // https://code.google.com/p/android/issues/detail?id=20493#c8
2127         // ActivityCompat.invalidateOptionsMenu(this);
2128     }
2129
2130     @Override
2131     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2132         // Get the hit test result.
2133         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2134
2135         // Define the URL strings.
2136         final String imageUrl;
2137         final String linkUrl;
2138
2139         // Get handles for the system managers.
2140         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2141
2142         // Remove the lint errors below that the clipboard manager might be null.
2143         assert clipboardManager != null;
2144
2145         // Process the link according to the type.
2146         switch (hitTestResult.getType()) {
2147             // `SRC_ANCHOR_TYPE` is a link.
2148             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2149                 // Get the target URL.
2150                 linkUrl = hitTestResult.getExtra();
2151
2152                 // Set the target URL as the title of the `ContextMenu`.
2153                 menu.setHeaderTitle(linkUrl);
2154
2155                 // Add an Open in New Tab entry.
2156                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2157                     // Load the link URL in a new tab and move to it.
2158                     addNewTab(linkUrl, true);
2159
2160                     // Consume the event.
2161                     return true;
2162                 });
2163
2164                 // Add an Open in Background entry.
2165                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2166                     // Load the link URL in a new tab but do not move to it.
2167                     addNewTab(linkUrl, false);
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                     openWithApp(linkUrl);
2176
2177                     // Consume the event.
2178                     return true;
2179                 });
2180
2181                 // Add an Open with Browser entry.
2182                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2183                     openWithBrowser(linkUrl);
2184
2185                     // Consume the event.
2186                     return true;
2187                 });
2188
2189                 // Add a Copy URL entry.
2190                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2191                     // Save the link URL in a `ClipData`.
2192                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2193
2194                     // Set the `ClipData` as the clipboard's primary clip.
2195                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2196
2197                     // Consume the event.
2198                     return true;
2199                 });
2200
2201                 // Add a Save URL entry.
2202                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2203                     // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2204                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2205                             currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2206
2207                     // Consume the event.
2208                     return true;
2209                 });
2210
2211                 // Add an empty Cancel entry, which by default closes the context menu.
2212                 menu.add(R.string.cancel);
2213                 break;
2214
2215             // `IMAGE_TYPE` is an image.
2216             case WebView.HitTestResult.IMAGE_TYPE:
2217                 // Get the image URL.
2218                 imageUrl = hitTestResult.getExtra();
2219
2220                 // Remove the incorrect lint warning below that the image URL might be null.
2221                 assert imageUrl != null;
2222
2223                 // Set the context menu title.
2224                 if (imageUrl.startsWith("data:")) {  // The image data is contained in within the URL, making it exceedingly long.
2225                     // Truncate the image URL before making it the title.
2226                     menu.setHeaderTitle(imageUrl.substring(0, 100));
2227                 } else {  // The image URL does not contain the full image data.
2228                     // Set the image URL as the title of the context menu.
2229                     menu.setHeaderTitle(imageUrl);
2230                 }
2231
2232                 // Add an Open in New Tab entry.
2233                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2234                     // Load the image in a new tab.
2235                     addNewTab(imageUrl, true);
2236
2237                     // Consume the event.
2238                     return true;
2239                 });
2240
2241                 // Add an Open with App entry.
2242                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2243                     // Open the image URL with an external app.
2244                     openWithApp(imageUrl);
2245
2246                     // Consume the event.
2247                     return true;
2248                 });
2249
2250                 // Add an Open with Browser entry.
2251                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2252                     // Open the image URL with an external browser.
2253                     openWithBrowser(imageUrl);
2254
2255                     // Consume the event.
2256                     return true;
2257                 });
2258
2259                 // Add a View Image entry.
2260                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2261                     // Load the image in the current tab.
2262                     loadUrl(currentWebView, imageUrl);
2263
2264                     // Consume the event.
2265                     return true;
2266                 });
2267
2268                 // Add a Save Image entry.
2269                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2270                    // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2271                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2272                             currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2273
2274                     // Consume the event.
2275                     return true;
2276                 });
2277
2278                 // Add a Copy URL entry.
2279                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2280                     // Save the image URL in a clip data.
2281                     ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2282
2283                     // Set the clip data as the clipboard's primary clip.
2284                     clipboardManager.setPrimaryClip(imageTypeClipData);
2285
2286                     // Consume the event.
2287                     return true;
2288                 });
2289
2290                 // Add an empty Cancel entry, which by default closes the context menu.
2291                 menu.add(R.string.cancel);
2292                 break;
2293
2294             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2295             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2296                 // Get the image URL.
2297                 imageUrl = hitTestResult.getExtra();
2298
2299                 // Instantiate a handler.
2300                 Handler handler = new Handler();
2301
2302                 // Get a message from the handler.
2303                 Message message = handler.obtainMessage();
2304
2305                 // Request the image details from the last touched node be returned in the message.
2306                 currentWebView.requestFocusNodeHref(message);
2307
2308                 // Get the link URL from the message data.
2309                 linkUrl = message.getData().getString("url");
2310
2311                 // Set the link URL as the title of the context menu.
2312                 menu.setHeaderTitle(linkUrl);
2313
2314                 // Add an Open in New Tab entry.
2315                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2316                     // Load the link URL in a new tab and move to it.
2317                     addNewTab(linkUrl, true);
2318
2319                     // Consume the event.
2320                     return true;
2321                 });
2322
2323                 // Add an Open in Background entry.
2324                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2325                     // Lod the link URL in a new tab but do not move to it.
2326                     addNewTab(linkUrl, false);
2327
2328                     // Consume the event.
2329                     return true;
2330                 });
2331
2332                 // Add an Open Image in New Tab entry.
2333                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2334                     // Load the image in a new tab and move to it.
2335                     addNewTab(imageUrl, true);
2336
2337                     // Consume the event.
2338                     return true;
2339                 });
2340
2341                 // Add an Open with App entry.
2342                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2343                     // Open the link URL with an external app.
2344                     openWithApp(linkUrl);
2345
2346                     // Consume the event.
2347                     return true;
2348                 });
2349
2350                 // Add an Open with Browser entry.
2351                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2352                     // Open the link URL with an external browser.
2353                     openWithBrowser(linkUrl);
2354
2355                     // Consume the event.
2356                     return true;
2357                 });
2358
2359                 // Add a View Image entry.
2360                 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2361                    // View the image in the current tab.
2362                    loadUrl(currentWebView, imageUrl);
2363
2364                    // Consume the event.
2365                    return true;
2366                 });
2367
2368                 // Add a Save Image entry.
2369                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2370                     // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2371                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2372                             currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2373
2374                     // Consume the event.
2375                     return true;
2376                 });
2377
2378                 // Add a Copy URL entry.
2379                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2380                     // Save the link URL in a clip data.
2381                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2382
2383                     // Set the clip data as the clipboard's primary clip.
2384                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2385
2386                     // Consume the event.
2387                     return true;
2388                 });
2389
2390                 // Add a Save URL entry.
2391                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2392                     // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2393                     new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2394                             currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2395
2396                     // Consume the event.
2397                     return true;
2398                 });
2399
2400                 // Add an empty Cancel entry, which by default closes the context menu.
2401                 menu.add(R.string.cancel);
2402                 break;
2403
2404             case WebView.HitTestResult.EMAIL_TYPE:
2405                 // Get the target URL.
2406                 linkUrl = hitTestResult.getExtra();
2407
2408                 // Set the target URL as the title of the `ContextMenu`.
2409                 menu.setHeaderTitle(linkUrl);
2410
2411                 // Add a Write Email entry.
2412                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2413                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2414                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2415
2416                     // Parse the url and set it as the data for the `Intent`.
2417                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2418
2419                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2420                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2421
2422                     try {
2423                         // Make it so.
2424                         startActivity(emailIntent);
2425                     } catch (ActivityNotFoundException exception) {
2426                         // Display a snackbar.
2427                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
2428                     }
2429
2430                     // Consume the event.
2431                     return true;
2432                 });
2433
2434                 // Add a Copy Email Address entry.
2435                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2436                     // Save the email address in a `ClipData`.
2437                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2438
2439                     // Set the `ClipData` as the clipboard's primary clip.
2440                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2441
2442                     // Consume the event.
2443                     return true;
2444                 });
2445
2446                 // Add an empty Cancel entry, which by default closes the context menu.
2447                 menu.add(R.string.cancel);
2448                 break;
2449         }
2450     }
2451
2452     @Override
2453     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2454         // Get a handle for the bookmarks list view.
2455         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2456
2457         // Get the dialog.
2458         Dialog dialog = dialogFragment.getDialog();
2459
2460         // Remove the incorrect lint warning below that the dialog might be null.
2461         assert dialog != null;
2462
2463         // Get the views from the dialog fragment.
2464         EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2465         EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2466
2467         // Extract the strings from the edit texts.
2468         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2469         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2470
2471         // Create a favorite icon byte array output stream.
2472         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2473
2474         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2475         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2476
2477         // Convert the favorite icon byte array stream to a byte array.
2478         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2479
2480         // Display the new bookmark below the current items in the (0 indexed) list.
2481         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2482
2483         // Create the bookmark.
2484         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2485
2486         // Update the bookmarks cursor with the current contents of this folder.
2487         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2488
2489         // Update the list view.
2490         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2491
2492         // Scroll to the new bookmark.
2493         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2494     }
2495
2496     @Override
2497     public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2498         // Get a handle for the bookmarks list view.
2499         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2500
2501         // Get the dialog.
2502         Dialog dialog = dialogFragment.getDialog();
2503
2504         // Remove the incorrect lint warning below that the dialog might be null.
2505         assert dialog != null;
2506
2507         // Get handles for the views in the dialog fragment.
2508         EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2509         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2510         ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2511
2512         // Get new folder name string.
2513         String folderNameString = createFolderNameEditText.getText().toString();
2514
2515         // Create a folder icon bitmap.
2516         Bitmap folderIconBitmap;
2517
2518         // Set the folder icon bitmap according to the dialog.
2519         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2520             // Get the default folder icon drawable.
2521             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2522
2523             // Convert the folder icon drawable to a bitmap drawable.
2524             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2525
2526             // Convert the folder icon bitmap drawable to a bitmap.
2527             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2528         } else {  // Use the WebView favorite icon.
2529             // Copy the favorite icon bitmap to the folder icon bitmap.
2530             folderIconBitmap = favoriteIconBitmap;
2531         }
2532
2533         // Create a folder icon byte array output stream.
2534         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2535
2536         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2537         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2538
2539         // Convert the folder icon byte array stream to a byte array.
2540         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2541
2542         // Move all the bookmarks down one in the display order.
2543         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2544             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2545             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2546         }
2547
2548         // Create the folder, which will be placed at the top of the `ListView`.
2549         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2550
2551         // Update the bookmarks cursor with the current contents of this folder.
2552         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2553
2554         // Update the `ListView`.
2555         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2556
2557         // Scroll to the new folder.
2558         bookmarksListView.setSelection(0);
2559     }
2560
2561     @Override
2562     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2563         // Get the dialog.
2564         Dialog dialog = dialogFragment.getDialog();
2565
2566         // Remove the incorrect lint warning below that the dialog might be null.
2567         assert dialog != null;
2568
2569         // Get handles for the views from `dialogFragment`.
2570         EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2571         RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2572         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2573         ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2574
2575         // Get the new folder name.
2576         String newFolderNameString = editFolderNameEditText.getText().toString();
2577
2578         // Check if the favorite icon has changed.
2579         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
2580             // Update the name in the database.
2581             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2582         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
2583             // Create the new folder icon Bitmap.
2584             Bitmap folderIconBitmap;
2585
2586             // Populate the new folder icon bitmap.
2587             if (defaultFolderIconRadioButton.isChecked()) {
2588                 // Get the default folder icon drawable.
2589                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2590
2591                 // Convert the folder icon drawable to a bitmap drawable.
2592                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2593
2594                 // Convert the folder icon bitmap drawable to a bitmap.
2595                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2596             } else {  // Use the `WebView` favorite icon.
2597                 // Copy the favorite icon bitmap to the folder icon bitmap.
2598                 folderIconBitmap = favoriteIconBitmap;
2599             }
2600
2601             // Create a folder icon byte array output stream.
2602             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2603
2604             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2605             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2606
2607             // Convert the folder icon byte array stream to a byte array.
2608             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2609
2610             // Update the folder icon in the database.
2611             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2612         } else {  // The folder icon and the name have changed.
2613             // Get the new folder icon `Bitmap`.
2614             Bitmap folderIconBitmap;
2615             if (defaultFolderIconRadioButton.isChecked()) {
2616                 // Get the default folder icon drawable.
2617                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2618
2619                 // Convert the folder icon drawable to a bitmap drawable.
2620                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2621
2622                 // Convert the folder icon bitmap drawable to a bitmap.
2623                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2624             } else {  // Use the `WebView` favorite icon.
2625                 // Copy the favorite icon bitmap to the folder icon bitmap.
2626                 folderIconBitmap = favoriteIconBitmap;
2627             }
2628
2629             // Create a folder icon byte array output stream.
2630             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2631
2632             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2633             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2634
2635             // Convert the folder icon byte array stream to a byte array.
2636             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2637
2638             // Update the folder name and icon in the database.
2639             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2640         }
2641
2642         // Update the bookmarks cursor with the current contents of this folder.
2643         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2644
2645         // Update the `ListView`.
2646         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2647     }
2648
2649     // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2650     @Override
2651     public void onBackPressed() {
2652         // Check the different options for processing `back`.
2653         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
2654             // Close the navigation drawer.
2655             drawerLayout.closeDrawer(GravityCompat.START);
2656         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
2657             // close the bookmarks drawer.
2658             drawerLayout.closeDrawer(GravityCompat.END);
2659         } else if (displayingFullScreenVideo) {  // A full screen video is shown.
2660             // Get a handle for the layouts.
2661             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2662             RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2663             FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);