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