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