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