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