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