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