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