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