]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Add WebView DevTools to the navigation menu. https://redmine.stoutner.com/issues/893
[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.OnBackPressedCallback;
103 import androidx.activity.result.ActivityResultCallback;
104 import androidx.activity.result.ActivityResultLauncher;
105 import androidx.activity.result.contract.ActivityResultContracts;
106 import androidx.annotation.NonNull;
107 import androidx.appcompat.app.ActionBar;
108 import androidx.appcompat.app.ActionBarDrawerToggle;
109 import androidx.appcompat.app.AppCompatActivity;
110 import androidx.appcompat.app.AppCompatDelegate;
111 import androidx.appcompat.widget.Toolbar;
112 import androidx.coordinatorlayout.widget.CoordinatorLayout;
113 import androidx.core.content.res.ResourcesCompat;
114 import androidx.core.view.GravityCompat;
115 import androidx.drawerlayout.widget.DrawerLayout;
116 import androidx.fragment.app.DialogFragment;
117 import androidx.fragment.app.Fragment;
118 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
119 import androidx.viewpager.widget.ViewPager;
120 import androidx.webkit.WebSettingsCompat;
121 import androidx.webkit.WebViewFeature;
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.helpers.SanitizeUrlHelper;
157 import com.stoutner.privacybrowser.views.NestedScrollWebView;
158
159 import java.io.ByteArrayInputStream;
160 import java.io.ByteArrayOutputStream;
161 import java.io.File;
162 import java.io.FileInputStream;
163 import java.io.FileOutputStream;
164 import java.io.IOException;
165 import java.io.InputStream;
166 import java.io.OutputStream;
167 import java.io.UnsupportedEncodingException;
168
169 import java.net.MalformedURLException;
170 import java.net.URL;
171 import java.net.URLDecoder;
172 import java.net.URLEncoder;
173
174 import java.text.NumberFormat;
175
176 import java.util.ArrayList;
177 import java.util.Date;
178 import java.util.HashSet;
179 import java.util.List;
180 import java.util.Objects;
181 import java.util.Set;
182 import java.util.concurrent.ExecutorService;
183 import java.util.concurrent.Executors;
184
185 import kotlin.Pair;
186
187 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
188         EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
189         PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveListener, UrlHistoryDialog.NavigateHistoryListener,
190         WebViewTabFragment.NewTabListener {
191
192     // Define the public static variables.
193     public static ExecutorService executorService = Executors.newFixedThreadPool(4);
194     public static String orbotStatus = "unknown";
195     public static ArrayList<PendingDialog> pendingDialogsArrayList =  new ArrayList<>();
196     public static String proxyMode = ProxyHelper.NONE;
197
198     // Declare the public static variables.
199     public static String currentBookmarksFolder = "";
200     public static boolean restartFromBookmarksActivity;
201     public static WebViewPagerAdapter webViewPagerAdapter;
202
203     // Declare the public static views.
204     public static AppBarLayout appBarLayout;
205
206     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
207     public final static int UNRECOGNIZED_USER_AGENT = -1;
208     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
209     public final static int SETTINGS_CUSTOM_USER_AGENT = 11;
210     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
211     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
212     public final static int DOMAINS_CUSTOM_USER_AGENT = 12;
213
214     // Define the start activity for result request codes.  The public static entry is accessed from `OpenDialog()`.
215     private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
216     public final static int BROWSE_OPEN_REQUEST_CODE = 1;
217
218     // Define the saved instance state constants.
219     private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
220     private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
221     private final String SAVED_TAB_POSITION = "saved_tab_position";
222     private final String PROXY_MODE = "proxy_mode";
223
224     // Define the saved instance state variables.
225     private ArrayList<Bundle> savedStateArrayList;
226     private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
227     private int savedTabPosition;
228     private String savedProxyMode;
229
230     // Define the class variables.
231     @SuppressWarnings("rawtypes")
232     AsyncTask populateBlocklists;
233
234     // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
235     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
236     private NestedScrollWebView currentWebView;
237
238     // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
239     private String searchURL;
240
241     // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
242     private ArrayList<List<String[]>> easyList;
243     private ArrayList<List<String[]>> easyPrivacy;
244     private ArrayList<List<String[]>> fanboysAnnoyanceList;
245     private ArrayList<List<String[]>> fanboysSocialList;
246     private ArrayList<List<String[]>> ultraList;
247     private ArrayList<List<String[]>> ultraPrivacy;
248
249     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
250     private ActionBarDrawerToggle actionBarDrawerToggle;
251
252     // The color spans are used in `onCreate()` and `highlightUrlText()`.
253     private ForegroundColorSpan redColorSpan;
254     private ForegroundColorSpan initialGrayColorSpan;
255     private ForegroundColorSpan finalGrayColorSpan;
256
257     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
258     private Cursor bookmarksCursor;
259
260     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
261     private CursorAdapter bookmarksCursorAdapter;
262
263     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
264     private String oldFolderNameString;
265
266     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
267     private ValueCallback<Uri[]> fileChooserCallback;
268
269     // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
270     private int appBarHeight;
271     private int defaultProgressViewStartOffset;
272     private int defaultProgressViewEndOffset;
273
274     // Declare the helpers.
275     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
276     private DomainsDatabaseHelper domainsDatabaseHelper;
277     private ProxyHelper proxyHelper;
278     private SanitizeUrlHelper sanitizeUrlHelper;
279
280     // Declare the class variables
281     private boolean bottomAppBar;
282     private boolean displayAdditionalAppBarIcons;
283     private boolean displayingFullScreenVideo;
284     private boolean downloadWithExternalApp;
285     private boolean fullScreenBrowsingModeEnabled;
286     private boolean hideAppBar;
287     private boolean incognitoModeEnabled;
288     private boolean inFullScreenBrowsingMode;
289     private boolean loadingNewIntent;
290     private BroadcastReceiver orbotStatusBroadcastReceiver;
291     private boolean reapplyAppSettingsOnRestart;
292     private boolean reapplyDomainSettingsOnRestart;
293     private boolean sanitizeAmpRedirects;
294     private boolean sanitizeTrackingQueries;
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("text/*"),
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("multipart/related"),
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("image/png"),
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(getString(R.string.app_theme_key), 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         displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
507
508         // Get the theme entry values string array.
509         String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
510
511         // 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.
512         if (appTheme.equals(appThemeEntryValuesStringArray[1])) {  // The light theme is selected.
513             // Apply the light theme.
514             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
515         } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
516             // Apply the dark theme.
517             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
518         } else {  // The system default theme is selected.
519             if (Build.VERSION.SDK_INT >= 28) {  // The system default theme is supported.
520                 // Follow the system default theme.
521                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
522             } else {  // The system default theme is not supported.
523                 // Follow the battery saver mode.
524                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
525             }
526         }
527
528         // Disable screenshots if not allowed.
529         if (!allowScreenshots) {
530             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
531         }
532
533         // 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.
534         WebView.enableSlowWholeDocumentDraw();
535
536         // Set the content view according to the position of the app bar.
537         if (bottomAppBar) setContentView(R.layout.main_framelayout_bottom_appbar);
538         else setContentView(R.layout.main_framelayout_top_appbar);
539
540         // Get handles for the views.
541         rootFrameLayout = findViewById(R.id.root_framelayout);
542         drawerLayout = findViewById(R.id.drawerlayout);
543         coordinatorLayout = findViewById(R.id.coordinatorlayout);
544         appBarLayout = findViewById(R.id.appbar_layout);
545         toolbar = findViewById(R.id.toolbar);
546         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
547         tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
548         tabLayout = findViewById(R.id.tablayout);
549         swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
550         webViewPager = findViewById(R.id.webviewpager);
551         NavigationView navigationView = findViewById(R.id.navigationview);
552         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
553
554         // Get a handle for the navigation menu.
555         Menu navigationMenu = navigationView.getMenu();
556
557         // Get handles for the navigation menu items.
558         navigationBackMenuItem = navigationMenu.findItem(R.id.back);
559         navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
560         navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
561         navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
562
563         // Listen for touches on the navigation menu.
564         navigationView.setNavigationItemSelectedListener(this);
565
566         // Get a handle for the app compat delegate.
567         AppCompatDelegate appCompatDelegate = getDelegate();
568
569         // Set the support action bar.
570         appCompatDelegate.setSupportActionBar(toolbar);
571
572         // Get a handle for the action bar.
573         actionBar = appCompatDelegate.getSupportActionBar();
574
575         // Remove the incorrect lint warning below that the action bar might be null.
576         assert actionBar != null;
577
578         // Add the custom layout, which shows the URL text bar.
579         actionBar.setCustomView(R.layout.url_app_bar);
580         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
581
582         // Get handles for the views in the URL app bar.
583         urlRelativeLayout = findViewById(R.id.url_relativelayout);
584         urlEditText = findViewById(R.id.url_edittext);
585
586         // Create the hamburger icon at the start of the AppBar.
587         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
588
589         // Initially disable the sliding drawers.  They will be enabled once the blocklists are loaded.
590         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
591
592         // Initialize the web view pager adapter.
593         webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
594
595         // Set the pager adapter on the web view pager.
596         webViewPager.setAdapter(webViewPagerAdapter);
597
598         // Store up to 100 tabs in memory.
599         webViewPager.setOffscreenPageLimit(100);
600
601         // Instantiate the helpers.
602         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
603         domainsDatabaseHelper = new DomainsDatabaseHelper(this);
604         proxyHelper = new ProxyHelper();
605         sanitizeUrlHelper = new SanitizeUrlHelper();
606
607         // Initialize the app.
608         initializeApp();
609
610         // Apply the app settings from the shared preferences.
611         applyAppSettings();
612
613         // Control what the system back command does.
614         OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) {
615             @Override
616             public void handleOnBackPressed() {
617                 // Process the different back options.
618                 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
619                     // Close the navigation drawer.
620                     drawerLayout.closeDrawer(GravityCompat.START);
621                 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
622                     // close the bookmarks drawer.
623                     drawerLayout.closeDrawer(GravityCompat.END);
624                 } else if (displayingFullScreenVideo) {  // A full screen video is shown.
625                     // Exit the full screen video.
626                     exitFullScreenVideo();
627                 } else if (currentWebView.canGoBack()) {  // There is at least one item in the current WebView history.
628                     // Get the current web back forward list.
629                     WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
630
631                     // Get the previous entry URL.
632                     String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
633
634                     // Apply the domain settings.
635                     applyDomainSettings(currentWebView, previousUrl, false, false, false);
636
637                     // Go back.
638                     currentWebView.goBack();
639                 } else if (tabLayout.getTabCount() > 1) {  // There are at least two tabs.
640                     // Close the current tab.
641                     closeCurrentTab();
642                 } else {  // There isn't anything to do in Privacy Browser.
643                     // Close Privacy Browser.  `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
644                     finishAndRemoveTask();
645
646                     // Manually kill Privacy Browser.  Otherwise, it is glitchy when restarted.
647                     System.exit(0);
648                 }
649             }
650         };
651
652         // Register the on back pressed callback.
653         getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
654
655         // Populate the blocklists.
656         populateBlocklists = new PopulateBlocklists(this, this).execute();
657     }
658
659     @Override
660     protected void onNewIntent(Intent intent) {
661         // Run the default commands.
662         super.onNewIntent(intent);
663
664         // Check to see if the app is being restarted from a saved state.
665         if (savedStateArrayList == null || savedStateArrayList.size() == 0) {  // The activity is not being restarted from a saved state.
666             // Get the information from the intent.
667             String intentAction = intent.getAction();
668             Uri intentUriData = intent.getData();
669             String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
670
671             // Determine if this is a web search.
672             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
673
674             // 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.
675             if (intentUriData != null || intentStringExtra != null || isWebSearch) {
676                 // Exit the full screen video if it is displayed.
677                 if (displayingFullScreenVideo) {
678                     // Exit full screen video mode.
679                     exitFullScreenVideo();
680
681                     // Reload the current WebView.  Otherwise, it can display entirely black.
682                     currentWebView.reload();
683                 }
684
685                 // Get the shared preferences.
686                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
687
688                 // Create a URL string.
689                 String url;
690
691                 // If the intent action is a web search, perform the search.
692                 if (isWebSearch) {  // The intent is a web search.
693                     // Create an encoded URL string.
694                     String encodedUrlString;
695
696                     // Sanitize the search input and convert it to a search.
697                     try {
698                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
699                     } catch (UnsupportedEncodingException exception) {
700                         encodedUrlString = "";
701                     }
702
703                     // Add the base search URL.
704                     url = searchURL + encodedUrlString;
705                 } else if (intentUriData != null) {  // The intent contains a URL formatted as a URI.
706                     // Set the intent data as the URL.
707                     url = intentUriData.toString();
708                 } else {  // The intent contains a string, which might be a URL.
709                     // Set the intent string as the URL.
710                     url = intentStringExtra;
711                 }
712
713                 // Add a new tab if specified in the preferences.
714                 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) {  // Load the URL in a new tab.
715                     // Set the loading new intent flag.
716                     loadingNewIntent = true;
717
718                     // Add a new tab.
719                     addNewTab(url, true);
720                 } else {  // Load the URL in the current tab.
721                     // Make it so.
722                     loadUrl(currentWebView, url);
723                 }
724
725                 // Close the navigation drawer if it is open.
726                 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
727                     drawerLayout.closeDrawer(GravityCompat.START);
728                 }
729
730                 // Close the bookmarks drawer if it is open.
731                 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
732                     drawerLayout.closeDrawer(GravityCompat.END);
733                 }
734             }
735         } else {  // The app has been restarted.
736             // Replace the intent that started the app with this one.  This will load the tab after the others have been restored.
737             setIntent(intent);
738         }
739     }
740
741     @Override
742     public void onRestart() {
743         // Run the default commands.
744         super.onRestart();
745
746         // Apply the app settings if returning from the Settings activity.
747         if (reapplyAppSettingsOnRestart) {
748             // Reset the reapply app settings on restart tracker.
749             reapplyAppSettingsOnRestart = false;
750
751             // Apply the app settings.
752             applyAppSettings();
753         }
754
755         // Apply the domain settings if returning from the settings or domains activity.
756         if (reapplyDomainSettingsOnRestart) {
757             // Reset the reapply domain settings on restart tracker.
758             reapplyDomainSettingsOnRestart = false;
759
760             // Reapply the domain settings for each tab.
761             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
762                 // Get the WebView tab fragment.
763                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
764
765                 // Get the fragment view.
766                 View fragmentView = webViewTabFragment.getView();
767
768                 // Only reload the WebViews if they exist.
769                 if (fragmentView != null) {
770                     // Get the nested scroll WebView from the tab fragment.
771                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
772
773                     // Reset the current domain name so the domain settings will be reapplied.
774                     nestedScrollWebView.setCurrentDomainName("");
775
776                     // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
777                     if (nestedScrollWebView.getUrl() != null) {
778                         applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
779                     }
780                 }
781             }
782         }
783
784         // Update the bookmarks drawer if returning from the Bookmarks activity.
785         if (restartFromBookmarksActivity) {
786             // Close the bookmarks drawer.
787             drawerLayout.closeDrawer(GravityCompat.END);
788
789             // Reload the bookmarks drawer.
790             loadBookmarksFolder();
791
792             // Reset `restartFromBookmarksActivity`.
793             restartFromBookmarksActivity = false;
794         }
795
796         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
797         updatePrivacyIcons(true);
798     }
799
800     // `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.
801     @Override
802     public void onStart() {
803         // Run the default commands.
804         super.onStart();
805
806         // Resume any WebViews.
807         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
808             // Get the WebView tab fragment.
809             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
810
811             // Get the fragment view.
812             View fragmentView = webViewTabFragment.getView();
813
814             // Only resume the WebViews if they exist (they won't when the app is first created).
815             if (fragmentView != null) {
816                 // Get the nested scroll WebView from the tab fragment.
817                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
818
819                 // Resume the nested scroll WebView.
820                 nestedScrollWebView.onResume();
821             }
822         }
823
824         // Resume the nested scroll WebView JavaScript timers.  This is a global command that resumes JavaScript timers on all WebViews.
825         if (currentWebView != null) {
826             currentWebView.resumeTimers();
827         }
828
829         // Reapply the proxy settings if the system is using a proxy.  This redisplays the appropriate alert dialog.
830         if (!proxyMode.equals(ProxyHelper.NONE)) {
831             applyProxy(false);
832         }
833
834         // Reapply any system UI flags.
835         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {  // The system is displaying a website or a video in full screen mode.
836             /* Hide the system bars.
837              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
838              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
839              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
840              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
841              */
842             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
843                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
844         }
845
846         // Show any pending dialogs.
847         for (int i = 0; i < pendingDialogsArrayList.size(); i++) {
848             // Get the pending dialog from the array list.
849             PendingDialog pendingDialog = pendingDialogsArrayList.get(i);
850
851             // Show the pending dialog.
852             pendingDialog.dialogFragment.show(getSupportFragmentManager(), pendingDialog.tag);
853         }
854
855         // Clear the pending dialogs array list.
856         pendingDialogsArrayList.clear();
857     }
858
859     // `onStop()` runs after `onPause()`.  It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
860     @Override
861     public void onStop() {
862         // Run the default commands.
863         super.onStop();
864
865         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
866             // Get the WebView tab fragment.
867             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
868
869             // Get the fragment view.
870             View fragmentView = webViewTabFragment.getView();
871
872             // Only pause the WebViews if they exist (they won't when the app is first created).
873             if (fragmentView != null) {
874                 // Get the nested scroll WebView from the tab fragment.
875                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
876
877                 // Pause the nested scroll WebView.
878                 nestedScrollWebView.onPause();
879             }
880         }
881
882         // Pause the WebView JavaScript timers.  This is a global command that pauses JavaScript on all WebViews.
883         if (currentWebView != null) {
884             currentWebView.pauseTimers();
885         }
886     }
887
888     @Override
889     public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
890         // Run the default commands.
891         super.onSaveInstanceState(savedInstanceState);
892
893         // Create the saved state array lists.
894         ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
895         ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
896
897         // Get the URLs from each tab.
898         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
899             // Get the WebView tab fragment.
900             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
901
902             // Get the fragment view.
903             View fragmentView = webViewTabFragment.getView();
904
905             if (fragmentView != null) {
906                 // Get the nested scroll WebView from the tab fragment.
907                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
908
909                 // Create saved state bundle.
910                 Bundle savedStateBundle = new Bundle();
911
912                 // Get the current states.
913                 nestedScrollWebView.saveState(savedStateBundle);
914                 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
915
916                 // Store the saved states in the array lists.
917                 savedStateArrayList.add(savedStateBundle);
918                 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
919             }
920         }
921
922         // Get the current tab position.
923         int currentTabPosition = tabLayout.getSelectedTabPosition();
924
925         // Store the saved states in the bundle.
926         savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
927         savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
928         savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
929         savedInstanceState.putString(PROXY_MODE, proxyMode);
930     }
931
932     @Override
933     public void onDestroy() {
934         // Unregister the orbot status broadcast receiver if it exists.
935         if (orbotStatusBroadcastReceiver != null) {
936             this.unregisterReceiver(orbotStatusBroadcastReceiver);
937         }
938
939         // Close the bookmarks cursor if it exists.
940         if (bookmarksCursor != null) {
941             bookmarksCursor.close();
942         }
943
944         // Close the bookmarks database if it exists.
945         if (bookmarksDatabaseHelper != null) {
946             bookmarksDatabaseHelper.close();
947         }
948
949         // Stop populating the blocklists if the AsyncTask is running in the background.
950         if (populateBlocklists != null) {
951             populateBlocklists.cancel(true);
952         }
953
954         // Run the default commands.
955         super.onDestroy();
956     }
957
958     @Override
959     public boolean onCreateOptionsMenu(Menu menu) {
960         // Inflate the menu.  This adds items to the action bar if it is present.
961         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
962
963         // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
964         optionsMenu = menu;
965
966         // Get handles for the menu items.
967         optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
968         optionsRefreshMenuItem = menu.findItem(R.id.refresh);
969         MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
970         optionsCookiesMenuItem = menu.findItem(R.id.cookies);
971         optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
972         optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data);  // Form data can be removed once the minimum API >= 26.
973         optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
974         optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
975         optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
976         optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
977         optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
978         optionsEasyListMenuItem = menu.findItem(R.id.easylist);
979         optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
980         optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
981         optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
982         optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
983         optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
984         optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
985         optionsProxyMenuItem = menu.findItem(R.id.proxy);
986         optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
987         optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
988         optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
989         optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
990         optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
991         optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
992         optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
993         optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
994         optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
995         optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
996         optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
997         optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
998         optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
999         optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
1000         optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
1001         optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
1002         optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
1003         optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
1004         optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1005         optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
1006         optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
1007         optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
1008         optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
1009         optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
1010
1011         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1012         updatePrivacyIcons(false);
1013
1014         // Only display the form data menu items if the API < 26.
1015         optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1016         optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1017
1018         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1019         optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1020
1021         // 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.
1022         if (displayAdditionalAppBarIcons) {
1023             optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1024             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1025             optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1026         } else { //Do not display the additional icons.
1027             optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1028             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1029             optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1030         }
1031
1032         // Replace Refresh with Stop if a URL is already loading.
1033         if (currentWebView != null && currentWebView.getProgress() != 100) {
1034             // Set the title.
1035             optionsRefreshMenuItem.setTitle(R.string.stop);
1036
1037             // 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.
1038             if (displayAdditionalAppBarIcons) {
1039                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
1040             }
1041         }
1042
1043         // Done.
1044         return true;
1045     }
1046
1047     @Override
1048     public boolean onPrepareOptionsMenu(Menu menu) {
1049         // Get a handle for the cookie manager.
1050         CookieManager cookieManager = CookieManager.getInstance();
1051
1052         // Initialize the current user agent string and the font size.
1053         String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1054         int fontSize = 100;
1055
1056         // 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.
1057         if (currentWebView != null) {
1058             // Set the add or edit domain text.
1059             if (currentWebView.getDomainSettingsApplied()) {
1060                 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1061             } else {
1062                 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1063             }
1064
1065             // Get the current user agent from the WebView.
1066             currentUserAgent = currentWebView.getSettings().getUserAgentString();
1067
1068             // Get the current font size from the
1069             fontSize = currentWebView.getSettings().getTextZoom();
1070
1071             // Set the status of the menu item checkboxes.
1072             optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1073             optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData());  // Form data can be removed once the minimum API >= 26.
1074             optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1075             optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1076             optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1077             optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1078             optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1079             optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1080             optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1081             optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1082             optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1083             optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1084
1085             // Initialize the display names for the blocklists with the number of blocked requests.
1086             optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1087             optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1088             optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1089             optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1090             optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1091             optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1092             optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1093             optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1094
1095             // Enable DOM Storage if JavaScript is enabled.
1096             optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1097
1098             // Get the current theme status.
1099             int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1100
1101             // Enable dark WebView if the API is < 33 or if night mode is enabled.
1102             optionsDarkWebViewMenuItem.setEnabled((Build.VERSION.SDK_INT < 33) || (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES));
1103
1104             // Set the checkbox status for dark WebView if the WebView supports it.
1105             if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {  // The device is running API >= 33 and algorithmic darkening is supported.
1106                 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView.getSettings()));
1107             } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {  // The device is running API < 33 and the WebView supports force dark.
1108                 //noinspection deprecation
1109                 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1110             }
1111         }
1112
1113         // Set the cookies menu item checked status.
1114         optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1115
1116         // Enable Clear Cookies if there are any.
1117         optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1118
1119         // 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`.
1120         String privateDataDirectoryString = getApplicationInfo().dataDir;
1121
1122         // Get a count of the number of files in the Local Storage directory.
1123         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1124         int localStorageDirectoryNumberOfFiles = 0;
1125         if (localStorageDirectory.exists()) {
1126             // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1127             localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1128         }
1129
1130         // Get a count of the number of files in the IndexedDB directory.
1131         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1132         int indexedDBDirectoryNumberOfFiles = 0;
1133         if (indexedDBDirectory.exists()) {
1134             // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1135             indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1136         }
1137
1138         // Enable Clear DOM Storage if there is any.
1139         optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1140
1141         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1142         if (Build.VERSION.SDK_INT < 26) {
1143             // Get the WebView database.
1144             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1145
1146             // Enable the clear form data menu item if there is anything to clear.
1147             optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1148         }
1149
1150         // Enable Clear Data if any of the submenu items are enabled.
1151         optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1152
1153         // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1154         optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1155
1156         // Set the proxy title and check the applied proxy.
1157         switch (proxyMode) {
1158             case ProxyHelper.NONE:
1159                 // Set the proxy title.
1160                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1161
1162                 // Check the proxy None radio button.
1163                 optionsProxyNoneMenuItem.setChecked(true);
1164                 break;
1165
1166             case ProxyHelper.TOR:
1167                 // Set the proxy title.
1168                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1169
1170                 // Check the proxy Tor radio button.
1171                 optionsProxyTorMenuItem.setChecked(true);
1172                 break;
1173
1174             case ProxyHelper.I2P:
1175                 // Set the proxy title.
1176                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1177
1178                 // Check the proxy I2P radio button.
1179                 optionsProxyI2pMenuItem.setChecked(true);
1180                 break;
1181
1182             case ProxyHelper.CUSTOM:
1183                 // Set the proxy title.
1184                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1185
1186                 // Check the proxy Custom radio button.
1187                 optionsProxyCustomMenuItem.setChecked(true);
1188                 break;
1189         }
1190
1191         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1192         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1193             // Update the user agent menu item title.
1194             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1195
1196             // Select the Privacy Browser radio box.
1197             optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1198         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1199             // Update the user agent menu item title.
1200             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1201
1202             // Select the WebView Default radio box.
1203             optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1204         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1205             // Update the user agent menu item title.
1206             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1207
1208             // Select the Firefox on Android radio box.
1209             optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1210         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1211             // Update the user agent menu item title.
1212             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1213
1214             // Select the Chrome on Android radio box.
1215             optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1216         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1217             // Update the user agent menu item title.
1218             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1219
1220             // Select the Safari on iOS radio box.
1221             optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1222         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1223             // Update the user agent menu item title.
1224             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1225
1226             // Select the Firefox on Linux radio box.
1227             optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1228         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1229             // Update the user agent menu item title.
1230             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1231
1232             // Select the Chromium on Linux radio box.
1233             optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1234         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1235             // Update the user agent menu item title.
1236             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1237
1238             // Select the Firefox on Windows radio box.
1239             optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1240         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1241             // Update the user agent menu item title.
1242             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1243
1244             // Select the Chrome on Windows radio box.
1245             optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1246         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1247             // Update the user agent menu item title.
1248             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1249
1250             // Select the Edge on Windows radio box.
1251             optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1252         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1253             // Update the user agent menu item title.
1254             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1255
1256             // Select the Internet on Windows radio box.
1257             optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1258         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1259             // Update the user agent menu item title.
1260             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1261
1262             // Select the Safari on macOS radio box.
1263             optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1264         } else {  // Custom user agent.
1265             // Update the user agent menu item title.
1266             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1267
1268             // Select the Custom radio box.
1269             optionsUserAgentCustomMenuItem.setChecked(true);
1270         }
1271
1272         // Set the font size title.
1273         optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1274
1275         // Run all the other default commands.
1276         super.onPrepareOptionsMenu(menu);
1277
1278         // Display the menu.
1279         return true;
1280     }
1281
1282     @Override
1283     public boolean onOptionsItemSelected(MenuItem menuItem) {
1284         // Get a handle for the shared preferences.
1285         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1286
1287         // Get a handle for the cookie manager.
1288         CookieManager cookieManager = CookieManager.getInstance();
1289
1290         // Get the selected menu item ID.
1291         int menuItemId = menuItem.getItemId();
1292
1293         // Run the commands that correlate to the selected menu item.
1294         if (menuItemId == R.id.javascript) {  // JavaScript.
1295             // Toggle the JavaScript status.
1296             currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1297
1298             // Update the privacy icon.
1299             updatePrivacyIcons(true);
1300
1301             // Display a `Snackbar`.
1302             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
1303                 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1304             } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
1305                 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1306             } else {  // Privacy mode.
1307                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1308             }
1309
1310             // Reload the current WebView.
1311             currentWebView.reload();
1312
1313             // Consume the event.
1314             return true;
1315         } else if (menuItemId == R.id.refresh) {  // Refresh.
1316             // Run the command that correlates to the current status of the menu item.
1317             if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
1318                 // Reload the current WebView.
1319                 currentWebView.reload();
1320             } else {  // The stop button was pushed.
1321                 // Stop the loading of the WebView.
1322                 currentWebView.stopLoading();
1323             }
1324
1325             // Consume the event.
1326             return true;
1327         } else if (menuItemId == R.id.bookmarks) {  // Bookmarks.
1328             // Open the bookmarks drawer.
1329             drawerLayout.openDrawer(GravityCompat.END);
1330
1331             // Consume the event.
1332             return true;
1333         } else if (menuItemId == R.id.cookies) {  // Cookies.
1334             // Switch the first-party cookie status.
1335             cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1336
1337             // Store the cookie status.
1338             currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1339
1340             // Update the menu checkbox.
1341             menuItem.setChecked(cookieManager.acceptCookie());
1342
1343             // Update the privacy icon.
1344             updatePrivacyIcons(true);
1345
1346             // Display a snackbar.
1347             if (cookieManager.acceptCookie()) {  // Cookies are enabled.
1348                 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1349             } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1350                 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1351             } else {  // Privacy mode.
1352                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1353             }
1354
1355             // Reload the current WebView.
1356             currentWebView.reload();
1357
1358             // Consume the event.
1359             return true;
1360         } else if (menuItemId == R.id.dom_storage) {  // DOM storage.
1361             // Toggle the status of domStorageEnabled.
1362             currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1363
1364             // Update the menu checkbox.
1365             menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1366
1367             // Update the privacy icon.
1368             updatePrivacyIcons(true);
1369
1370             // Display a snackbar.
1371             if (currentWebView.getSettings().getDomStorageEnabled()) {
1372                 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1373             } else {
1374                 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1375             }
1376
1377             // Reload the current WebView.
1378             currentWebView.reload();
1379
1380             // Consume the event.
1381             return true;
1382         } else if (menuItemId == R.id.save_form_data) {  // Form data.  This can be removed once the minimum API >= 26.
1383             // Switch the status of saveFormDataEnabled.
1384             currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1385
1386             // Update the menu checkbox.
1387             menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1388
1389             // Display a snackbar.
1390             if (currentWebView.getSettings().getSaveFormData()) {
1391                 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1392             } else {
1393                 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1394             }
1395
1396             // Update the privacy icon.
1397             updatePrivacyIcons(true);
1398
1399             // Reload the current WebView.
1400             currentWebView.reload();
1401
1402             // Consume the event.
1403             return true;
1404         } else if (menuItemId == R.id.clear_cookies) {  // Clear cookies.
1405             // Create a snackbar.
1406             Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1407                     .setAction(R.string.undo, v -> {
1408                         // Do nothing because everything will be handled by `onDismissed()` below.
1409                     })
1410                     .addCallback(new Snackbar.Callback() {
1411                         @Override
1412                         public void onDismissed(Snackbar snackbar, int event) {
1413                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1414                                 // Delete the cookies.
1415                                 cookieManager.removeAllCookies(null);
1416                             }
1417                         }
1418                     })
1419                     .show();
1420
1421             // Consume the event.
1422             return true;
1423         } else if (menuItemId == R.id.clear_dom_storage) {  // Clear DOM storage.
1424             // Create a snackbar.
1425             Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1426                     .setAction(R.string.undo, v -> {
1427                         // Do nothing because everything will be handled by `onDismissed()` below.
1428                     })
1429                     .addCallback(new Snackbar.Callback() {
1430                         @Override
1431                         public void onDismissed(Snackbar snackbar, int event) {
1432                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1433                                 // Delete the DOM Storage.
1434                                 WebStorage webStorage = WebStorage.getInstance();
1435                                 webStorage.deleteAllData();
1436
1437                                 // Initialize a handler to manually delete the DOM storage files and directories.
1438                                 Handler deleteDomStorageHandler = new Handler();
1439
1440                                 // Setup a runnable to manually delete the DOM storage files and directories.
1441                                 Runnable deleteDomStorageRunnable = () -> {
1442                                     try {
1443                                         // Get a handle for the runtime.
1444                                         Runtime runtime = Runtime.getRuntime();
1445
1446                                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1447                                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1448                                         String privateDataDirectoryString = getApplicationInfo().dataDir;
1449
1450                                         // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1451                                         Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1452
1453                                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1454                                         Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1455                                         Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1456                                         Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1457                                         Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1458
1459                                         // Wait for the processes to finish.
1460                                         deleteLocalStorageProcess.waitFor();
1461                                         deleteIndexProcess.waitFor();
1462                                         deleteQuotaManagerProcess.waitFor();
1463                                         deleteQuotaManagerJournalProcess.waitFor();
1464                                         deleteDatabasesProcess.waitFor();
1465                                     } catch (Exception exception) {
1466                                         // Do nothing if an error is thrown.
1467                                     }
1468                                 };
1469
1470                                 // Manually delete the DOM storage files after 200 milliseconds.
1471                                 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1472                             }
1473                         }
1474                     })
1475                     .show();
1476
1477             // Consume the event.
1478             return true;
1479         } else if (menuItemId == R.id.clear_form_data) {  // Clear form data.  This can be remove once the minimum API >= 26.
1480             // Create a snackbar.
1481             Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1482                     .setAction(R.string.undo, v -> {
1483                         // Do nothing because everything will be handled by `onDismissed()` below.
1484                     })
1485                     .addCallback(new Snackbar.Callback() {
1486                         @Override
1487                         public void onDismissed(Snackbar snackbar, int event) {
1488                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1489                                 // Get a handle for the webView database.
1490                                 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1491
1492                                 // Delete the form data.
1493                                 webViewDatabase.clearFormData();
1494                             }
1495                         }
1496                     })
1497                     .show();
1498
1499             // Consume the event.
1500             return true;
1501         } else if (menuItemId == R.id.easylist) {  // EasyList.
1502             // Toggle the EasyList status.
1503             currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
1504
1505             // Update the menu checkbox.
1506             menuItem.setChecked(currentWebView.getEasyListEnabled());
1507
1508             // Reload the current WebView.
1509             currentWebView.reload();
1510
1511             // Consume the event.
1512             return true;
1513         } else if (menuItemId == R.id.easyprivacy) {  // EasyPrivacy.
1514             // Toggle the EasyPrivacy status.
1515             currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
1516
1517             // Update the menu checkbox.
1518             menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1519
1520             // Reload the current WebView.
1521             currentWebView.reload();
1522
1523             // Consume the event.
1524             return true;
1525         } else if (menuItemId == R.id.fanboys_annoyance_list) {  // Fanboy's Annoyance List.
1526             // Toggle Fanboy's Annoyance List status.
1527             currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1528
1529             // Update the menu checkbox.
1530             menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1531
1532             // Update the status of Fanboy's Social Blocking List.
1533             optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1534
1535             // Reload the current WebView.
1536             currentWebView.reload();
1537
1538             // Consume the event.
1539             return true;
1540         } else if (menuItemId == R.id.fanboys_social_blocking_list) {  // Fanboy's Social Blocking List.
1541             // Toggle Fanboy's Social Blocking List status.
1542             currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
1543
1544             // Update the menu checkbox.
1545             menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1546
1547             // Reload the current WebView.
1548             currentWebView.reload();
1549
1550             // Consume the event.
1551             return true;
1552         } else if (menuItemId == R.id.ultralist) {  // UltraList.
1553             // Toggle the UltraList status.
1554             currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
1555
1556             // Update the menu checkbox.
1557             menuItem.setChecked(currentWebView.getUltraListEnabled());
1558
1559             // Reload the current WebView.
1560             currentWebView.reload();
1561
1562             // Consume the event.
1563             return true;
1564         } else if (menuItemId == R.id.ultraprivacy) {  // UltraPrivacy.
1565             // Toggle the UltraPrivacy status.
1566             currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
1567
1568             // Update the menu checkbox.
1569             menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1570
1571             // Reload the current WebView.
1572             currentWebView.reload();
1573
1574             // Consume the event.
1575             return true;
1576         } else if (menuItemId == R.id.block_all_third_party_requests) {  // Block all third-party requests.
1577             //Toggle the third-party requests blocker status.
1578             currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
1579
1580             // Update the menu checkbox.
1581             menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1582
1583             // Reload the current WebView.
1584             currentWebView.reload();
1585
1586             // Consume the event.
1587             return true;
1588         } else if (menuItemId == R.id.proxy_none) {  // Proxy - None.
1589             // Update the proxy mode.
1590             proxyMode = ProxyHelper.NONE;
1591
1592             // Apply the proxy mode.
1593             applyProxy(true);
1594
1595             // Consume the event.
1596             return true;
1597         } else if (menuItemId == R.id.proxy_tor) {  // Proxy - Tor.
1598             // Update the proxy mode.
1599             proxyMode = ProxyHelper.TOR;
1600
1601             // Apply the proxy mode.
1602             applyProxy(true);
1603
1604             // Consume the event.
1605             return true;
1606         } else if (menuItemId == R.id.proxy_i2p) {  // Proxy - I2P.
1607             // Update the proxy mode.
1608             proxyMode = ProxyHelper.I2P;
1609
1610             // Apply the proxy mode.
1611             applyProxy(true);
1612
1613             // Consume the event.
1614             return true;
1615         } else if (menuItemId == R.id.proxy_custom) {  // Proxy - Custom.
1616             // Update the proxy mode.
1617             proxyMode = ProxyHelper.CUSTOM;
1618
1619             // Apply the proxy mode.
1620             applyProxy(true);
1621
1622             // Consume the event.
1623             return true;
1624         } else if (menuItemId == R.id.user_agent_privacy_browser) {  // User Agent - Privacy Browser.
1625             // Update the user agent.
1626             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1627
1628             // Reload the current WebView.
1629             currentWebView.reload();
1630
1631             // Consume the event.
1632             return true;
1633         } else if (menuItemId == R.id.user_agent_webview_default) {  // User Agent - WebView Default.
1634             // Update the user agent.
1635             currentWebView.getSettings().setUserAgentString("");
1636
1637             // Reload the current WebView.
1638             currentWebView.reload();
1639
1640             // Consume the event.
1641             return true;
1642         } else if (menuItemId == R.id.user_agent_firefox_on_android) {  // User Agent - Firefox on Android.
1643             // Update the user agent.
1644             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1645
1646             // Reload the current WebView.
1647             currentWebView.reload();
1648
1649             // Consume the event.
1650             return true;
1651         } else if (menuItemId == R.id.user_agent_chrome_on_android) {  // User Agent - Chrome on Android.
1652             // Update the user agent.
1653             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1654
1655             // Reload the current WebView.
1656             currentWebView.reload();
1657
1658             // Consume the event.
1659             return true;
1660         } else if (menuItemId == R.id.user_agent_safari_on_ios) {  // User Agent - Safari on iOS.
1661             // Update the user agent.
1662             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1663
1664             // Reload the current WebView.
1665             currentWebView.reload();
1666
1667             // Consume the event.
1668             return true;
1669         } else if (menuItemId == R.id.user_agent_firefox_on_linux) {  // User Agent - Firefox on Linux.
1670             // Update the user agent.
1671             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1672
1673             // Reload the current WebView.
1674             currentWebView.reload();
1675
1676             // Consume the event.
1677             return true;
1678         } else if (menuItemId == R.id.user_agent_chromium_on_linux) {  // User Agent - Chromium on Linux.
1679             // Update the user agent.
1680             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1681
1682             // Reload the current WebView.
1683             currentWebView.reload();
1684
1685             // Consume the event.
1686             return true;
1687         } else if (menuItemId == R.id.user_agent_firefox_on_windows) {  // User Agent - Firefox on Windows.
1688             // Update the user agent.
1689             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1690
1691             // Reload the current WebView.
1692             currentWebView.reload();
1693
1694             // Consume the event.
1695             return true;
1696         } else if (menuItemId == R.id.user_agent_chrome_on_windows) {  // User Agent - Chrome on Windows.
1697             // Update the user agent.
1698             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1699
1700             // Reload the current WebView.
1701             currentWebView.reload();
1702
1703             // Consume the event.
1704             return true;
1705         } else if (menuItemId == R.id.user_agent_edge_on_windows) {  // User Agent - Edge on Windows.
1706             // Update the user agent.
1707             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1708
1709             // Reload the current WebView.
1710             currentWebView.reload();
1711
1712             // Consume the event.
1713             return true;
1714         } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) {  // User Agent - Internet Explorer on Windows.
1715             // Update the user agent.
1716             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1717
1718             // Reload the current WebView.
1719             currentWebView.reload();
1720
1721             // Consume the event.
1722             return true;
1723         } else if (menuItemId == R.id.user_agent_safari_on_macos) {  // User Agent - Safari on macOS.
1724             // Update the user agent.
1725             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1726
1727             // Reload the current WebView.
1728             currentWebView.reload();
1729
1730             // Consume the event.
1731             return true;
1732         } else if (menuItemId == R.id.user_agent_custom) {  // User Agent - Custom.
1733             // Update the user agent.
1734             currentWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
1735
1736             // Reload the current WebView.
1737             currentWebView.reload();
1738
1739             // Consume the event.
1740             return true;
1741         } else if (menuItemId == R.id.font_size) {  // Font size.
1742             // Instantiate the font size dialog.
1743             DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1744
1745             // Show the font size dialog.
1746             fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1747
1748             // Consume the event.
1749             return true;
1750         } else if (menuItemId == R.id.swipe_to_refresh) {  // Swipe to refresh.
1751             // Toggle the stored status of swipe to refresh.
1752             currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1753
1754             // Update the swipe refresh layout.
1755             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1756                 // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
1757                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1758             } else {  // Swipe to refresh is disabled.
1759                 // Disable the swipe refresh layout.
1760                 swipeRefreshLayout.setEnabled(false);
1761             }
1762
1763             // Consume the event.
1764             return true;
1765         } else if (menuItemId == R.id.wide_viewport) {  // Wide viewport.
1766             // Toggle the viewport.
1767             currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1768
1769             // Consume the event.
1770             return true;
1771         } else if (menuItemId == R.id.display_images) {  // Display images.
1772             // Toggle the displaying of images.
1773             if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1774                 // Disable loading of images.
1775                 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1776
1777                 // Reload the website to remove existing images.
1778                 currentWebView.reload();
1779             } else {  // Images are not currently loaded automatically.
1780                 // Enable loading of images.  Missing images will be loaded without the need for a reload.
1781                 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1782             }
1783
1784             // Consume the event.
1785             return true;
1786         } else if (menuItemId == R.id.dark_webview) {  // Dark WebView.
1787             // Check to see if dark WebView is supported by this WebView.
1788             if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {  // The device is running API >= 33 and algorithmic darkening is supported.
1789                 // Toggle algorithmic darkening.
1790                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView.getSettings(), !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView.getSettings()));
1791             } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {  // The device is running API < 33 and the WebView supports force dark.
1792                 // Toggle the dark WebView setting.
1793                 //noinspection deprecation
1794                 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) {  // Dark WebView is currently enabled.
1795                     // Turn off dark WebView.
1796                     //noinspection deprecation
1797                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1798                 } else {  // Dark WebView is currently disabled.
1799                     // Turn on dark WebView.
1800                     //noinspection deprecation
1801                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1802                 }
1803             }
1804
1805             // Consume the event.
1806             return true;
1807         } else if (menuItemId == R.id.find_on_page) {  // Find on page.
1808             // Get a handle for the views.
1809             Toolbar toolbar = findViewById(R.id.toolbar);
1810             LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1811             EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1812
1813             // Set the minimum height of the find on page linear layout to match the toolbar.
1814             findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1815
1816             // Hide the toolbar.
1817             toolbar.setVisibility(View.GONE);
1818
1819             // Show the find on page linear layout.
1820             findOnPageLinearLayout.setVisibility(View.VISIBLE);
1821
1822             // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1823             // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1824             findOnPageEditText.postDelayed(() -> {
1825                 // Set the focus on the find on page edit text.
1826                 findOnPageEditText.requestFocus();
1827
1828                 // Get a handle for the input method manager.
1829                 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1830
1831                 // Remove the lint warning below that the input method manager might be null.
1832                 assert inputMethodManager != null;
1833
1834                 // Display the keyboard.  `0` sets no input flags.
1835                 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1836             }, 200);
1837
1838             // Consume the event.
1839             return true;
1840         } else if (menuItemId == R.id.print) {  // Print.
1841             // Get a print manager instance.
1842             PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1843
1844             // Remove the lint error below that print manager might be null.
1845             assert printManager != null;
1846
1847             // Create a print document adapter from the current WebView.
1848             PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
1849
1850             // Print the document.
1851             printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1852
1853             // Consume the event.
1854             return true;
1855         } else if (menuItemId == R.id.save_url) {  // Save URL.
1856             // Check the download preference.
1857             if (downloadWithExternalApp) {  // Download with an external app.
1858                 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1859             } else {  // Handle the download inside of Privacy Browser.
1860                 // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
1861                 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1862                         currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1863             }
1864
1865             // Consume the event.
1866             return true;
1867         } else if (menuItemId == R.id.save_archive) {
1868             // Open the file picker with a default file name built from the current domain name.
1869             saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1870
1871             // Consume the event.
1872             return true;
1873         } else if (menuItemId == R.id.save_image) {  // Save image.
1874             // Open the file picker with a default file name built from the current domain name.
1875             saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1876
1877             // Consume the event.
1878             return true;
1879         } else if (menuItemId == R.id.add_to_homescreen) {  // Add to homescreen.
1880             // Instantiate the create home screen shortcut dialog.
1881             DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1882                     currentWebView.getFavoriteOrDefaultIcon());
1883
1884             // Show the create home screen shortcut dialog.
1885             createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1886
1887             // Consume the event.
1888             return true;
1889         } else if (menuItemId == R.id.view_source) {  // View source.
1890             // Create an intent to launch the view source activity.
1891             Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1892
1893             // Add the variables to the intent.
1894             viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1895             viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1896
1897             // Make it so.
1898             startActivity(viewSourceIntent);
1899
1900             // Consume the event.
1901             return true;
1902         } else if (menuItemId == R.id.share_message) {  // Share a message.
1903             // Prepare the share string.
1904             String shareString = currentWebView.getTitle() + " â€“ " + currentWebView.getUrl();
1905
1906             // Create the share intent.
1907             Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
1908
1909             // Add the share string to the intent.
1910             shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1911
1912             // Set the MIME type.
1913             shareMessageIntent.setType("text/plain");
1914
1915             // Set the intent to open in a new task.
1916             shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1917
1918             // Make it so.
1919             startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
1920
1921             // Consume the event.
1922             return true;
1923         } else if (menuItemId == R.id.share_url) {  // Share URL.
1924             // Create the share intent.
1925             Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
1926
1927             // Add the URL to the intent.
1928             shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
1929
1930             // Add the title to the intent.
1931             shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
1932
1933             // Set the MIME type.
1934             shareUrlIntent.setType("text/plain");
1935
1936             // Set the intent to open in a new task.
1937             shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1938
1939             //Make it so.
1940             startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
1941
1942             // Consume the event.
1943             return true;
1944         } else if (menuItemId == R.id.open_with_app) {  // Open with app.
1945             // Open the URL with an outside app.
1946             openWithApp(currentWebView.getUrl());
1947
1948             // Consume the event.
1949             return true;
1950         } else if (menuItemId == R.id.open_with_browser) {  // Open with browser.
1951             // Open the URL with an outside browser.
1952             openWithBrowser(currentWebView.getUrl());
1953
1954             // Consume the event.
1955             return true;
1956         } else if (menuItemId == R.id.add_or_edit_domain) {  // Add or edit domain.
1957             // Reapply the domain settings on returning to `MainWebViewActivity`.
1958             reapplyDomainSettingsOnRestart = true;
1959
1960             // Check if domain settings currently exist.
1961             if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1962                 // Create an intent to launch the domains activity.
1963                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1964
1965                 // Add the extra information to the intent.
1966                 domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, currentWebView.getDomainSettingsDatabaseId());
1967                 domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
1968                 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
1969                 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
1970
1971                 // Get the current certificate.
1972                 SslCertificate sslCertificate = currentWebView.getCertificate();
1973
1974                 // Check to see if the SSL certificate is populated.
1975                 if (sslCertificate != null) {
1976                     // Extract the certificate to strings.
1977                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
1978                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
1979                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
1980                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
1981                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
1982                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
1983                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1984                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1985
1986                     // Add the certificate to the intent.
1987                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
1988                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
1989                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
1990                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
1991                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
1992                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
1993                     domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
1994                     domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
1995                 }
1996
1997                 // Make it so.
1998                 startActivity(domainsIntent);
1999             } else {  // Add a new domain.
2000                 // Get the current URI.
2001                 Uri currentUri = Uri.parse(currentWebView.getUrl());
2002
2003                 // Get the current domain from the URI.
2004                 String currentDomain = currentUri.getHost();
2005
2006                 // Set an empty domain if it is null.
2007                 if (currentDomain == null)
2008                     currentDomain = "";
2009
2010                 // Create the domain and store the database ID.
2011                 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2012
2013                 // Create an intent to launch the domains activity.
2014                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2015
2016                 // Add the extra information to the intent.
2017                 domainsIntent.putExtra(DomainsActivity.LOAD_DOMAIN, newDomainDatabaseId);
2018                 domainsIntent.putExtra(DomainsActivity.CLOSE_ON_BACK, true);
2019                 domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
2020                 domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
2021
2022                 // Get the current certificate.
2023                 SslCertificate sslCertificate = currentWebView.getCertificate();
2024
2025                 // Check to see if the SSL certificate is populated.
2026                 if (sslCertificate != null) {
2027                     // Extract the certificate to strings.
2028                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
2029                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
2030                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
2031                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
2032                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
2033                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
2034                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2035                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2036
2037                     // Add the certificate to the intent.
2038                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_CNAME, issuedToCName);
2039                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_ONAME, issuedToOName);
2040                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_TO_UNAME, issuedToUName);
2041                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_CNAME, issuedByCName);
2042                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_ONAME, issuedByOName);
2043                     domainsIntent.putExtra(DomainsActivity.SSL_ISSUED_BY_UNAME, issuedByUName);
2044                     domainsIntent.putExtra(DomainsActivity.SSL_START_DATE, startDateLong);
2045                     domainsIntent.putExtra(DomainsActivity.SSL_END_DATE, endDateLong);
2046                 }
2047
2048                 // Make it so.
2049                 startActivity(domainsIntent);
2050             }
2051
2052             // Consume the event.
2053             return true;
2054         } else {  // There is no match with the options menu.  Pass the event up to the parent method.
2055             // Don't consume the event.
2056             return super.onOptionsItemSelected(menuItem);
2057         }
2058     }
2059
2060     // removeAllCookies is deprecated, but it is required for API < 21.
2061     @Override
2062     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2063         // Get a handle for the shared preferences.
2064         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2065
2066         // Get the menu item ID.
2067         int menuItemId = menuItem.getItemId();
2068
2069         // Run the commands that correspond to the selected menu item.
2070         if (menuItemId == R.id.clear_and_exit) {  // Clear and exit.
2071             // Clear and exit Privacy Browser.
2072             clearAndExit();
2073         } else if (menuItemId == R.id.home) {  // Home.
2074             // Load the homepage.
2075             loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2076         } else if (menuItemId == R.id.back) {  // Back.
2077             // Check if the WebView can go back.
2078             if (currentWebView.canGoBack()) {
2079                 // Get the current web back forward list.
2080                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2081
2082                 // Get the previous entry URL.
2083                 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2084
2085                 // Apply the domain settings.
2086                 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2087
2088                 // Load the previous website in the history.
2089                 currentWebView.goBack();
2090             }
2091         } else if (menuItemId == R.id.forward) {  // Forward.
2092             // Check if the WebView can go forward.
2093             if (currentWebView.canGoForward()) {
2094                 // Get the current web back forward list.
2095                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2096
2097                 // Get the next entry URL.
2098                 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2099
2100                 // Apply the domain settings.
2101                 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2102
2103                 // Load the next website in the history.
2104                 currentWebView.goForward();
2105             }
2106         } else if (menuItemId == R.id.history) {  // History.
2107             // Instantiate the URL history dialog.
2108             DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2109
2110             // Show the URL history dialog.
2111             urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2112         } else if (menuItemId == R.id.open) {  // Open.
2113             // Instantiate the open file dialog.
2114             DialogFragment openDialogFragment = new OpenDialog();
2115
2116             // Show the open file dialog.
2117             openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2118         } else if (menuItemId == R.id.requests) {  // Requests.
2119             // Populate the resource requests.
2120             RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2121
2122             // Create an intent to launch the Requests activity.
2123             Intent requestsIntent = new Intent(this, RequestsActivity.class);
2124
2125             // Add the block third-party requests status to the intent.
2126             requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
2127
2128             // Make it so.
2129             startActivity(requestsIntent);
2130         } else if (menuItemId == R.id.downloads) {  // Downloads.
2131             // Try the default system download manager.
2132             try {
2133                 // Launch the default system Download Manager.
2134                 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2135
2136                 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2137                 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2138
2139                 // Make it so.
2140                 startActivity(defaultDownloadManagerIntent);
2141             } catch (Exception defaultDownloadManagerException) {
2142                 // Try a generic file manager.
2143                 try {
2144                     // Create a generic file manager intent.
2145                     Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2146
2147                     // Open the download directory.
2148                     genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2149
2150                     // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2151                     genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2152
2153                     // Make it so.
2154                     startActivity(genericFileManagerIntent);
2155                 } catch (Exception genericFileManagerException) {
2156                     // Try an alternate file manager.
2157                     try {
2158                         // Create an alternate file manager intent.
2159                         Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2160
2161                         // Open the download directory.
2162                         alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2163
2164                         // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2165                         alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2166
2167                         // Open the alternate file manager.
2168                         startActivity(alternateFileManagerIntent);
2169                     } catch (Exception alternateFileManagerException) {
2170                         // Display a snackbar.
2171                         Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2172                     }
2173                 }
2174             }
2175         } else if (menuItemId == R.id.domains) {  // Domains.
2176             // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2177             reapplyDomainSettingsOnRestart = true;
2178
2179             // Launch the domains activity.
2180             Intent domainsIntent = new Intent(this, DomainsActivity.class);
2181
2182             // Add the extra information to the intent.
2183             domainsIntent.putExtra(DomainsActivity.CURRENT_URL, currentWebView.getUrl());
2184             domainsIntent.putExtra(DomainsActivity.CURRENT_IP_ADDRESSES, currentWebView.getCurrentIpAddresses());
2185
2186             // Get the current certificate.
2187             SslCertificate sslCertificate = currentWebView.getCertificate();
2188
2189             // Check to see if the SSL certificate is populated.
2190             if (sslCertificate != null) {
2191                 // Extract the certificate to strings.
2192                 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2193                 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2194                 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2195                 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2196                 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2197                 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2198                 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2199                 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2200
2201                 // Add the certificate to the intent.
2202                 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2203                 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2204                 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2205                 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2206                 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2207                 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2208                 domainsIntent.putExtra("ssl_start_date", startDateLong);
2209                 domainsIntent.putExtra("ssl_end_date", endDateLong);
2210             }
2211
2212             // Make it so.
2213             startActivity(domainsIntent);
2214         } else if (menuItemId == R.id.settings) {  // Settings.
2215             // Set the flag to reapply app settings on restart when returning from Settings.
2216             reapplyAppSettingsOnRestart = true;
2217
2218             // Set the flag to reapply the domain settings on restart when returning from Settings.
2219             reapplyDomainSettingsOnRestart = true;
2220
2221             // Launch the settings activity.
2222             Intent settingsIntent = new Intent(this, SettingsActivity.class);
2223             startActivity(settingsIntent);
2224         } else if (menuItemId == R.id.import_export) { // Import/Export.
2225             // Create an intent to launch the import/export activity.
2226             Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2227
2228             // Make it so.
2229             startActivity(importExportIntent);
2230         } else if (menuItemId == R.id.logcat) {  // Logcat.
2231             // Create an intent to launch the logcat activity.
2232             Intent logcatIntent = new Intent(this, LogcatActivity.class);
2233
2234             // Make it so.
2235             startActivity(logcatIntent);
2236         } else if (menuItemId == R.id.webview_devtools) {  // WebView Dev.
2237             // Create a WebView DevTools intent.
2238             Intent webViewDevToolsIntent = new Intent("com.android.webview.SHOW_DEV_UI");
2239
2240             // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2241             webViewDevToolsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2242
2243             // Make it so.
2244             startActivity(webViewDevToolsIntent);
2245         } else if (menuItemId == R.id.guide) {  // Guide.
2246             // Create an intent to launch the guide activity.
2247             Intent guideIntent = new Intent(this, GuideActivity.class);
2248
2249             // Make it so.
2250             startActivity(guideIntent);
2251         } else if (menuItemId == R.id.about) {  // About
2252             // Create an intent to launch the about activity.
2253             Intent aboutIntent = new Intent(this, AboutActivity.class);
2254
2255             // Create a string array for the blocklist versions.
2256             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],
2257                     ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2258
2259             // Add the blocklist versions to the intent.
2260             aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2261
2262             // Make it so.
2263             startActivity(aboutIntent);
2264         }
2265
2266         // Close the navigation drawer.
2267         drawerLayout.closeDrawer(GravityCompat.START);
2268         return true;
2269     }
2270
2271     @Override
2272     public void onPostCreate(Bundle savedInstanceState) {
2273         // Run the default commands.
2274         super.onPostCreate(savedInstanceState);
2275
2276         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2277         actionBarDrawerToggle.syncState();
2278     }
2279
2280     @Override
2281     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2282         // Get the hit test result.
2283         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2284
2285         // Define the URL strings.
2286         final String imageUrl;
2287         final String linkUrl;
2288
2289         // Get handles for the system managers.
2290         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2291
2292         // Remove the lint errors below that the clipboard manager might be null.
2293         assert clipboardManager != null;
2294
2295         // Process the link according to the type.
2296         switch (hitTestResult.getType()) {
2297             // `SRC_ANCHOR_TYPE` is a link.
2298             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2299                 // Get the target URL.
2300                 linkUrl = hitTestResult.getExtra();
2301
2302                 // Set the target URL as the title of the `ContextMenu`.
2303                 menu.setHeaderTitle(linkUrl);
2304
2305                 // Add an Open in New Tab entry.
2306                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2307                     // Load the link URL in a new tab and move to it.
2308                     addNewTab(linkUrl, true);
2309
2310                     // Consume the event.
2311                     return true;
2312                 });
2313
2314                 // Add an Open in Background entry.
2315                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2316                     // Load the link URL in a new tab but do not move to it.
2317                     addNewTab(linkUrl, false);
2318
2319                     // Consume the event.
2320                     return true;
2321                 });
2322
2323                 // Add an Open with App entry.
2324                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2325                     openWithApp(linkUrl);
2326
2327                     // Consume the event.
2328                     return true;
2329                 });
2330
2331                 // Add an Open with Browser entry.
2332                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2333                     openWithBrowser(linkUrl);
2334
2335                     // Consume the event.
2336                     return true;
2337                 });
2338
2339                 // Add a Copy URL entry.
2340                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2341                     // Save the link URL in a `ClipData`.
2342                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2343
2344                     // Set the `ClipData` as the clipboard's primary clip.
2345                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2346
2347                     // Consume the event.
2348                     return true;
2349                 });
2350
2351                 // Add a Save URL entry.
2352                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2353                     // Check the download preference.
2354                     if (downloadWithExternalApp) {  // Download with an external app.
2355                         downloadUrlWithExternalApp(linkUrl);
2356                     } else {  // Handle the download inside of Privacy Browser.
2357                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2358                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2359                                 currentWebView.getAcceptCookies()).execute(linkUrl);
2360                     }
2361
2362                     // Consume the event.
2363                     return true;
2364                 });
2365
2366                 // Add an empty Cancel entry, which by default closes the context menu.
2367                 menu.add(R.string.cancel);
2368                 break;
2369
2370             // `IMAGE_TYPE` is an image.
2371             case WebView.HitTestResult.IMAGE_TYPE:
2372                 // Get the image URL.
2373                 imageUrl = hitTestResult.getExtra();
2374
2375                 // Remove the incorrect lint warning below that the image URL might be null.
2376                 assert imageUrl != null;
2377
2378                 // Set the context menu title.
2379                 if (imageUrl.startsWith("data:")) {  // The image data is contained in within the URL, making it exceedingly long.
2380                     // Truncate the image URL before making it the title.
2381                     menu.setHeaderTitle(imageUrl.substring(0, 100));
2382                 } else {  // The image URL does not contain the full image data.
2383                     // Set the image URL as the title of the context menu.
2384                     menu.setHeaderTitle(imageUrl);
2385                 }
2386
2387                 // Add an Open in New Tab entry.
2388                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2389                     // Load the image in a new tab.
2390                     addNewTab(imageUrl, true);
2391
2392                     // Consume the event.
2393                     return true;
2394                 });
2395
2396                 // Add an Open with App entry.
2397                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2398                     // Open the image URL with an external app.
2399                     openWithApp(imageUrl);
2400
2401                     // Consume the event.
2402                     return true;
2403                 });
2404
2405                 // Add an Open with Browser entry.
2406                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2407                     // Open the image URL with an external browser.
2408                     openWithBrowser(imageUrl);
2409
2410                     // Consume the event.
2411                     return true;
2412                 });
2413
2414                 // Add a View Image entry.
2415                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2416                     // Load the image in the current tab.
2417                     loadUrl(currentWebView, imageUrl);
2418
2419                     // Consume the event.
2420                     return true;
2421                 });
2422
2423                 // Add a Save Image entry.
2424                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2425                     // Check the download preference.
2426                     if (downloadWithExternalApp) {  // Download with an external app.
2427                         downloadUrlWithExternalApp(imageUrl);
2428                     } else {  // Handle the download inside of Privacy Browser.
2429                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2430                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2431                                 currentWebView.getAcceptCookies()).execute(imageUrl);
2432                     }
2433
2434                     // Consume the event.
2435                     return true;
2436                 });
2437
2438                 // Add a Copy URL entry.
2439                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2440                     // Save the image URL in a clip data.
2441                     ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2442
2443                     // Set the clip data as the clipboard's primary clip.
2444                     clipboardManager.setPrimaryClip(imageTypeClipData);
2445
2446                     // Consume the event.
2447                     return true;
2448                 });
2449
2450                 // Add an empty Cancel entry, which by default closes the context menu.
2451                 menu.add(R.string.cancel);
2452                 break;
2453
2454             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2455             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2456                 // Get the image URL.
2457                 imageUrl = hitTestResult.getExtra();
2458
2459                 // Instantiate a handler.
2460                 Handler handler = new Handler();
2461
2462                 // Get a message from the handler.
2463                 Message message = handler.obtainMessage();
2464
2465                 // Request the image details from the last touched node be returned in the message.
2466                 currentWebView.requestFocusNodeHref(message);
2467
2468                 // Get the link URL from the message data.
2469                 linkUrl = message.getData().getString("url");
2470
2471                 // Set the link URL as the title of the context menu.
2472                 menu.setHeaderTitle(linkUrl);
2473
2474                 // Add an Open in New Tab entry.
2475                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2476                     // Load the link URL in a new tab and move to it.
2477                     addNewTab(linkUrl, true);
2478
2479                     // Consume the event.
2480                     return true;
2481                 });
2482
2483                 // Add an Open in Background entry.
2484                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2485                     // Lod the link URL in a new tab but do not move to it.
2486                     addNewTab(linkUrl, false);
2487
2488                     // Consume the event.
2489                     return true;
2490                 });
2491
2492                 // Add an Open Image in New Tab entry.
2493                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2494                     // Load the image in a new tab and move to it.
2495                     addNewTab(imageUrl, true);
2496
2497                     // Consume the event.
2498                     return true;
2499                 });
2500
2501                 // Add an Open with App entry.
2502                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2503                     // Open the link URL with an external app.
2504                     openWithApp(linkUrl);
2505
2506                     // Consume the event.
2507                     return true;
2508                 });
2509
2510                 // Add an Open with Browser entry.
2511                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2512                     // Open the link URL with an external browser.
2513                     openWithBrowser(linkUrl);
2514
2515                     // Consume the event.
2516                     return true;
2517                 });
2518
2519                 // Add a View Image entry.
2520                 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2521                    // View the image in the current tab.
2522                    loadUrl(currentWebView, imageUrl);
2523
2524                    // Consume the event.
2525                    return true;
2526                 });
2527
2528                 // Add a Save Image entry.
2529                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2530                     // Check the download preference.
2531                     if (downloadWithExternalApp) {  // Download with an external app.
2532                         downloadUrlWithExternalApp(imageUrl);
2533                     } else {  // Handle the download inside of Privacy Browser.
2534                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2535                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2536                                 currentWebView.getAcceptCookies()).execute(imageUrl);
2537                     }
2538
2539                     // Consume the event.
2540                     return true;
2541                 });
2542
2543                 // Add a Copy URL entry.
2544                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2545                     // Save the link URL in a clip data.
2546                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2547
2548                     // Set the clip data as the clipboard's primary clip.
2549                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2550
2551                     // Consume the event.
2552                     return true;
2553                 });
2554
2555                 // Add a Save URL entry.
2556                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2557                     // Check the download preference.
2558                     if (downloadWithExternalApp) {  // Download with an external app.
2559                         downloadUrlWithExternalApp(linkUrl);
2560                     } else {  // Handle the download inside of Privacy Browser.
2561                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2562                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2563                                 currentWebView.getAcceptCookies()).execute(linkUrl);
2564                     }
2565
2566                     // Consume the event.
2567                     return true;
2568                 });
2569
2570                 // Add an empty Cancel entry, which by default closes the context menu.
2571                 menu.add(R.string.cancel);
2572                 break;
2573
2574             case WebView.HitTestResult.EMAIL_TYPE:
2575                 // Get the target URL.
2576                 linkUrl = hitTestResult.getExtra();
2577
2578                 // Set the target URL as the title of the `ContextMenu`.
2579                 menu.setHeaderTitle(linkUrl);
2580
2581                 // Add a Write Email entry.
2582                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2583                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2584                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2585
2586                     // Parse the url and set it as the data for the `Intent`.
2587                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2588
2589                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2590                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2591
2592                     try {
2593                         // Make it so.
2594                         startActivity(emailIntent);
2595                     } catch (ActivityNotFoundException exception) {
2596                         // Display a snackbar.
2597                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
2598                     }
2599
2600                     // Consume the event.
2601                     return true;
2602                 });
2603
2604                 // Add a Copy Email Address entry.
2605                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2606                     // Save the email address in a `ClipData`.
2607                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2608
2609                     // Set the `ClipData` as the clipboard's primary clip.
2610                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2611
2612                     // Consume the event.
2613                     return true;
2614                 });
2615
2616                 // Add an empty Cancel entry, which by default closes the context menu.
2617                 menu.add(R.string.cancel);
2618                 break;
2619         }
2620     }
2621
2622     @Override
2623     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2624         // Get a handle for the bookmarks list view.
2625         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2626
2627         // Get the dialog.
2628         Dialog dialog = dialogFragment.getDialog();
2629
2630         // Remove the incorrect lint warning below that the dialog might be null.
2631         assert dialog != null;
2632
2633         // Get the views from the dialog fragment.
2634         EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2635         EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2636
2637         // Extract the strings from the edit texts.
2638         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2639         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2640
2641         // Create a favorite icon byte array output stream.
2642         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2643
2644         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2645         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2646
2647         // Convert the favorite icon byte array stream to a byte array.
2648         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2649
2650         // Display the new bookmark below the current items in the (0 indexed) list.
2651         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2652
2653         // Create the bookmark.
2654         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2655
2656         // Update the bookmarks cursor with the current contents of this folder.
2657         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2658
2659         // Update the list view.
2660         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2661
2662         // Scroll to the new bookmark.
2663         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2664     }
2665
2666     @Override
2667     public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2668         // Get a handle for the bookmarks list view.
2669         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2670
2671         // Get the dialog.
2672         Dialog dialog = dialogFragment.getDialog();
2673
2674         // Remove the incorrect lint warning below that the dialog might be null.
2675         assert dialog != null;
2676
2677         // Get handles for the views in the dialog fragment.
2678         EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2679         RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2680         ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2681
2682         // Get new folder name string.
2683         String folderNameString = folderNameEditText.getText().toString();
2684
2685         // Create a folder icon bitmap.
2686         Bitmap folderIconBitmap;
2687
2688         // Set the folder icon bitmap according to the dialog.
2689         if (defaultIconRadioButton.isChecked()) {  // Use the default folder icon.
2690             // Get the default folder icon drawable.
2691             Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2692
2693             // Convert the folder icon drawable to a bitmap drawable.
2694             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2695
2696             // Convert the folder icon bitmap drawable to a bitmap.
2697             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2698         } else {  // Use the WebView favorite icon.
2699             // Copy the favorite icon bitmap to the folder icon bitmap.
2700             folderIconBitmap = favoriteIconBitmap;
2701         }
2702
2703         // Create a folder icon byte array output stream.
2704         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2705
2706         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2707         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2708
2709         // Convert the folder icon byte array stream to a byte array.
2710         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2711
2712         // Move all the bookmarks down one in the display order.
2713         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2714             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2715             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2716         }
2717
2718         // Create the folder, which will be placed at the top of the `ListView`.
2719         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2720
2721         // Update the bookmarks cursor with the current contents of this folder.
2722         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2723
2724         // Update the `ListView`.
2725         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2726
2727         // Scroll to the new folder.
2728         bookmarksListView.setSelection(0);
2729     }
2730
2731     @Override
2732     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2733         // Remove the incorrect lint warning below that the dialog fragment might be null.
2734         assert dialogFragment != null;
2735
2736         // Get the dialog.
2737         Dialog dialog = dialogFragment.getDialog();
2738
2739         // Remove the incorrect lint warning below that the dialog might be null.
2740         assert dialog != null;
2741
2742         // Get handles for the views from the dialog.
2743         RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2744         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2745         ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2746         EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2747
2748         // Get the new folder name.
2749         String newFolderNameString = editFolderNameEditText.getText().toString();
2750
2751         // Check if the favorite icon has changed.
2752         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
2753             // Update the name in the database.
2754             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2755         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
2756             // Create the new folder icon Bitmap.
2757             Bitmap folderIconBitmap;
2758
2759             // Populate the new folder icon bitmap.
2760             if (defaultFolderIconRadioButton.isChecked()) {
2761                 // Get the default folder icon drawable.
2762                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2763
2764                 // Convert the folder icon drawable to a bitmap drawable.
2765                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2766
2767                 // Convert the folder icon bitmap drawable to a bitmap.
2768                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2769             } else {  // Use the `WebView` favorite icon.
2770                 // Copy the favorite icon bitmap to the folder icon bitmap.
2771                 folderIconBitmap = favoriteIconBitmap;
2772             }
2773
2774             // Create a folder icon byte array output stream.
2775             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2776
2777             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2778             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2779
2780             // Convert the folder icon byte array stream to a byte array.
2781             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2782
2783             // Update the folder icon in the database.
2784             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2785         } else {  // The folder icon and the name have changed.
2786             // Get the new folder icon bitmap.
2787             Bitmap folderIconBitmap;
2788             if (defaultFolderIconRadioButton.isChecked()) {
2789                 // Get the default folder icon drawable.
2790                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2791
2792                 // Convert the folder icon drawable to a bitmap drawable.
2793                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2794
2795                 // Convert the folder icon bitmap drawable to a bitmap.
2796                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2797             } else {  // Use the `WebView` favorite icon.
2798                 // Copy the favorite icon bitmap to the folder icon bitmap.
2799                 folderIconBitmap = favoriteIconBitmap;
2800             }
2801
2802             // Create a folder icon byte array output stream.
2803             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2804
2805             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2806             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2807
2808             // Convert the folder icon byte array stream to a byte array.
2809             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2810
2811             // Update the folder name and icon in the database.
2812             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2813         }
2814
2815         // Update the bookmarks cursor with the current contents of this folder.
2816         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2817
2818         // Update the `ListView`.
2819         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2820     }
2821
2822     // Process the results of a file browse.
2823     @Override
2824     public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2825         // Run the default commands.
2826         super.onActivityResult(requestCode, resultCode, returnedIntent);
2827
2828         // Run the commands that correlate to the specified request code.
2829         switch (requestCode) {
2830             case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2831                 // Pass the file to the WebView.
2832                 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2833                 break;
2834
2835             case BROWSE_OPEN_REQUEST_CODE:
2836                 // Don't do anything if the user pressed back from the file picker.
2837                 if (resultCode == Activity.RESULT_OK) {
2838                     // Get a handle for the open dialog fragment.
2839                     DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2840
2841                     // Only update the file name if the dialog still exists.
2842                     if (openDialogFragment != null) {
2843                         // Get a handle for the open dialog.
2844                         Dialog openDialog = openDialogFragment.getDialog();
2845
2846                         // Remove the incorrect lint warning below that the dialog might be null.
2847                         assert openDialog != null;
2848
2849                         // Get a handle for the file name edit text.
2850                         EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2851
2852                         // Get the file name URI from the intent.
2853                         Uri fileNameUri = returnedIntent.getData();
2854
2855                         // Get the file name string from the URI.
2856                         String fileNameString = fileNameUri.toString();
2857
2858                         // Set the file name text.
2859                         fileNameEditText.setText(fileNameString);
2860
2861                         // Move the cursor to the end of the file name edit text.
2862                         fileNameEditText.setSelection(fileNameString.length());
2863                     }
2864                 }
2865                 break;
2866         }
2867     }
2868
2869     private void loadUrlFromTextBox() {
2870         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
2871         String unformattedUrlString = urlEditText.getText().toString().trim();
2872
2873         // Initialize the formatted URL string.
2874         String url = "";
2875
2876         // Check to see if the unformatted URL string is a valid URL.  Otherwise, convert it into a search.
2877         if (unformattedUrlString.startsWith("content://")) {  // This is a Content URL.
2878             // Load the entire content URL.
2879             url = unformattedUrlString;
2880         } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2881                 unformattedUrlString.startsWith("file://")) {  // This is a standard URL.
2882             // Add `https://` at the beginning if there is no protocol.  Otherwise the app will segfault.
2883             if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://")) {
2884                 unformattedUrlString = "https://" + unformattedUrlString;
2885             }
2886
2887             // Initialize the unformatted URL.
2888             URL unformattedUrl = null;
2889
2890             // Convert the unformatted URL string to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
2891             try {
2892                 unformattedUrl = new URL(unformattedUrlString);
2893             } catch (MalformedURLException e) {
2894                 e.printStackTrace();
2895             }
2896
2897             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2898             String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2899             String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2900             String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2901             String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2902             String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2903
2904             // Build the URI.
2905             Uri.Builder uri = new Uri.Builder();
2906             uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2907
2908             // Decode the URI as a UTF-8 string in.
2909             try {
2910                 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2911             } catch (UnsupportedEncodingException exception) {
2912                 // Do nothing.  The formatted URL string will remain blank.
2913             }
2914         } else if (!unformattedUrlString.isEmpty()){  // This is not a URL, but rather a search string.
2915             // Create an encoded URL String.
2916             String encodedUrlString;
2917
2918             // Sanitize the search input.
2919             try {
2920                 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2921             } catch (UnsupportedEncodingException exception) {
2922                 encodedUrlString = "";
2923             }
2924
2925             // Add the base search URL.
2926             url = searchURL + encodedUrlString;
2927         }
2928
2929         // Clear the focus from the URL edit text.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
2930         urlEditText.clearFocus();
2931
2932         // Make it so.
2933         loadUrl(currentWebView, url);
2934     }
2935
2936     private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2937         // Sanitize the URL.
2938         url = sanitizeUrl(url);
2939
2940         // Apply the domain settings and load the URL.
2941         applyDomainSettings(nestedScrollWebView, url, true, false, true);
2942     }
2943
2944     public void findPreviousOnPage(View view) {
2945         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
2946         currentWebView.findNext(false);
2947     }
2948
2949     public void findNextOnPage(View view) {
2950         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2951         currentWebView.findNext(true);
2952     }
2953
2954     public void closeFindOnPage(View view) {
2955         // Get a handle for the views.
2956         Toolbar toolbar = findViewById(R.id.toolbar);
2957         LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2958         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2959
2960         // Delete the contents of `find_on_page_edittext`.
2961         findOnPageEditText.setText(null);
2962
2963         // Clear the highlighted phrases if the WebView is not null.
2964         if (currentWebView != null) {
2965             currentWebView.clearMatches();
2966         }
2967
2968         // Hide the find on page linear layout.
2969         findOnPageLinearLayout.setVisibility(View.GONE);
2970
2971         // Show the toolbar.
2972         toolbar.setVisibility(View.VISIBLE);
2973
2974         // Get a handle for the input method manager.
2975         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2976
2977         // Remove the lint warning below that the input method manager might be null.
2978         assert inputMethodManager != null;
2979
2980         // Hide the keyboard.
2981         inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2982     }
2983
2984     @Override
2985     public void onApplyNewFontSize(DialogFragment dialogFragment) {
2986         // Remove the incorrect lint warning below that the dialog fragment might be null.
2987         assert dialogFragment != null;
2988
2989         // Get the dialog.
2990         Dialog dialog = dialogFragment.getDialog();
2991
2992         // Remove the incorrect lint warning below tha the dialog might be null.
2993         assert dialog != null;
2994
2995         // Get a handle for the font size edit text.
2996         EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2997
2998         // Initialize the new font size variable with the current font size.
2999         int newFontSize = currentWebView.getSettings().getTextZoom();
3000
3001         // Get the font size from the edit text.
3002         try {
3003             newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
3004         } catch (Exception exception) {
3005             // If the edit text does not contain a valid font size do nothing.
3006         }
3007
3008         // Apply the new font size.
3009         currentWebView.getSettings().setTextZoom(newFontSize);
3010     }
3011
3012     @Override
3013     public void onOpen(DialogFragment dialogFragment) {
3014         // Get the dialog.
3015         Dialog dialog = dialogFragment.getDialog();
3016
3017         // Remove the incorrect lint warning below that the dialog might be null.
3018         assert dialog != null;
3019
3020         // Get handles for the views.
3021         EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3022         CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
3023
3024         // Get the file path string.
3025         String openFilePath = fileNameEditText.getText().toString();
3026
3027         // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
3028         applyDomainSettings(currentWebView, openFilePath, true, false, false);
3029
3030         // Open the file according to the type.
3031         if (mhtCheckBox.isChecked()) {  // Force opening of an MHT file.
3032             try {
3033                 // Get the MHT file input stream.
3034                 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
3035
3036                 // Create a temporary MHT file.
3037                 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3038
3039                 // Get a file output stream for the temporary MHT file.
3040                 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
3041
3042                 // Create a transfer byte array.
3043                 byte[] transferByteArray = new byte[1024];
3044
3045                 // Create an integer to track the number of bytes read.
3046                 int bytesRead;
3047
3048                 // Copy the temporary MHT file input stream to the MHT output stream.
3049                 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3050                     temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3051                 }
3052
3053                 // Flush the temporary MHT file output stream.
3054                 temporaryMhtFileOutputStream.flush();
3055
3056                 // Close the streams.
3057                 temporaryMhtFileOutputStream.close();
3058                 mhtFileInputStream.close();
3059
3060                 // Load the temporary MHT file.
3061                 currentWebView.loadUrl(temporaryMhtFile.toString());
3062             } catch (Exception exception) {
3063                 // Display a snackbar.
3064                 Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
3065             }
3066         } else {  // Let the WebView handle opening of the file.
3067             // Open the file.
3068             currentWebView.loadUrl(openFilePath);
3069         }
3070     }
3071
3072     private void downloadUrlWithExternalApp(String url) {
3073         // Create a download intent.  Not specifying the action type will display the maximum number of options.
3074         Intent downloadIntent = new Intent();
3075
3076         // Set the URI and the mime type.
3077         downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3078
3079         // Flag the intent to open in a new task.
3080         downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3081
3082         // Show the chooser.
3083         startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3084     }
3085
3086     public void onSaveUrl(@NonNull String originalUrlString, @NonNull String fileNameString, @NonNull DialogFragment dialogFragment) {
3087         // Store the URL.  This will be used in the save URL activity result launcher.
3088         if (originalUrlString.startsWith("data:")) {
3089             // Save the original URL.
3090             saveUrlString = originalUrlString;
3091         } else {
3092             // Get the dialog.
3093             Dialog dialog = dialogFragment.getDialog();
3094
3095             // Remove the incorrect lint warning below that the dialog might be null.
3096             assert dialog != null;
3097
3098             // Get a handle for the dialog URL edit text.
3099             EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3100
3101             // Get the URL from the edit text, which may have been modified.
3102             saveUrlString = dialogUrlEditText.getText().toString();
3103         }
3104
3105         // Open the file picker.
3106         saveUrlActivityResultLauncher.launch(fileNameString);
3107     }
3108     
3109     // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3110     @SuppressLint("ClickableViewAccessibility")
3111     private void initializeApp() {
3112         // Get a handle for the input method.
3113         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3114
3115         // Remove the lint warning below that the input method manager might be null.
3116         assert inputMethodManager != null;
3117
3118         // Initialize the gray foreground color spans for highlighting the URLs.
3119         initialGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3120         finalGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3121
3122         // Get the current theme status.
3123         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3124
3125         // Set the red color span according to the theme.
3126         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3127             redColorSpan = new ForegroundColorSpan(getColor(R.color.red_a700));
3128         } else {
3129             redColorSpan = new ForegroundColorSpan(getColor(R.color.red_900));
3130         }
3131
3132         // Remove the formatting from the URL edit text when the user is editing the text.
3133         urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3134             if (hasFocus) {  // The user is editing the URL text box.
3135                 // Remove the highlighting.
3136                 urlEditText.getText().removeSpan(redColorSpan);
3137                 urlEditText.getText().removeSpan(initialGrayColorSpan);
3138                 urlEditText.getText().removeSpan(finalGrayColorSpan);
3139             } else {  // The user has stopped editing the URL text box.
3140                 // Move to the beginning of the string.
3141                 urlEditText.setSelection(0);
3142
3143                 // Reapply the highlighting.
3144                 highlightUrlText();
3145             }
3146         });
3147
3148         // Set the go button on the keyboard to load the URL in `urlTextBox`.
3149         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3150             // If the event is a key-down event on the `enter` button, load the URL.
3151             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3152                 // Load the URL into the mainWebView and consume the event.
3153                 loadUrlFromTextBox();
3154
3155                 // If the enter key was pressed, consume the event.
3156                 return true;
3157             } else {
3158                 // If any other key was pressed, do not consume the event.
3159                 return false;
3160             }
3161         });
3162
3163         // Create an Orbot status broadcast receiver.
3164         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3165             @Override
3166             public void onReceive(Context context, Intent intent) {
3167                 // Store the content of the status message in `orbotStatus`.
3168                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3169
3170                 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3171                 if ((orbotStatus != null) && orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
3172                     // Reset the waiting for proxy status.
3173                     waitingForProxy = false;
3174
3175                     // Get a list of the current fragments.
3176                     List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
3177
3178                     // Check each fragment to see if it is a waiting for proxy dialog.  Sometimes more than one is displayed.
3179                     for (int i = 0; i < fragmentList.size(); i++) {
3180                         // Get the fragment tag.
3181                         String fragmentTag = fragmentList.get(i).getTag();
3182
3183                         // Check to see if it is the waiting for proxy dialog.
3184                         if ((fragmentTag!= null) && fragmentTag.equals(getString(R.string.waiting_for_proxy_dialog))) {
3185                             // Dismiss the waiting for proxy dialog.
3186                             ((DialogFragment) fragmentList.get(i)).dismiss();
3187                         }
3188                     }
3189
3190                     // Reload existing URLs and load any URLs that are waiting for the proxy.
3191                     for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3192                         // Get the WebView tab fragment.
3193                         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3194
3195                         // Get the fragment view.
3196                         View fragmentView = webViewTabFragment.getView();
3197
3198                         // Only process the WebViews if they exist.
3199                         if (fragmentView != null) {
3200                             // Get the nested scroll WebView from the tab fragment.
3201                             NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3202
3203                             // Get the waiting for proxy URL string.
3204                             String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3205
3206                             // Load the pending URL if it exists.
3207                             if (!waitingForProxyUrlString.isEmpty()) {  // A URL is waiting to be loaded.
3208                                 // Load the URL.
3209                                 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3210
3211                                 // Reset the waiting for proxy URL string.
3212                                 nestedScrollWebView.setWaitingForProxyUrlString("");
3213                             } else {  // No URL is waiting to be loaded.
3214                                 // Reload the existing URL.
3215                                 nestedScrollWebView.reload();
3216                             }
3217                         }
3218                     }
3219                 }
3220             }
3221         };
3222
3223         // Register the Orbot status broadcast receiver on `this` context.
3224         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3225
3226         // Get handles for views that need to be modified.
3227         LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3228         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3229         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3230         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3231         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3232         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3233
3234         // Update the web view pager every time a tab is modified.
3235         webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3236             @Override
3237             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3238                 // Do nothing.
3239             }
3240
3241             @Override
3242             public void onPageSelected(int position) {
3243                 // Close the find on page bar if it is open.
3244                 closeFindOnPage(null);
3245
3246                 // Set the current WebView.
3247                 setCurrentWebView(position);
3248
3249                 // Select the corresponding tab if it does not match the currently selected page.  This will happen if the page was scrolled by creating a new tab.
3250                 if (tabLayout.getSelectedTabPosition() != position) {
3251                     // Wait until the new tab has been created.
3252                     tabLayout.post(() -> {
3253                         // Get a handle for the tab.
3254                         TabLayout.Tab tab = tabLayout.getTabAt(position);
3255
3256                         // Assert that the tab is not null.
3257                         assert tab != null;
3258
3259                         // Select the tab.
3260                         tab.select();
3261                     });
3262                 }
3263             }
3264
3265             @Override
3266             public void onPageScrollStateChanged(int state) {
3267                 // Do nothing.
3268             }
3269         });
3270
3271         // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3272         tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3273             @Override
3274             public void onTabSelected(TabLayout.Tab tab) {
3275                 // Select the same page in the view pager.
3276                 webViewPager.setCurrentItem(tab.getPosition());
3277             }
3278
3279             @Override
3280             public void onTabUnselected(TabLayout.Tab tab) {
3281                 // Do nothing.
3282             }
3283
3284             @Override
3285             public void onTabReselected(TabLayout.Tab tab) {
3286                 // Instantiate the View SSL Certificate dialog.
3287                 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId(), currentWebView.getFavoriteOrDefaultIcon());
3288
3289                 // Display the View SSL Certificate dialog.
3290                 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3291             }
3292         });
3293
3294         // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3295         bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3296             // Consume the touch.
3297             return true;
3298         });
3299
3300         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3301         launchBookmarksActivityFab.setOnClickListener(v -> {
3302             // Get a copy of the favorite icon bitmap.
3303             Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3304
3305             // Create a favorite icon byte array output stream.
3306             ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3307
3308             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
3309             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3310
3311             // Convert the favorite icon byte array stream to a byte array.
3312             byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3313
3314             // Create an intent to launch the bookmarks activity.
3315             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3316
3317             // Add the extra information to the intent.
3318             bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3319             bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3320             bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3321             bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3322
3323             // Make it so.
3324             startActivity(bookmarksIntent);
3325         });
3326
3327         // Set the create new bookmark folder FAB to display an alert dialog.
3328         createBookmarkFolderFab.setOnClickListener(v -> {
3329             // Create a create bookmark folder dialog.
3330             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3331
3332             // Show the create bookmark folder dialog.
3333             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3334         });
3335
3336         // Set the create new bookmark FAB to display an alert dialog.
3337         createBookmarkFab.setOnClickListener(view -> {
3338             // Instantiate the create bookmark dialog.
3339             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3340
3341             // Display the create bookmark dialog.
3342             createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3343         });
3344
3345         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3346         findOnPageEditText.addTextChangedListener(new TextWatcher() {
3347             @Override
3348             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3349                 // Do nothing.
3350             }
3351
3352             @Override
3353             public void onTextChanged(CharSequence s, int start, int before, int count) {
3354                 // Do nothing.
3355             }
3356
3357             @Override
3358             public void afterTextChanged(Editable s) {
3359                 // Search for the text in the WebView if it is not null.  Sometimes on resume after a period of non-use the WebView will be null.
3360                 if (currentWebView != null) {
3361                     currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3362                 }
3363             }
3364         });
3365
3366         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3367         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3368             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
3369                 // Hide the soft keyboard.
3370                 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3371
3372                 // Consume the event.
3373                 return true;
3374             } else {  // A different key was pressed.
3375                 // Do not consume the event.
3376                 return false;
3377             }
3378         });
3379
3380         // Implement swipe to refresh.
3381         swipeRefreshLayout.setOnRefreshListener(() -> {
3382             // Reload the website.
3383             currentWebView.reload();
3384         });
3385
3386         // Store the default progress view offsets for use later in `initializeWebView()`.
3387         defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3388         defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3389
3390         // Set the refresh color scheme according to the theme.
3391         swipeRefreshLayout.setColorSchemeResources(R.color.blue_text);
3392
3393         // Initialize a color background typed value.
3394         TypedValue colorBackgroundTypedValue = new TypedValue();
3395
3396         // Get the color background from the theme.
3397         getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3398
3399         // Get the color background int from the typed value.
3400         int colorBackgroundInt = colorBackgroundTypedValue.data;
3401
3402         // Set the swipe refresh background color.
3403         swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3404
3405         // The drawer titles identify the drawer layouts in accessibility mode.
3406         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3407         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3408
3409         // Load the bookmarks folder.
3410         loadBookmarksFolder();
3411
3412         // Handle clicks on bookmarks.
3413         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3414             // Convert the id from long to int to match the format of the bookmarks database.
3415             int databaseId = (int) id;
3416
3417             // Get the bookmark cursor for this ID.
3418             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3419
3420             // Move the bookmark cursor to the first row.
3421             bookmarkCursor.moveToFirst();
3422
3423             // Act upon the bookmark according to the type.
3424             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
3425                 // Store the new folder name in `currentBookmarksFolder`.
3426                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3427
3428                 // Load the new folder.
3429                 loadBookmarksFolder();
3430             } else {  // The selected bookmark is not a folder.
3431                 // Load the bookmark URL.
3432                 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3433
3434                 // Close the bookmarks drawer.
3435                 drawerLayout.closeDrawer(GravityCompat.END);
3436             }
3437
3438             // Close the `Cursor`.
3439             bookmarkCursor.close();
3440         });
3441
3442         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3443             // Convert the database ID from `long` to `int`.
3444             int databaseId = (int) id;
3445
3446             // Find out if the selected bookmark is a folder.
3447             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3448
3449             // Check to see if the bookmark is a folder.
3450             if (isFolder) {  // The bookmark is a folder.
3451                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3452                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3453
3454                 // Instantiate the edit folder bookmark dialog.
3455                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3456
3457                 // Show the edit folder bookmark dialog.
3458                 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3459             } else {  // The bookmark is not a folder.
3460                 // Get the bookmark cursor for this ID.
3461                 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3462
3463                 // Move the bookmark cursor to the first row.
3464                 bookmarkCursor.moveToFirst();
3465
3466                 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3467                 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3468
3469                 // Display a snackbar.
3470                 Snackbar.make(drawerLayout, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3471             }
3472
3473             // Consume the event.
3474             return true;
3475         });
3476
3477         // The drawer listener is used to update the navigation menu.
3478         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3479             @Override
3480             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3481             }
3482
3483             @Override
3484             public void onDrawerOpened(@NonNull View drawerView) {
3485             }
3486
3487             @Override
3488             public void onDrawerClosed(@NonNull View drawerView) {
3489                 // Reset the drawer icon when the drawer is closed.  Otherwise, it is an arrow if the drawer is open when the app is restarted.
3490                 actionBarDrawerToggle.syncState();
3491             }
3492
3493             @Override
3494             public void onDrawerStateChanged(int newState) {
3495                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
3496                     // Update the navigation menu items if the WebView is not null.
3497                     if (currentWebView != null) {
3498                         navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3499                         navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3500                         navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3501                         navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3502
3503                         // Hide the keyboard (if displayed).
3504                         inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3505                     }
3506
3507                     // Clear the focus from from the URL text box.  This removes any text selection markers and context menus, which otherwise draw above the open drawers.
3508                     urlEditText.clearFocus();
3509
3510                     // Clear the focus from from the WebView if it is not null, which can happen if a user opens a drawer while the browser is being resumed.
3511                     if (currentWebView != null) {
3512                         // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3513                         currentWebView.clearFocus();
3514                     }
3515                 }
3516             }
3517         });
3518
3519         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
3520         @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3521
3522         // Get a handle for the WebView.
3523         WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3524
3525         // Store the default user agent.
3526         webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3527
3528         // Destroy the bare WebView.
3529         bareWebView.destroy();
3530     }
3531
3532     private void applyAppSettings() {
3533         // Get a handle for the shared preferences.
3534         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3535
3536         // Store the values from the shared preferences in variables.
3537         incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false);
3538         sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true);
3539         sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true);
3540         proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value));
3541         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false);
3542         hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true);
3543         downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3544         scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3545
3546         // Apply the saved proxy mode if the app has been restarted.
3547         if (savedProxyMode != null) {
3548             // Apply the saved proxy mode.
3549             proxyMode = savedProxyMode;
3550
3551             // Reset the saved proxy mode.
3552             savedProxyMode = null;
3553         }
3554
3555         // Get the search string.
3556         String searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value));
3557
3558         // Set the search string.
3559         if (searchString.equals(getString(R.string.custom_url_item)))
3560             searchURL = sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value));
3561         else
3562             searchURL = searchString;
3563
3564         // Apply the proxy.
3565         applyProxy(false);
3566
3567         // Adjust the layout and scrolling parameters according to the position of the app bar.
3568         if (bottomAppBar) {  // The app bar is on the bottom.
3569             // Adjust the UI.
3570             if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3571                 // Reset the WebView padding to fill the available space.
3572                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
3573             } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3574                 // Move the WebView above the app bar layout.
3575                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
3576
3577                 // Show the app bar if it is scrolled off the screen.
3578                 if (appBarLayout.getTranslationY() != 0) {
3579                     // Animate the bottom app bar onto the screen.
3580                     objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
3581
3582                     // Make it so.
3583                     objectAnimator.start();
3584                 }
3585             }
3586         } else {  // The app bar is on the top.
3587             // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3588             CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3589             AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3590             AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3591             AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3592
3593             // Add the scrolling behavior to the layout parameters.
3594             if (scrollAppBar) {
3595                 // Enable scrolling of the app bar.
3596                 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3597                 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3598                 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3599                 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3600             } else {
3601                 // Disable scrolling of the app bar.
3602                 swipeRefreshLayoutParams.setBehavior(null);
3603                 toolbarLayoutParams.setScrollFlags(0);
3604                 findOnPageLayoutParams.setScrollFlags(0);
3605                 tabsLayoutParams.setScrollFlags(0);
3606
3607                 // Expand the app bar if it is currently collapsed.
3608                 appBarLayout.setExpanded(true);
3609             }
3610
3611             // Set the app bar scrolling for each WebView.
3612             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3613                 // Get the WebView tab fragment.
3614                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3615
3616                 // Get the fragment view.
3617                 View fragmentView = webViewTabFragment.getView();
3618
3619                 // Only modify the WebViews if they exist.
3620                 if (fragmentView != null) {
3621                     // Get the nested scroll WebView from the tab fragment.
3622                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3623
3624                     // Set the app bar scrolling.
3625                     nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3626                 }
3627             }
3628         }
3629
3630         // Update the full screen browsing mode settings.
3631         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3632             // Update the visibility of the app bar, which might have changed in the settings.
3633             if (hideAppBar) {
3634                 // Hide the tab linear layout.
3635                 tabsLinearLayout.setVisibility(View.GONE);
3636
3637                 // Hide the action bar.
3638                 actionBar.hide();
3639             } else {
3640                 // Show the tab linear layout.
3641                 tabsLinearLayout.setVisibility(View.VISIBLE);
3642
3643                 // Show the action bar.
3644                 actionBar.show();
3645             }
3646
3647             /* Hide the system bars.
3648              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3649              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3650              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3651              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3652              */
3653             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3654                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3655         } else {  // Privacy Browser is not in full screen browsing mode.
3656             // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3657             inFullScreenBrowsingMode = false;
3658
3659             // Show the tab linear layout.
3660             tabsLinearLayout.setVisibility(View.VISIBLE);
3661
3662             // Show the action bar.
3663             actionBar.show();
3664
3665             // Remove the `SYSTEM_UI` flags from the root frame layout.
3666             rootFrameLayout.setSystemUiVisibility(0);
3667         }
3668     }
3669
3670     @Override
3671     public void navigateHistory(@NonNull String url, int steps) {
3672         // Apply the domain settings.
3673         applyDomainSettings(currentWebView, url, false, false, false);
3674
3675         // Load the history entry.
3676         currentWebView.goBackOrForward(steps);
3677     }
3678
3679     @Override
3680     public void pinnedErrorGoBack() {
3681         // Get the current web back forward list.
3682         WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3683
3684         // Get the previous entry URL.
3685         String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3686
3687         // Apply the domain settings.
3688         applyDomainSettings(currentWebView, previousUrl, false, false, false);
3689
3690         // Go back.
3691         currentWebView.goBack();
3692     }
3693
3694     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3695     @SuppressLint("SetJavaScriptEnabled")
3696     private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3697         // Store the current URL.
3698         nestedScrollWebView.setCurrentUrl(url);
3699
3700         // Parse the URL into a URI.
3701         Uri uri = Uri.parse(url);
3702
3703         // Extract the domain from `uri`.
3704         String newHostName = uri.getHost();
3705
3706         // Strings don't like to be null.
3707         if (newHostName == null) {
3708             newHostName = "";
3709         }
3710
3711         // Apply the domain settings if a new domain is being loaded or if the new domain is blank.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3712         if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3713             // Set the new host name as the current domain name.
3714             nestedScrollWebView.setCurrentDomainName(newHostName);
3715
3716             // Reset the ignoring of pinned domain information.
3717             nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3718
3719             // Clear any pinned SSL certificate or IP addresses.
3720             nestedScrollWebView.clearPinnedSslCertificate();
3721             nestedScrollWebView.setPinnedIpAddresses("");
3722
3723             // Reset the favorite icon if specified.
3724             if (resetTab) {
3725                 // Initialize the favorite icon.
3726                 nestedScrollWebView.initializeFavoriteIcon();
3727
3728                 // Get the current page position.
3729                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3730
3731                 // Get the corresponding tab.
3732                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3733
3734                 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3735                 if (tab != null) {
3736                     // Get the tab custom view.
3737                     View tabCustomView = tab.getCustomView();
3738
3739                     // Remove the warning below that the tab custom view might be null.
3740                     assert tabCustomView != null;
3741
3742                     // Get the tab views.
3743                     ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3744                     TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3745
3746                     // Set the default favorite icon as the favorite icon for this tab.
3747                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3748
3749                     // Set the loading title text.
3750                     tabTitleTextView.setText(R.string.loading);
3751                 }
3752             }
3753
3754             // Get a full domain name cursor.
3755             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3756
3757             // Initialize `domainSettingsSet`.
3758             Set<String> domainSettingsSet = new HashSet<>();
3759
3760             // Get the domain name column index.
3761             int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3762
3763             // Populate the domain settings set.
3764             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3765                 // Move the domains cursor to the current row.
3766                 domainNameCursor.moveToPosition(i);
3767
3768                 // Store the domain name in the domain settings set.
3769                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3770             }
3771
3772             // Close the domain name cursor.
3773             domainNameCursor.close();
3774
3775             // Initialize the domain name in database variable.
3776             String domainNameInDatabase = null;
3777
3778             // Check the hostname against the domain settings set.
3779             if (domainSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
3780                 // Record the domain name in the database.
3781                 domainNameInDatabase = newHostName;
3782
3783                 // Set the domain settings applied tracker to true.
3784                 nestedScrollWebView.setDomainSettingsApplied(true);
3785             } else {  // The hostname is not contained in the domain settings set.
3786                 // Set the domain settings applied tracker to false.
3787                 nestedScrollWebView.setDomainSettingsApplied(false);
3788             }
3789
3790             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3791             while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3792                 if (domainSettingsSet.contains("*." + newHostName)) {  // Check the host name prepended by `*.`.
3793                     // Set the domain settings applied tracker to true.
3794                     nestedScrollWebView.setDomainSettingsApplied(true);
3795
3796                     // Store the applied domain names as it appears in the database.
3797                     domainNameInDatabase = "*." + newHostName;
3798                 }
3799
3800                 // Strip out the lowest subdomain of of the host name.
3801                 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3802             }
3803
3804
3805             // Get a handle for the shared preferences.
3806             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3807
3808             // Store the general preference information.
3809             String defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value));
3810             String defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value));
3811             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true);
3812             String webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value));
3813             boolean wideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true);
3814             boolean displayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true);
3815
3816             // Get the WebView theme entry values string array.
3817             String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3818
3819             // Get a handle for the cookie manager.
3820             CookieManager cookieManager = CookieManager.getInstance();
3821
3822             // Initialize the user agent array adapter and string array.
3823             ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3824             String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3825
3826             if (nestedScrollWebView.getDomainSettingsApplied()) {  // The url has custom domain settings.
3827                 // Remove the incorrect lint warning below that the domain name in database might be null.
3828                 assert domainNameInDatabase != null;
3829
3830                 // Get a cursor for the current host.
3831                 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3832
3833                 // Move to the first position.
3834                 currentDomainSettingsCursor.moveToFirst();
3835
3836                 // Get the settings from the cursor.
3837                 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID)));
3838                 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3839                 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3840                 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3841                 // Form data can be removed once the minimum API >= 26.
3842                 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3843                 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3844                 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3845                 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3846                         DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3847                 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3848                         DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3849                 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3850                 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3851                 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3852                         DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3853                 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3854                 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3855                 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3856                 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3857                 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3858                 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3859                 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3860                 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3861                 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3862                 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3863                 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3864                 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3865                 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3866                 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3867                 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3868                 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3869                 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3870
3871                 // Close the current host domain settings cursor.
3872                 currentDomainSettingsCursor.close();
3873
3874                 // If there is a pinned SSL certificate, store it in the WebView.
3875                 if (pinnedSslCertificate) {
3876                     nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3877                             pinnedSslStartDate, pinnedSslEndDate);
3878                 }
3879
3880                 // If there is a pinned IP address, store it in the WebView.
3881                 if (pinnedIpAddresses) {
3882                     nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3883                 }
3884
3885                 // Apply the cookie domain settings.
3886                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3887
3888                 // Apply the form data setting if the API < 26.
3889                 if (Build.VERSION.SDK_INT < 26) {
3890                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3891                 }
3892
3893                 // Apply the font size.
3894                 try {  // Try the specified font size to see if it is valid.
3895                     if (fontSize == 0) {  // Apply the default font size.
3896                             // Try to set the font size from the value in the app settings.
3897                             nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3898                     } else {  // Apply the font size from domain settings.
3899                         nestedScrollWebView.getSettings().setTextZoom(fontSize);
3900                     }
3901                 } catch (Exception exception) {  // The specified font size is invalid
3902                     // Set the font size to be 100%
3903                     nestedScrollWebView.getSettings().setTextZoom(100);
3904                 }
3905
3906                 // Set the user agent.
3907                 if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3908                     // Get the array position of the default user agent name.
3909                     int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3910
3911                     // Set the user agent according to the system default.
3912                     switch (defaultUserAgentArrayPosition) {
3913                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3914                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3915                             nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3916                             break;
3917
3918                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3919                             // Set the user agent to `""`, which uses the default value.
3920                             nestedScrollWebView.getSettings().setUserAgentString("");
3921                             break;
3922
3923                         case SETTINGS_CUSTOM_USER_AGENT:
3924                             // Set the default custom user agent.
3925                             nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
3926                             break;
3927
3928                         default:
3929                             // Get the user agent string from the user agent data array
3930                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3931                     }
3932                 } else {  // Set the user agent according to the stored name.
3933                     // Get the array position of the user agent name.
3934                     int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3935
3936                     switch (userAgentArrayPosition) {
3937                         case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3938                             nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3939                             break;
3940
3941                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3942                             // Set the user agent to `""`, which uses the default value.
3943                             nestedScrollWebView.getSettings().setUserAgentString("");
3944                             break;
3945
3946                         default:
3947                             // Get the user agent string from the user agent data array.
3948                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3949                     }
3950                 }
3951
3952                 // Set swipe to refresh.
3953                 switch (swipeToRefreshInt) {
3954                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3955                         // Store the swipe to refresh status in the nested scroll WebView.
3956                         nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3957
3958                         // Update the swipe refresh layout.
3959                         if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
3960                             // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3961                             swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3962                         } else {  // Swipe to refresh is disabled.
3963                             // Disable the swipe refresh layout.
3964                             swipeRefreshLayout.setEnabled(false);
3965                         }
3966                         break;
3967
3968                     case DomainsDatabaseHelper.ENABLED:
3969                         // Store the swipe to refresh status in the nested scroll WebView.
3970                         nestedScrollWebView.setSwipeToRefresh(true);
3971
3972                         // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3973                         swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3974                         break;
3975
3976                     case DomainsDatabaseHelper.DISABLED:
3977                         // Store the swipe to refresh status in the nested scroll WebView.
3978                         nestedScrollWebView.setSwipeToRefresh(false);
3979
3980                         // Disable swipe to refresh.
3981                         swipeRefreshLayout.setEnabled(false);
3982                         break;
3983                 }
3984
3985                 // Check to see if WebView themes are supported.
3986                 if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {  // The device is running API >= 33 and algorithmic darkening is supported.
3987                     // Set the WebView theme.
3988                     switch (webViewThemeInt) {
3989                         case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3990                             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3991                             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
3992                                 // Turn off algorithmic darkening.
3993                                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
3994                             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
3995                                 // Turn on algorithmic darkening.
3996                                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
3997                             } else {  // The system default theme is selected.
3998                                 // Get the current system theme status.
3999                                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4000
4001                                 // Set the algorithmic darkening according to the current system theme status.
4002                                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES));
4003                             }
4004                             break;
4005
4006                         case DomainsDatabaseHelper.LIGHT_THEME:
4007                             // Turn off algorithmic darkening.
4008                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
4009                             break;
4010
4011                         case DomainsDatabaseHelper.DARK_THEME:
4012                             // Turn on algorithmic darkening.
4013                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
4014                             break;
4015                     }
4016                 } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {  // The device is running API < 33 and the WebView supports force dark.
4017                     // Set the WebView theme.
4018                     switch (webViewThemeInt) {
4019                         case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4020                             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4021                             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
4022                                 // Turn off the WebView dark mode.
4023                                 //noinspection deprecation
4024                                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4025                             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
4026                                 // Turn on the WebView dark mode.
4027                                 //noinspection deprecation
4028                                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4029                             } else {  // The system default theme is selected.
4030                                 // Get the current system theme status.
4031                                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4032
4033                                 // Set the WebView theme according to the current system theme status.
4034                                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
4035                                     // Turn off the WebView dark mode.
4036                                     //noinspection deprecation
4037                                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4038                                 } else {  // The system is in night mode.
4039                                     // Turn on the WebView dark mode.
4040                                     //noinspection deprecation
4041                                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4042                                 }
4043                             }
4044                             break;
4045
4046                         case DomainsDatabaseHelper.LIGHT_THEME:
4047                             // Turn off the WebView dark mode.
4048                             //noinspection deprecation
4049                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4050                             break;
4051
4052                         case DomainsDatabaseHelper.DARK_THEME:
4053                             // Turn on the WebView dark mode.
4054                             //noinspection deprecation
4055                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4056                             break;
4057                     }
4058                 }
4059
4060                 // Set the viewport.
4061                 switch (wideViewportInt) {
4062                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4063                         nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4064                         break;
4065
4066                     case DomainsDatabaseHelper.ENABLED:
4067                         nestedScrollWebView.getSettings().setUseWideViewPort(true);
4068                         break;
4069
4070                     case DomainsDatabaseHelper.DISABLED:
4071                         nestedScrollWebView.getSettings().setUseWideViewPort(false);
4072                         break;
4073                 }
4074
4075                 // Set the loading of webpage images.
4076                 switch (displayWebpageImagesInt) {
4077                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4078                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4079                         break;
4080
4081                     case DomainsDatabaseHelper.ENABLED:
4082                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4083                         break;
4084
4085                     case DomainsDatabaseHelper.DISABLED:
4086                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4087                         break;
4088                 }
4089
4090                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4091                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4092             } else {  // The new URL does not have custom domain settings.  Load the defaults.
4093                 // Store the values from the shared preferences.
4094                 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean(getString(R.string.javascript_key), false));
4095                 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4096                 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false));
4097                 boolean saveFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false);  // Form data can be removed once the minimum API >= 26.
4098                 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean(getString(R.string.easylist_key), true));
4099                 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true));
4100                 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true));
4101                 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true));
4102                 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean(getString(R.string.ultralist_key), true));
4103                 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true));
4104                 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false));
4105
4106                 // Apply the default cookie setting.
4107                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4108
4109                 // Apply the default font size setting.
4110                 try {
4111                     // Try to set the font size from the value in the app settings.
4112                     nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4113                 } catch (Exception exception) {
4114                     // If the app settings value is invalid, set the font size to 100%.
4115                     nestedScrollWebView.getSettings().setTextZoom(100);
4116                 }
4117
4118                 // Apply the form data setting if the API < 26.
4119                 if (Build.VERSION.SDK_INT < 26) {
4120                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4121                 }
4122
4123                 // Store the swipe to refresh status in the nested scroll WebView.
4124                 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4125
4126                 // Update the swipe refresh layout.
4127                 if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
4128                     // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
4129                     swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4130                 } else {  // Swipe to refresh is disabled.
4131                     // Disable the swipe refresh layout.
4132                     swipeRefreshLayout.setEnabled(false);
4133                 }
4134
4135                 // Reset the pinned variables.
4136                 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4137
4138                 // Get the array position of the user agent name.
4139                 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4140
4141                 // Set the user agent.
4142                 switch (userAgentArrayPosition) {
4143                     case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4144                         // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4145                         nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4146                         break;
4147
4148                     case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4149                         // Set the user agent to `""`, which uses the default value.
4150                         nestedScrollWebView.getSettings().setUserAgentString("");
4151                         break;
4152
4153                     case SETTINGS_CUSTOM_USER_AGENT:
4154                         // Set the default custom user agent.
4155                         nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
4156                         break;
4157
4158                     default:
4159                         // Get the user agent string from the user agent data array
4160                         nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4161                 }
4162
4163                 // Apply the WebView theme if supported by the installed WebView.
4164                 if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {  // The device is running API >= 33 and algorithmic darkening is supported.
4165                     // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4166                     if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // the light theme is selected.
4167                         // Turn off algorithmic darkening.
4168                         WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
4169                     } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
4170                         // Turn on algorithmic darkening.
4171                         WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
4172                     } else {  // The system default theme is selected.
4173                         // Get the current system theme status.
4174                         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4175
4176                         // Set the algorithmic darkening according to the current system theme status.
4177                         WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), currentThemeStatus == Configuration.UI_MODE_NIGHT_YES);
4178                     }
4179                 } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {  // The device is running API < 33 and the WebView supports force dark.
4180                     // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4181                     if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
4182                         // Turn off the WebView dark mode.
4183                         //noinspection deprecation
4184                         WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4185                     } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
4186                         // Turn on the WebView dark mode.
4187                         //noinspection deprecation
4188                         WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4189                     } else {  // The system default theme is selected.
4190                         // Get the current system theme status.
4191                         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4192
4193                         // Set the WebView theme according to the current system theme status.
4194                         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
4195                             // Turn off the WebView dark mode.
4196                             //noinspection deprecation
4197                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4198                         } else {  // The system is in night mode.
4199                             // Turn on the WebView dark mode.
4200                             //noinspection deprecation
4201                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4202                         }
4203                     }
4204                 }
4205
4206                 // Set the viewport.
4207                 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4208
4209                 // Set the loading of webpage images.
4210                 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4211
4212                 // Set a transparent background on the URL relative layout.
4213                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4214             }
4215
4216             // Close the domains database helper.
4217             domainsDatabaseHelper.close();
4218
4219             // Update the privacy icons.
4220             updatePrivacyIcons(true);
4221         }
4222
4223         // Reload the website if returning from the Domains activity.
4224         if (reloadWebsite) {
4225             nestedScrollWebView.reload();
4226         }
4227
4228         // Load the URL if directed.  This makes sure that the domain settings are properly loaded before the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4229         if (loadUrl) {
4230             nestedScrollWebView.loadUrl(url);
4231         }
4232     }
4233
4234     private void applyProxy(boolean reloadWebViews) {
4235         // Set the proxy according to the mode.
4236         proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4237
4238         // Reset the waiting for proxy tracker.
4239         waitingForProxy = false;
4240
4241         // Get the current theme status.
4242         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4243
4244         // Update the user interface and reload the WebViews if requested.
4245         switch (proxyMode) {
4246             case ProxyHelper.NONE:
4247                 // Initialize a color background typed value.
4248                 TypedValue colorBackgroundTypedValue = new TypedValue();
4249
4250                 // Get the color background from the theme.
4251                 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4252
4253                 // Get the color background int from the typed value.
4254                 int colorBackgroundInt = colorBackgroundTypedValue.data;
4255
4256                 // Set the default app bar layout background.
4257                 appBarLayout.setBackgroundColor(colorBackgroundInt);
4258                 break;
4259
4260             case ProxyHelper.TOR:
4261                 // Set the app bar background to indicate proxying through Orbot is enabled.
4262                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4263                     appBarLayout.setBackgroundResource(R.color.blue_50);
4264                 } else {
4265                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4266                 }
4267
4268                 // Check to see if Orbot is installed.
4269                 try {
4270                     // Get the package manager.
4271                     PackageManager packageManager = getPackageManager();
4272
4273                     // Check to see if Orbot is in the list.  This will throw an error and drop to the catch section if it isn't installed.
4274                     packageManager.getPackageInfo("org.torproject.android", 0);
4275
4276                     // Check to see if the proxy is ready.
4277                     if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) {  // Orbot is not ready.
4278                         // Set the waiting for proxy status.
4279                         waitingForProxy = true;
4280
4281                         // Show the waiting for proxy dialog if it isn't already displayed.
4282                         if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4283                             // Get a handle for the waiting for proxy alert dialog.
4284                             DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4285
4286                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4287                             try {
4288                                 // Show the waiting for proxy alert dialog.
4289                                 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4290                             } catch (Exception waitingForTorException) {
4291                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4292                                 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4293                             }
4294                         }
4295                     }
4296                 } catch (PackageManager.NameNotFoundException exception) {  // Orbot is not installed.
4297                     // Show the Orbot not installed dialog if it is not already displayed.
4298                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4299                         // Get a handle for the Orbot not installed alert dialog.
4300                         DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4301
4302                         // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4303                         try {
4304                             // Display the Orbot not installed alert dialog.
4305                             orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4306                         } catch (Exception orbotNotInstalledException) {
4307                             // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4308                             pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4309                         }
4310                     }
4311                 }
4312                 break;
4313
4314             case ProxyHelper.I2P:
4315                 // Set the app bar background to indicate proxying through Orbot is enabled.
4316                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4317                     appBarLayout.setBackgroundResource(R.color.blue_50);
4318                 } else {
4319                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4320                 }
4321                 // Get the package manager.
4322                 PackageManager packageManager = getPackageManager();
4323
4324                 // Check to see if I2P is installed.
4325                 try {
4326                     // Check to see if the F-Droid flavor is installed.  This will throw an error and drop to the catch section if it isn't installed.
4327                     packageManager.getPackageInfo("net.i2p.android.router", 0);
4328                 } catch (PackageManager.NameNotFoundException fdroidException) {  // The F-Droid flavor is not installed.
4329                     try {
4330                         // Check to see if the Google Play flavor is installed.  This will throw an error and drop to the catch section if it isn't installed.
4331                         packageManager.getPackageInfo("net.i2p.android", 0);
4332                     } catch (PackageManager.NameNotFoundException googlePlayException) {  // The Google Play flavor is not installed.
4333                         // Sow the I2P not installed dialog if it is not already displayed.
4334                         if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4335                             // Get a handle for the waiting for proxy alert dialog.
4336                             DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4337
4338                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4339                             try {
4340                                 // Display the I2P not installed alert dialog.
4341                                 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4342                             } catch (Exception i2pNotInstalledException) {
4343                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4344                                 pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4345                             }
4346                         }
4347                     }
4348                 }
4349                 break;
4350
4351             case ProxyHelper.CUSTOM:
4352                 // Set the app bar background to indicate proxying through Orbot is enabled.
4353                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4354                     appBarLayout.setBackgroundResource(R.color.blue_50);
4355                 } else {
4356                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4357                 }
4358                 break;
4359         }
4360
4361         // Reload the WebViews if requested and not waiting for the proxy.
4362         if (reloadWebViews && !waitingForProxy) {
4363             // Reload the WebViews.
4364             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4365                 // Get the WebView tab fragment.
4366                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4367
4368                 // Get the fragment view.
4369                 View fragmentView = webViewTabFragment.getView();
4370
4371                 // Only reload the WebViews if they exist.
4372                 if (fragmentView != null) {
4373                     // Get the nested scroll WebView from the tab fragment.
4374                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4375
4376                     // Reload the WebView.
4377                     nestedScrollWebView.reload();
4378                 }
4379             }
4380         }
4381     }
4382
4383     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4384         // Only update the privacy icons if the options menu and the current WebView have already been populated.
4385         if ((optionsMenu != null) && (currentWebView != null)) {
4386             // Update the privacy icon.
4387             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled.
4388                 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4389             } else if (currentWebView.getAcceptCookies()) {  // JavaScript is disabled but cookies are enabled.
4390                 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4391             } else {  // All the dangerous features are disabled.
4392                 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4393             }
4394
4395             // Update the cookies icon.
4396             if (currentWebView.getAcceptCookies()) {
4397                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4398             } else {
4399                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled);
4400             }
4401
4402             // Update the refresh icon.
4403             if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) {  // The refresh icon is displayed.
4404                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4405                 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
4406             } else {  // The stop icon is displayed.
4407                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4408                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
4409             }
4410
4411             // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4412             if (runInvalidateOptionsMenu) {
4413                 invalidateOptionsMenu();
4414             }
4415         }
4416     }
4417
4418     private void highlightUrlText() {
4419         // Only highlight the URL text if the box is not currently selected.
4420         if (!urlEditText.hasFocus()) {
4421             // Get the URL string.
4422             String urlString = urlEditText.getText().toString();
4423
4424             // Highlight the URL according to the protocol.
4425             if (urlString.startsWith("file://") || urlString.startsWith("content://")) {  // This is a file or content URL.
4426                 // De-emphasize everything before the file name.
4427                 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4428             } else {  // This is a web URL.
4429                 // Get the index of the `/` immediately after the domain name.
4430                 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4431
4432                 // Create a base URL string.
4433                 String baseUrl;
4434
4435                 // Get the base URL.
4436                 if (endOfDomainName > 0) {  // There is at least one character after the base URL.
4437                     // Get the base URL.
4438                     baseUrl = urlString.substring(0, endOfDomainName);
4439                 } else {  // There are no characters after the base URL.
4440                     // Set the base URL to be the entire URL string.
4441                     baseUrl = urlString;
4442                 }
4443
4444                 // Get the index of the last `.` in the domain.
4445                 int lastDotIndex = baseUrl.lastIndexOf(".");
4446
4447                 // Get the index of the penultimate `.` in the domain.
4448                 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4449
4450                 // Markup the beginning of the URL.
4451                 if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4452                     urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4453
4454                     // De-emphasize subdomains.
4455                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4456                         urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4457                     }
4458                 } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4459                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4460                         // De-emphasize the protocol and the additional subdomains.
4461                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4462                     } else {  // There is only one subdomain in the domain name.
4463                         // De-emphasize only the protocol.
4464                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4465                     }
4466                 }
4467
4468                 // De-emphasize the text after the domain name.
4469                 if (endOfDomainName > 0) {
4470                     urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4471                 }
4472             }
4473         }
4474     }
4475
4476     private void loadBookmarksFolder() {
4477         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4478         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4479
4480         // Populate the bookmarks cursor adapter.
4481         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4482             @Override
4483             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4484                 // Inflate the individual item layout.
4485                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4486             }
4487
4488             @Override
4489             public void bindView(View view, Context context, Cursor cursor) {
4490                 // Get handles for the views.
4491                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4492                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4493
4494                 // Get the favorite icon byte array from the cursor.
4495                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4496
4497                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4498                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4499
4500                 // Display the bitmap in `bookmarkFavoriteIcon`.
4501                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4502
4503                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4504                 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4505                 bookmarkNameTextView.setText(bookmarkNameString);
4506
4507                 // Make the font bold for folders.
4508                 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4509                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4510                 } else {  // Reset the font to default for normal bookmarks.
4511                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4512                 }
4513             }
4514         };
4515
4516         // Get a handle for the bookmarks list view.
4517         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4518
4519         // Populate the list view with the adapter.
4520         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4521
4522         // Get a handle for the bookmarks title text view.
4523         TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4524
4525         // Set the bookmarks drawer title.
4526         if (currentBookmarksFolder.isEmpty()) {
4527             bookmarksTitleTextView.setText(R.string.bookmarks);
4528         } else {
4529             bookmarksTitleTextView.setText(currentBookmarksFolder);
4530         }
4531     }
4532
4533     private void openWithApp(String url) {
4534         // Create an open with app intent with `ACTION_VIEW`.
4535         Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4536
4537         // Set the URI but not the MIME type.  This should open all available apps.
4538         openWithAppIntent.setData(Uri.parse(url));
4539
4540         // Flag the intent to open in a new task.
4541         openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4542
4543         // Try the intent.
4544         try {
4545             // Show the chooser.
4546             startActivity(openWithAppIntent);
4547         } catch (ActivityNotFoundException exception) {  // There are no apps available to open the URL.
4548             // Show a snackbar with the error.
4549             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4550         }
4551     }
4552
4553     private void openWithBrowser(String url) {
4554         // Create an open with browser intent with `ACTION_VIEW`.
4555         Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4556
4557         // Set the URI and the MIME type.  `"text/html"` should load browser options.
4558         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4559
4560         // Flag the intent to open in a new task.
4561         openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4562
4563         // Try the intent.
4564         try {
4565             // Show the chooser.
4566             startActivity(openWithBrowserIntent);
4567         } catch (ActivityNotFoundException exception) {  // There are no browsers available to open the URL.
4568             // Show a snackbar with the error.
4569             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4570         }
4571     }
4572
4573     private String sanitizeUrl(String url) {
4574         // Sanitize tracking queries.
4575         if (sanitizeTrackingQueries)
4576             url = sanitizeUrlHelper.sanitizeTrackingQueries(url);
4577
4578         // Sanitize AMP redirects.
4579         if (sanitizeAmpRedirects)
4580             url = sanitizeUrlHelper.sanitizeAmpRedirects(url);
4581
4582         // Return the sanitized URL.
4583         return url;
4584     }
4585
4586     public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4587         // Store the blocklists.
4588         easyList = combinedBlocklists.get(0);
4589         easyPrivacy = combinedBlocklists.get(1);
4590         fanboysAnnoyanceList = combinedBlocklists.get(2);
4591         fanboysSocialList = combinedBlocklists.get(3);
4592         ultraList = combinedBlocklists.get(4);
4593         ultraPrivacy = combinedBlocklists.get(5);
4594
4595         // Check to see if the activity has been restarted with a saved state.
4596         if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) {  // The activity has not been restarted or it was restarted on start to force the night theme.
4597             // Add the first tab.
4598             addNewTab("", true);
4599         } else {  // The activity has been restarted.
4600             // Restore each tab.  Once the minimum API >= 24, a `forEach()` command can be used.
4601             for (int i = 0; i < savedStateArrayList.size(); i++) {
4602                 // Add a new tab.
4603                 tabLayout.addTab(tabLayout.newTab());
4604
4605                 // Get the new tab.
4606                 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4607
4608                 // Remove the lint warning below that the current tab might be null.
4609                 assert newTab != null;
4610
4611                 // Set a custom view on the new tab.
4612                 newTab.setCustomView(R.layout.tab_custom_view);
4613
4614                 // Add the new page.
4615                 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4616             }
4617
4618             // Reset the saved state variables.
4619             savedStateArrayList = null;
4620             savedNestedScrollWebViewStateArrayList = null;
4621
4622             // Restore the selected tab position.
4623             if (savedTabPosition == 0) {  // The first tab is selected.
4624                 // Set the first page as the current WebView.
4625                 setCurrentWebView(0);
4626             } else {  // the first tab is not selected.
4627                 // Move to the selected tab.
4628                 webViewPager.setCurrentItem(savedTabPosition);
4629             }
4630
4631             // Get the intent that started the app.
4632             Intent intent = getIntent();
4633
4634             // Reset the intent.  This prevents a duplicate tab from being created on restart.
4635             setIntent(new Intent());
4636
4637             // Get the information from the intent.
4638             String intentAction = intent.getAction();
4639             Uri intentUriData = intent.getData();
4640             String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4641
4642             // Determine if this is a web search.
4643             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4644
4645             // 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.
4646             if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4647                 // Get the shared preferences.
4648                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4649
4650                 // Create a URL string.
4651                 String url;
4652
4653                 // If the intent action is a web search, perform the search.
4654                 if (isWebSearch) {  // The intent is a web search.
4655                     // Create an encoded URL string.
4656                     String encodedUrlString;
4657
4658                     // Sanitize the search input and convert it to a search.
4659                     try {
4660                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4661                     } catch (UnsupportedEncodingException exception) {
4662                         encodedUrlString = "";
4663                     }
4664
4665                     // Add the base search URL.
4666                     url = searchURL + encodedUrlString;
4667                 } else if (intentUriData != null) {  // The intent contains a URL formatted as a URI.
4668                     // Set the intent data as the URL.
4669                     url = intentUriData.toString();
4670                 } else {  // The intent contains a string, which might be a URL.
4671                     // Set the intent string as the URL.
4672                     url = intentStringExtra;
4673                 }
4674
4675                 // Add a new tab if specified in the preferences.
4676                 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) {  // Load the URL in a new tab.
4677                     // Set the loading new intent flag.
4678                     loadingNewIntent = true;
4679
4680                     // Add a new tab.
4681                     addNewTab(url, true);
4682                 } else {  // Load the URL in the current tab.
4683                     // Make it so.
4684                     loadUrl(currentWebView, url);
4685                 }
4686             }
4687         }
4688     }
4689
4690     public void addTab(View view) {
4691         // Add a new tab with a blank URL.
4692         addNewTab("", true);
4693     }
4694
4695     private void addNewTab(String url, boolean moveToTab) {
4696         // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4697         urlEditText.clearFocus();
4698
4699         // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
4700         int newTabNumber = tabLayout.getTabCount();
4701
4702         // Add a new tab.
4703         tabLayout.addTab(tabLayout.newTab());
4704
4705         // Get the new tab.
4706         TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4707
4708         // Remove the lint warning below that the current tab might be null.
4709         assert newTab != null;
4710
4711         // Set a custom view on the new tab.
4712         newTab.setCustomView(R.layout.tab_custom_view);
4713
4714         // Add the new WebView page.
4715         webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4716
4717         // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4718         if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4719             // Animate the bottom app bar onto the screen.
4720             objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4721
4722             // Make it so.
4723             objectAnimator.start();
4724         }
4725     }
4726
4727     public void closeTab(View view) {
4728         // Run the command according to the number of tabs.
4729         if (tabLayout.getTabCount() > 1) {  // There is more than one tab open.
4730             // Close the current tab.
4731             closeCurrentTab();
4732         } else {  // There is only one tab open.
4733             clearAndExit();
4734         }
4735     }
4736
4737     private void closeCurrentTab() {
4738         // Get the current tab number.
4739         int currentTabNumber = tabLayout.getSelectedTabPosition();
4740
4741         // Delete the current tab.
4742         tabLayout.removeTabAt(currentTabNumber);
4743
4744         // Delete the current page.  If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
4745         // meaning that the current WebView must be reset.  Otherwise it will happen automatically as the selected tab number changes.
4746         if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4747             setCurrentWebView(currentTabNumber);
4748         }
4749     }
4750
4751     private void exitFullScreenVideo() {
4752         // Re-enable the screen timeout.
4753         fullScreenVideoFrameLayout.setKeepScreenOn(false);
4754
4755         // Unset the full screen video flag.
4756         displayingFullScreenVideo = false;
4757
4758         // Remove all the views from the full screen video frame layout.
4759         fullScreenVideoFrameLayout.removeAllViews();
4760
4761         // Hide the full screen video frame layout.
4762         fullScreenVideoFrameLayout.setVisibility(View.GONE);
4763
4764         // Enable the sliding drawers.
4765         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4766
4767         // Show the coordinator layout.
4768         coordinatorLayout.setVisibility(View.VISIBLE);
4769
4770         // Apply the appropriate full screen mode flags.
4771         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
4772             // Hide the app bar if specified.
4773             if (hideAppBar) {
4774                 // Hide the tab linear layout.
4775                 tabsLinearLayout.setVisibility(View.GONE);
4776
4777                 // Hide the action bar.
4778                 actionBar.hide();
4779             }
4780
4781             /* Hide the system bars.
4782              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4783              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4784              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4785              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4786              */
4787             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4788                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4789         } else {  // Switch to normal viewing mode.
4790             // Remove the `SYSTEM_UI` flags from the root frame layout.
4791             rootFrameLayout.setSystemUiVisibility(0);
4792         }
4793     }
4794
4795     private void clearAndExit() {
4796         // Get a handle for the shared preferences.
4797         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4798
4799         // Close the bookmarks cursor and database.
4800         bookmarksCursor.close();
4801         bookmarksDatabaseHelper.close();
4802
4803         // Get the status of the clear everything preference.
4804         boolean clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true);
4805
4806         // Get a handle for the runtime.
4807         Runtime runtime = Runtime.getRuntime();
4808
4809         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4810         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4811         String privateDataDirectoryString = getApplicationInfo().dataDir;
4812
4813         // Clear cookies.
4814         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
4815             // Request the cookies be deleted.
4816             CookieManager.getInstance().removeAllCookies(null);
4817
4818             // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4819             try {
4820                 // Two commands must be used because `Runtime.exec()` does not like `*`.
4821                 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4822                 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4823
4824                 // Wait until the processes have finished.
4825                 deleteCookiesProcess.waitFor();
4826                 deleteCookiesJournalProcess.waitFor();
4827             } catch (Exception exception) {
4828                 // Do nothing if an error is thrown.
4829             }
4830         }
4831
4832         // Clear DOM storage.
4833         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
4834             // Ask `WebStorage` to clear the DOM storage.
4835             WebStorage webStorage = WebStorage.getInstance();
4836             webStorage.deleteAllData();
4837
4838             // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4839             try {
4840                 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4841                 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4842
4843                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4844                 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4845                 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4846                 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4847                 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4848
4849                 // Wait until the processes have finished.
4850                 deleteLocalStorageProcess.waitFor();
4851                 deleteIndexProcess.waitFor();
4852                 deleteQuotaManagerProcess.waitFor();
4853                 deleteQuotaManagerJournalProcess.waitFor();
4854                 deleteDatabaseProcess.waitFor();
4855             } catch (Exception exception) {
4856                 // Do nothing if an error is thrown.
4857             }
4858         }
4859
4860         // Clear form data if the API < 26.
4861         if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
4862             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4863             webViewDatabase.clearFormData();
4864
4865             // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4866             try {
4867                 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4868                 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4869                 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4870
4871                 // Wait until the processes have finished.
4872                 deleteWebDataProcess.waitFor();
4873                 deleteWebDataJournalProcess.waitFor();
4874             } catch (Exception exception) {
4875                 // Do nothing if an error is thrown.
4876             }
4877         }
4878
4879         // Clear the logcat.
4880         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4881             try {
4882                 // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
4883                 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4884
4885                 // Wait for the process to finish.
4886                 process.waitFor();
4887             } catch (IOException|InterruptedException exception) {
4888                 // Do nothing.
4889             }
4890         }
4891
4892         // Clear the cache.
4893         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
4894             // Clear the cache from each WebView.
4895             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4896                 // Get the WebView tab fragment.
4897                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4898
4899                 // Get the WebView fragment view.
4900                 View webViewFragmentView = webViewTabFragment.getView();
4901
4902                 // Only clear the cache if the WebView exists.
4903                 if (webViewFragmentView != null) {
4904                     // Get the nested scroll WebView from the tab fragment.
4905                     NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4906
4907                     // Clear the cache for this WebView.
4908                     nestedScrollWebView.clearCache(true);
4909                 }
4910             }
4911
4912             // Manually delete the cache directories.
4913             try {
4914                 // Delete the main cache directory.
4915                 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4916
4917                 // Delete the secondary `Service Worker` cache directory.
4918                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4919                 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
4920
4921                 // Wait until the processes have finished.
4922                 deleteCacheProcess.waitFor();
4923                 deleteServiceWorkerProcess.waitFor();
4924             } catch (Exception exception) {
4925                 // Do nothing if an error is thrown.
4926             }
4927         }
4928
4929         // Wipe out each WebView.
4930         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4931             // Get the WebView tab fragment.
4932             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4933
4934             // Get the WebView frame layout.
4935             FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4936
4937             // Only wipe out the WebView if it exists.
4938             if (webViewFrameLayout != null) {
4939                 // Get the nested scroll WebView from the tab fragment.
4940                 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4941
4942                 // Clear SSL certificate preferences for this WebView.
4943                 nestedScrollWebView.clearSslPreferences();
4944
4945                 // Clear the back/forward history for this WebView.
4946                 nestedScrollWebView.clearHistory();
4947
4948                 // Remove all the views from the frame layout.
4949                 webViewFrameLayout.removeAllViews();
4950
4951                 // Destroy the internal state of the WebView.
4952                 nestedScrollWebView.destroy();
4953             }
4954         }
4955
4956         // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4957         // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4958         if (clearEverything) {
4959             try {
4960                 // Delete the folder.
4961                 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4962
4963                 // Wait until the process has finished.
4964                 deleteAppWebviewProcess.waitFor();
4965             } catch (Exception exception) {
4966                 // Do nothing if an error is thrown.
4967             }
4968         }
4969
4970         // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4971         finishAndRemoveTask();
4972
4973         // Remove the terminated program from RAM.  The status code is `0`.
4974         System.exit(0);
4975     }
4976
4977     public void bookmarksBack(View view) {
4978         if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
4979             // close the bookmarks drawer.
4980             drawerLayout.closeDrawer(GravityCompat.END);
4981         } else {  // A subfolder is displayed.
4982             // Place the former parent folder in `currentFolder`.
4983             currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4984
4985             // Load the new folder.
4986             loadBookmarksFolder();
4987         }
4988     }
4989
4990     private void setCurrentWebView(int pageNumber) {
4991         // Stop the swipe to refresh indicator if it is running
4992         swipeRefreshLayout.setRefreshing(false);
4993
4994         // Get the WebView tab fragment.
4995         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4996
4997         // Get the fragment view.
4998         View webViewFragmentView = webViewTabFragment.getView();
4999
5000         // Set the current WebView if the fragment view is not null.
5001         if (webViewFragmentView != null) {  // The fragment has been populated.
5002             // Store the current WebView.
5003             currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
5004
5005             // Update the status of swipe to refresh.
5006             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
5007                 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
5008                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
5009             } else {  // Swipe to refresh is disabled.
5010                 // Disable the swipe refresh layout.
5011                 swipeRefreshLayout.setEnabled(false);
5012             }
5013
5014             // Get a handle for the cookie manager.
5015             CookieManager cookieManager = CookieManager.getInstance();
5016
5017             // Set the cookie status.
5018             cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
5019
5020             // Update the privacy icons.  `true` redraws the icons in the app bar.
5021             updatePrivacyIcons(true);
5022
5023             // Get a handle for the input method manager.
5024             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5025
5026             // Remove the lint warning below that the input method manager might be null.
5027             assert inputMethodManager != null;
5028
5029             // Get the current URL.
5030             String url = currentWebView.getUrl();
5031
5032             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5033             if (!loadingNewIntent) {  // A new intent is not being loaded.
5034                 if ((url == null) || url.equals("about:blank")) {  // The WebView is blank.
5035                     // Display the hint in the URL edit text.
5036                     urlEditText.setText("");
5037
5038                     // Request focus for the URL text box.
5039                     urlEditText.requestFocus();
5040
5041                     // Display the keyboard.
5042                     inputMethodManager.showSoftInput(urlEditText, 0);
5043                 } else {  // The WebView has a loaded URL.
5044                     // Clear the focus from the URL text box.
5045                     urlEditText.clearFocus();
5046
5047                     // Hide the soft keyboard.
5048                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5049
5050                     // Display the current URL in the URL text box.
5051                     urlEditText.setText(url);
5052
5053                     // Highlight the URL text.
5054                     highlightUrlText();
5055                 }
5056             } else {  // A new intent is being loaded.
5057                 // Reset the loading new intent tracker.
5058                 loadingNewIntent = false;
5059             }
5060
5061             // Set the background to indicate the domain settings status.
5062             if (currentWebView.getDomainSettingsApplied()) {
5063                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
5064                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
5065             } else {
5066                 // Remove any background on the URL relative layout.
5067                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5068             }
5069         } else {  // The fragment has not been populated.  Try again in 100 milliseconds.
5070             // Create a handler to set the current WebView.
5071             Handler setCurrentWebViewHandler = new Handler();
5072
5073             // Create a runnable to set the current WebView.
5074             Runnable setCurrentWebWebRunnable = () -> {
5075                 // Set the current WebView.
5076                 setCurrentWebView(pageNumber);
5077             };
5078
5079             // Try setting the current WebView again after 100 milliseconds.
5080             setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5081         }
5082     }
5083
5084     @SuppressLint("ClickableViewAccessibility")
5085     @Override
5086     public void initializeWebView(@NonNull NestedScrollWebView nestedScrollWebView, int pageNumber, @NonNull ProgressBar progressBar, @NonNull String url, boolean restoringState) {
5087         // Get a handle for the shared preferences.
5088         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5089
5090         // Get the WebView theme.
5091         String webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value));
5092
5093         // Get the WebView theme entry values string array.
5094         String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5095
5096         // Apply the WebView theme if supported by the installed WebView.
5097         if ((Build.VERSION.SDK_INT >= 33) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {  // The device is running API >= 33 and algorithmic darkening is supported.
5098             // Set the WebView them.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5099             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
5100                 // Turn off algorithmic darkening.
5101                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5102
5103                 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5104                 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5105                 nestedScrollWebView.setVisibility(View.VISIBLE);
5106             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
5107                 // Turn on algorithmic darkening.
5108                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5109             } else {
5110                 // The system default theme is selected.
5111                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5112
5113                 // Set the algorithmic darkening according to the current system theme status.
5114                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
5115                     // Turn off algorithmic darkening.
5116                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5117
5118                     // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5119                     // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5120                     nestedScrollWebView.setVisibility(View.VISIBLE);
5121                 } else {  // The system is in night mode.
5122                     // Turn on algorithmic darkening.
5123                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5124                 }
5125             }
5126         } else if ((Build.VERSION.SDK_INT < 33) && WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {  // The device is running API < 33 and the WebView supports force dark.
5127             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5128             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
5129                 // Turn off the WebView dark mode.
5130                 //noinspection deprecation
5131                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5132
5133                 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5134                 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5135                 nestedScrollWebView.setVisibility(View.VISIBLE);
5136             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
5137                 // Turn on the WebView dark mode.
5138                 //noinspection deprecation
5139                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5140             } else {  // The system default theme is selected.
5141                 // Get the current system theme status.
5142                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5143
5144                 // Set the WebView theme according to the current system theme status.
5145                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
5146                     // Turn off the WebView dark mode.
5147                     //noinspection deprecation
5148                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5149
5150                     // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5151                     // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5152                     nestedScrollWebView.setVisibility(View.VISIBLE);
5153                 } else {  // The system is in night mode.
5154                     // Turn on the WebView dark mode.
5155                     //noinspection deprecation
5156                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5157                 }
5158             }
5159         }
5160
5161         // Get a handle for the activity
5162         Activity activity = this;
5163
5164         // Get a handle for the input method manager.
5165         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5166
5167         // Instantiate the blocklist helper.
5168         BlocklistHelper blocklistHelper = new BlocklistHelper();
5169
5170         // Remove the lint warning below that the input method manager might be null.
5171         assert inputMethodManager != null;
5172
5173         // Set the app bar scrolling.
5174         nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5175
5176         // Allow pinch to zoom.
5177         nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5178
5179         // Hide zoom controls.
5180         nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5181
5182         // Don't allow mixed content (HTTP and HTTPS) on the same website.
5183         nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5184
5185         // Set the WebView to load in overview mode (zoomed out to the maximum width).
5186         nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5187
5188         // Explicitly disable geolocation.
5189         nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5190
5191         // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5192         nestedScrollWebView.getSettings().setAllowFileAccess(true);
5193
5194         // Create a double-tap gesture detector to toggle full-screen mode.
5195         GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5196             // Override `onDoubleTap()`.  All other events are handled using the default settings.
5197             @Override
5198             public boolean onDoubleTap(MotionEvent event) {
5199                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
5200                     // Toggle the full screen browsing mode tracker.
5201                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5202
5203                     // Toggle the full screen browsing mode.
5204                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
5205                         // Hide the app bar if specified.
5206                         if (hideAppBar) {  // The app bar is hidden.
5207                             // Close the find on page bar if it is visible.
5208                             closeFindOnPage(null);
5209
5210                             // Hide the tab linear layout.
5211                             tabsLinearLayout.setVisibility(View.GONE);
5212
5213                             // Hide the action bar.
5214                             actionBar.hide();
5215
5216                             // Set layout and scrolling parameters according to the position of the app bar.
5217                             if (bottomAppBar) {  // The app bar is at the bottom.
5218                                 // Reset the WebView padding to fill the available space.
5219                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5220                             } else {  // The app bar is at the top.
5221                                 // Check to see if the app bar is normally scrolled.
5222                                 if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5223                                     // Get the swipe refresh layout parameters.
5224                                     CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5225
5226                                     // Remove the off-screen scrolling layout.
5227                                     swipeRefreshLayoutParams.setBehavior(null);
5228                                 } else {  // The app bar is not scrolled when it is displayed.
5229                                     // Remove the padding from the top of the swipe refresh layout.
5230                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5231
5232                                     // The swipe refresh circle must be moved above the now removed status bar location.
5233                                     swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5234                                 }
5235                             }
5236                         } else {  // The app bar is not hidden.
5237                             // Adjust the UI for the bottom app bar.
5238                             if (bottomAppBar) {
5239                                 // Adjust the UI according to the scrolling of the app bar.
5240                                 if (scrollAppBar) {
5241                                     // Reset the WebView padding to fill the available space.
5242                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5243                                 } else {
5244                                     // Move the WebView above the app bar layout.
5245                                     swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5246                                 }
5247                             }
5248                         }
5249
5250                         /* Hide the system bars.
5251                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5252                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5253                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5254                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5255                          */
5256                         rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5257                                 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5258                     } else {  // Switch to normal viewing mode.
5259                         // Show the app bar if it was hidden.
5260                         if (hideAppBar) {
5261                             // Show the tab linear layout.
5262                             tabsLinearLayout.setVisibility(View.VISIBLE);
5263
5264                             // Show the action bar.
5265                             actionBar.show();
5266                         }
5267
5268                         // Set layout and scrolling parameters according to the position of the app bar.
5269                         if (bottomAppBar) {  // The app bar is at the bottom.
5270                             // Adjust the UI.
5271                             if (scrollAppBar) {
5272                                 // Reset the WebView padding to fill the available space.
5273                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5274                             } else {
5275                                 // Move the WebView above the app bar layout.
5276                                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5277                             }
5278                         } else {  // The app bar is at the top.
5279                             // Check to see if the app bar is normally scrolled.
5280                             if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5281                                 // Get the swipe refresh layout parameters.
5282                                 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5283
5284                                 // Add the off-screen scrolling layout.
5285                                 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5286                             } else {  // The app bar is not scrolled when it is displayed.
5287                                 // The swipe refresh layout must be manually moved below the app bar layout.
5288                                 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5289
5290                                 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5291                                 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5292                             }
5293                         }
5294
5295                         // Remove the `SYSTEM_UI` flags from the root frame layout.
5296                         rootFrameLayout.setSystemUiVisibility(0);
5297                     }
5298
5299                     // Consume the double-tap.
5300                     return true;
5301                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5302                     return false;
5303                 }
5304             }
5305
5306             @Override
5307             public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5308                 // Scroll the bottom app bar if enabled.
5309                 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5310                     // Calculate the Y change.
5311                     float motionY = motionEvent2.getY() - motionEvent1.getY();
5312
5313                     // Scroll the app bar if the change is greater than 50 pixels.
5314                     if (motionY > 50) {
5315                         // Animate the bottom app bar onto the screen.
5316                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5317                     } else if (motionY < -50) {
5318                         // Animate the bottom app bar off the screen.
5319                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5320                     }
5321
5322                     // Make it so.
5323                     objectAnimator.start();
5324                 }
5325
5326                 // Do not consume the event.
5327                 return false;
5328             }
5329         });
5330
5331         // Pass all touch events on the WebView through the double-tap gesture detector.
5332         nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5333             // Call `performClick()` on the view, which is required for accessibility.
5334             view.performClick();
5335
5336             // Send the event to the gesture detector.
5337             return doubleTapGestureDetector.onTouchEvent(event);
5338         });
5339
5340         // Register the WebView for a context menu.  This is used to see link targets and download images.
5341         registerForContextMenu(nestedScrollWebView);
5342
5343         // Allow the downloading of files.
5344         nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5345             // Check the download preference.
5346             if (downloadWithExternalApp) {  // Download with an external app.
5347                 downloadUrlWithExternalApp(downloadUrl);
5348             } else {  // Handle the download inside of Privacy Browser.
5349                 // Define a formatted file size string.
5350                 String formattedFileSizeString;
5351
5352                 // Process the content length if it contains data.
5353                 if (contentLength > 0) {  // The content length is greater than 0.
5354                     // Format the content length as a string.
5355                     formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5356                 } else {  // The content length is not greater than 0.
5357                     // Set the formatted file size string to be `unknown size`.
5358                     formattedFileSizeString = getString(R.string.unknown_size);
5359                 }
5360
5361                 // Get the file name from the content disposition.
5362                 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5363
5364                 // Instantiate the save dialog.
5365                 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5366                         nestedScrollWebView.getAcceptCookies());
5367
5368                 // Try to show the dialog.  The download listener continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
5369                 try {
5370                     // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
5371                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5372                 } catch (Exception exception) {  // The dialog could not be shown.
5373                     // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5374                     pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5375                 }
5376             }
5377         });
5378
5379         // Update the find on page count.
5380         nestedScrollWebView.setFindListener(new WebView.FindListener() {
5381             // Get a handle for `findOnPageCountTextView`.
5382             final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5383
5384             @Override
5385             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5386                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
5387                     // Set `findOnPageCountTextView` to `0/0`.
5388                     findOnPageCountTextView.setText(R.string.zero_of_zero);
5389                 } else if (isDoneCounting) {  // There are matches.
5390                     // `activeMatchOrdinal` is zero-based.
5391                     int activeMatch = activeMatchOrdinal + 1;
5392
5393                     // Build the match string.
5394                     String matchString = activeMatch + "/" + numberOfMatches;
5395
5396                     // Set `findOnPageCountTextView`.
5397                     findOnPageCountTextView.setText(matchString);
5398                 }
5399             }
5400         });
5401
5402         // Process scroll changes.
5403         nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5404             // Set the swipe to refresh status.
5405             if (nestedScrollWebView.getSwipeToRefresh()) {
5406                 // Only enable swipe to refresh if the WebView is scrolled to the top.
5407                 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5408             } else {
5409                 // Disable swipe to refresh.
5410                 swipeRefreshLayout.setEnabled(false);
5411             }
5412
5413             // Reinforce the system UI visibility flags if in full screen browsing mode.
5414             // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5415             if (inFullScreenBrowsingMode) {
5416                 /* Hide the system bars.
5417                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5418                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5419                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5420                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5421                  */
5422                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5423                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5424             }
5425         });
5426
5427         // Set the web chrome client.
5428         nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5429             // Update the progress bar when a page is loading.
5430             @Override
5431             public void onProgressChanged(WebView view, int progress) {
5432                 // Update the progress bar.
5433                 progressBar.setProgress(progress);
5434
5435                 // Set the visibility of the progress bar.
5436                 if (progress < 100) {
5437                     // Show the progress bar.
5438                     progressBar.setVisibility(View.VISIBLE);
5439                 } else {
5440                     // Hide the progress bar.
5441                     progressBar.setVisibility(View.GONE);
5442
5443                     //Stop the swipe to refresh indicator if it is running
5444                     swipeRefreshLayout.setRefreshing(false);
5445
5446                     // Make the current WebView visible.  If this is a new tab, the current WebView would have been created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5447                     nestedScrollWebView.setVisibility(View.VISIBLE);
5448                 }
5449             }
5450
5451             // Set the favorite icon when it changes.
5452             @Override
5453             public void onReceivedIcon(WebView view, Bitmap icon) {
5454                 // Only update the favorite icon if the website has finished loading.
5455                 if (progressBar.getVisibility() == View.GONE) {
5456                     // Store the new favorite icon.
5457                     nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5458
5459                     // Get the current page position.
5460                     int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5461
5462                     // Get the current tab.
5463                     TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5464
5465                     // Check to see if the tab has been populated.
5466                     if (tab != null) {
5467                         // Get the custom view from the tab.
5468                         View tabView = tab.getCustomView();
5469
5470                         // Check to see if the custom tab view has been populated.
5471                         if (tabView != null) {
5472                             // Get the favorite icon image view from the tab.
5473                             ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5474
5475                             // Display the favorite icon in the tab.
5476                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5477                         }
5478                     }
5479                 }
5480             }
5481
5482             // Save a copy of the title when it changes.
5483             @Override
5484             public void onReceivedTitle(WebView view, String title) {
5485                 // Get the current page position.
5486                 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5487
5488                 // Get the current tab.
5489                 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5490
5491                 // Only populate the title text view if the tab has been fully created.
5492                 if (tab != null) {
5493                     // Get the custom view from the tab.
5494                     View tabView = tab.getCustomView();
5495
5496                     // Only populate the title text view if the tab view has been fully populated.
5497                     if (tabView != null) {
5498                         // Get the title text view from the tab.
5499                         TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5500
5501                         // Set the title according to the URL.
5502                         if (title.equals("about:blank")) {
5503                             // Set the title to indicate a new tab.
5504                             tabTitleTextView.setText(R.string.new_tab);
5505                         } else {
5506                             // Set the title as the tab text.
5507                             tabTitleTextView.setText(title);
5508                         }
5509                     }
5510                 }
5511             }
5512
5513             // Enter full screen video.
5514             @Override
5515             public void onShowCustomView(View video, CustomViewCallback callback) {
5516                 // Set the full screen video flag.
5517                 displayingFullScreenVideo = true;
5518
5519                 // Hide the keyboard.
5520                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5521
5522                 // Hide the coordinator layout.
5523                 coordinatorLayout.setVisibility(View.GONE);
5524
5525                 /* Hide the system bars.
5526                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5527                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5528                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5529                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5530                  */
5531                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5532                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5533
5534                 // Disable the sliding drawers.
5535                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5536
5537                 // Add the video view to the full screen video frame layout.
5538                 fullScreenVideoFrameLayout.addView(video);
5539
5540                 // Show the full screen video frame layout.
5541                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5542
5543                 // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
5544                 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5545             }
5546
5547             // Exit full screen video.
5548             @Override
5549             public void onHideCustomView() {
5550                 // Exit the full screen video.
5551                 exitFullScreenVideo();
5552             }
5553
5554             // Upload files.
5555             @Override
5556             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5557                 // Store the file path callback.
5558                 fileChooserCallback = filePathCallback;
5559
5560                 // Create an intent to open a chooser based on the file chooser parameters.
5561                 Intent fileChooserIntent = fileChooserParams.createIntent();
5562
5563                 // Get a handle for the package manager.
5564                 PackageManager packageManager = getPackageManager();
5565
5566                 // Check to see if the file chooser intent resolves to an installed package.
5567                 if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
5568                     // Start the file chooser intent.
5569                     startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5570                 } else {  // The file chooser intent will cause a crash.
5571                     // Create a generic intent to open a chooser.
5572                     Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5573
5574                     // Request an openable file.
5575                     genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5576
5577                     // Set the file type to everything.
5578                     genericFileChooserIntent.setType("*/*");
5579
5580                     // Start the generic file chooser intent.
5581                     startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5582                 }
5583                 return true;
5584             }
5585         });
5586
5587         nestedScrollWebView.setWebViewClient(new WebViewClient() {
5588             // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5589             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5590             @Override
5591             public boolean shouldOverrideUrlLoading(WebView view, String url) {
5592                 // Sanitize the url.
5593                 url = sanitizeUrl(url);
5594
5595                 // Handle the URL according to the type.
5596                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
5597                     // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5598                     loadUrl(nestedScrollWebView, url);
5599
5600                     // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5601                     // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5602                     return true;
5603                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
5604                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5605                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5606
5607                     // Parse the url and set it as the data for the intent.
5608                     emailIntent.setData(Uri.parse(url));
5609
5610                     // Open the email program in a new task instead of as part of Privacy Browser.
5611                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5612
5613                     try {
5614                         // Make it so.
5615                         startActivity(emailIntent);
5616                     } catch (ActivityNotFoundException exception) {
5617                         // Display a snackbar.
5618                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5619                     }
5620
5621
5622                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5623                     return true;
5624                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
5625                     // Open the dialer and load the phone number, but wait for the user to place the call.
5626                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5627
5628                     // Add the phone number to the intent.
5629                     dialIntent.setData(Uri.parse(url));
5630
5631                     // Open the dialer in a new task instead of as part of Privacy Browser.
5632                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5633
5634                     try {
5635                         // Make it so.
5636                         startActivity(dialIntent);
5637                     } catch (ActivityNotFoundException exception) {
5638                         // Display a snackbar.
5639                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5640                     }
5641
5642                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5643                     return true;
5644                 } else {  // Load a system chooser to select an app that can handle the URL.
5645                     // Open an app that can handle the URL.
5646                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5647
5648                     // Add the URL to the intent.
5649                     genericIntent.setData(Uri.parse(url));
5650
5651                     // List all apps that can handle the URL instead of just opening the first one.
5652                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5653
5654                     // Open the app in a new task instead of as part of Privacy Browser.
5655                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5656
5657                     // Start the app or display a snackbar if no app is available to handle the URL.
5658                     try {
5659                         startActivity(genericIntent);
5660                     } catch (ActivityNotFoundException exception) {
5661                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
5662                     }
5663
5664                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5665                     return true;
5666                 }
5667             }
5668
5669             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5670             @Override
5671             public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5672                 // Get the URL.
5673                 String url = webResourceRequest.getUrl().toString();
5674
5675                 // Check to see if the resource request is for the main URL.
5676                 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5677                     // `return null` loads the resource request, which should never be blocked if it is the main URL.
5678                     return null;
5679                 }
5680
5681                 // Wait until the blocklists have been populated.  When Privacy Browser is being resumed after having the process killed in the background it will try to load the URLs immediately.
5682                 while (ultraPrivacy == null) {
5683                     // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5684                     synchronized (this) {
5685                         try {
5686                             // Check to see if the blocklists have been populated after 100 ms.
5687                             wait(100);
5688                         } catch (InterruptedException exception) {
5689                             // Do nothing.
5690                         }
5691                     }
5692                 }
5693
5694                 // Create an empty web resource response to be used if the resource request is blocked.
5695                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5696
5697                 // Reset the whitelist results tracker.
5698                 String[] whitelistResultStringArray = null;
5699
5700                 // Initialize the third party request tracker.
5701                 boolean isThirdPartyRequest = false;
5702
5703                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5704                 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5705
5706                 // Store a copy of the current domain for use in later requests.
5707                 String currentDomain = currentBaseDomain;
5708
5709                 // Get the request host name.
5710                 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5711
5712                 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5713                 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5714                     // Determine the current base domain.
5715                     while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5716                         // Remove the first subdomain.
5717                         currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5718                     }
5719
5720                     // Determine the request base domain.
5721                     while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5722                         // Remove the first subdomain.
5723                         requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5724                     }
5725
5726                     // Update the third party request tracker.
5727                     isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5728                 }
5729
5730                 // Get the current WebView page position.
5731                 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5732
5733                 // Determine if the WebView is currently displayed.
5734                 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5735
5736                 // Block third-party requests if enabled.
5737                 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5738                     // Add the result to the resource requests.
5739                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5740
5741                     // Increment the blocked requests counters.
5742                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5743                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5744
5745                     // Update the titles of the blocklist menu items if the WebView is currently displayed.
5746                     if (webViewDisplayed) {
5747                         // Updating the UI must be run from the UI thread.
5748                         activity.runOnUiThread(() -> {
5749                             // Update the menu item titles.
5750                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5751
5752                             // Update the options menu if it has been populated.
5753                             if (optionsMenu != null) {
5754                                 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5755                                 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5756                                         getString(R.string.block_all_third_party_requests));
5757                             }
5758                         });
5759                     }
5760
5761                     // Return an empty web resource response.
5762                     return emptyWebResourceResponse;
5763                 }
5764
5765                 // Check UltraList if it is enabled.
5766                 if (nestedScrollWebView.getUltraListEnabled()) {
5767                     // Check the URL against UltraList.
5768                     String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5769
5770                     // Process the UltraList results.
5771                     if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraList's blacklist.
5772                         // Add the result to the resource requests.
5773                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5774
5775                         // Increment the blocked requests counters.
5776                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5777                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5778
5779                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5780                         if (webViewDisplayed) {
5781                             // Updating the UI must be run from the UI thread.
5782                             activity.runOnUiThread(() -> {
5783                                 // Update the menu item titles.
5784                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5785
5786                                 // Update the options menu if it has been populated.
5787                                 if (optionsMenu != null) {
5788                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5789                                     optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5790                                 }
5791                             });
5792                         }
5793
5794                         // The resource request was blocked.  Return an empty web resource response.
5795                         return emptyWebResourceResponse;
5796                     } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraList's whitelist.
5797                         // Add a whitelist entry to the resource requests array.
5798                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5799
5800                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5801                         return null;
5802                     }
5803                 }
5804
5805                 // Check UltraPrivacy if it is enabled.
5806                 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5807                     // Check the URL against UltraPrivacy.
5808                     String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5809
5810                     // Process the UltraPrivacy results.
5811                     if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraPrivacy's blacklist.
5812                         // Add the result to the resource requests.
5813                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5814                                 ultraPrivacyResults[5]});
5815
5816                         // Increment the blocked requests counters.
5817                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5818                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5819
5820                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5821                         if (webViewDisplayed) {
5822                             // Updating the UI must be run from the UI thread.
5823                             activity.runOnUiThread(() -> {
5824                                 // Update the menu item titles.
5825                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5826
5827                                 // Update the options menu if it has been populated.
5828                                 if (optionsMenu != null) {
5829                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5830                                     optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5831                                 }
5832                             });
5833                         }
5834
5835                         // The resource request was blocked.  Return an empty web resource response.
5836                         return emptyWebResourceResponse;
5837                     } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraPrivacy's whitelist.
5838                         // Add a whitelist entry to the resource requests array.
5839                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5840                                 ultraPrivacyResults[5]});
5841
5842                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5843                         return null;
5844                     }
5845                 }
5846
5847                 // Check EasyList if it is enabled.
5848                 if (nestedScrollWebView.getEasyListEnabled()) {
5849                     // Check the URL against EasyList.
5850                     String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5851
5852                     // Process the EasyList results.
5853                     if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyList's blacklist.
5854                         // Add the result to the resource requests.
5855                         nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5856
5857                         // Increment the blocked requests counters.
5858                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5859                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5860
5861                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5862                         if (webViewDisplayed) {
5863                             // Updating the UI must be run from the UI thread.
5864                             activity.runOnUiThread(() -> {
5865                                 // Update the menu item titles.
5866                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5867
5868                                 // Update the options menu if it has been populated.
5869                                 if (optionsMenu != null) {
5870                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5871                                     optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5872                                 }
5873                             });
5874                         }
5875
5876                         // The resource request was blocked.  Return an empty web resource response.
5877                         return emptyWebResourceResponse;
5878                     } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyList's whitelist.
5879                         // Update the whitelist result string array tracker.
5880                         whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5881                     }
5882                 }
5883
5884                 // Check EasyPrivacy if it is enabled.
5885                 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5886                     // Check the URL against EasyPrivacy.
5887                     String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5888
5889                     // Process the EasyPrivacy results.
5890                     if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyPrivacy's blacklist.
5891                         // Add the result to the resource requests.
5892                         nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5893                                 easyPrivacyResults[5]});
5894
5895                         // Increment the blocked requests counters.
5896                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5897                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5898
5899                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5900                         if (webViewDisplayed) {
5901                             // Updating the UI must be run from the UI thread.
5902                             activity.runOnUiThread(() -> {
5903                                 // Update the menu item titles.
5904                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5905
5906                                 // Update the options menu if it has been populated.
5907                                 if (optionsMenu != null) {
5908                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5909                                     optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5910                                 }
5911                             });
5912                         }
5913
5914                         // The resource request was blocked.  Return an empty web resource response.
5915                         return emptyWebResourceResponse;
5916                     } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyPrivacy's whitelist.
5917                         // Update the whitelist result string array tracker.
5918                         whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5919                     }
5920                 }
5921
5922                 // Check Fanboy’s Annoyance List if it is enabled.
5923                 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5924                     // Check the URL against Fanboy's Annoyance List.
5925                     String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5926
5927                     // Process the Fanboy's Annoyance List results.
5928                     if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Annoyance List's blacklist.
5929                         // Add the result to the resource requests.
5930                         nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5931                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5932
5933                         // Increment the blocked requests counters.
5934                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5935                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5936
5937                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5938                         if (webViewDisplayed) {
5939                             // Updating the UI must be run from the UI thread.
5940                             activity.runOnUiThread(() -> {
5941                                 // Update the menu item titles.
5942                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5943
5944                                 // Update the options menu if it has been populated.
5945                                 if (optionsMenu != null) {
5946                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5947                                     optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5948                                             getString(R.string.fanboys_annoyance_list));
5949                                 }
5950                             });
5951                         }
5952
5953                         // The resource request was blocked.  Return an empty web resource response.
5954                         return emptyWebResourceResponse;
5955                     } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){  // The resource request matched Fanboy's Annoyance List's whitelist.
5956                         // Update the whitelist result string array tracker.
5957                         whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5958                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5959                     }
5960                 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5961                     // Check the URL against Fanboy's Annoyance List.
5962                     String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5963
5964                     // Process the Fanboy's Social Blocking List results.
5965                     if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
5966                         // Add the result to the resource requests.
5967                         nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5968                                 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5969
5970                         // Increment the blocked requests counters.
5971                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5972                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5973
5974                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5975                         if (webViewDisplayed) {
5976                             // Updating the UI must be run from the UI thread.
5977                             activity.runOnUiThread(() -> {
5978                                 // Update the menu item titles.
5979                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5980
5981                                 // Update the options menu if it has been populated.
5982                                 if (optionsMenu != null) {
5983                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5984                                     optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5985                                             getString(R.string.fanboys_social_blocking_list));
5986                                 }
5987                             });
5988                         }
5989
5990                         // The resource request was blocked.  Return an empty web resource response.
5991                         return emptyWebResourceResponse;
5992                     } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
5993                         // Update the whitelist result string array tracker.
5994                         whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5995                                 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5996                     }
5997                 }
5998
5999                 // Add the request to the log because it hasn't been processed by any of the previous checks.
6000                 if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
6001                     nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
6002                 } else {  // The request didn't match any blocklist entry.  Log it as a default request.
6003                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
6004                 }
6005
6006                 // The resource request has not been blocked.  `return null` loads the requested resource.
6007                 return null;
6008             }
6009
6010             // Handle HTTP authentication requests.
6011             @Override
6012             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
6013                 // Store the handler.
6014                 nestedScrollWebView.setHttpAuthHandler(handler);
6015
6016                 // Instantiate an HTTP authentication dialog.
6017                 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
6018
6019                 // Show the HTTP authentication dialog.
6020                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
6021             }
6022
6023             @Override
6024             public void onPageStarted(WebView view, String url, Bitmap favicon) {
6025                 // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
6026                 // This should only be populated if it is greater than 0 because otherwise it will be reset to 0 if the app bar is hidden in full screen browsing mode.
6027                 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
6028
6029                 // Set the padding and layout settings according to the position of the app bar.
6030                 if (bottomAppBar) {  // The app bar is on the bottom.
6031                     // Adjust the UI.
6032                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
6033                         // Reset the WebView padding to fill the available space.
6034                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
6035                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
6036                         // Move the WebView above the app bar layout.
6037                         swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
6038                     }
6039                 } else {  // The app bar is on the top.
6040                     // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.  This can't be done in `appAppSettings()` because the app bar is not yet populated there.
6041                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
6042                         // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
6043                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
6044
6045                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6046                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
6047                     } else {
6048                         // The swipe refresh layout must be manually moved below the app bar layout.
6049                         swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
6050
6051                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
6052                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
6053                     }
6054                 }
6055
6056                 // Reset the list of resource requests.
6057                 nestedScrollWebView.clearResourceRequests();
6058
6059                 // Reset the requests counters.
6060                 nestedScrollWebView.resetRequestsCounters();
6061
6062                 // Get the current page position.
6063                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6064
6065                 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
6066                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6067                     // Display the formatted URL text.
6068                     urlEditText.setText(url);
6069
6070                     // Apply text highlighting to the URL text box.
6071                     highlightUrlText();
6072
6073                     // Hide the keyboard.
6074                     inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6075                 }
6076
6077                 // Reset the list of host IP addresses.
6078                 nestedScrollWebView.setCurrentIpAddresses("");
6079
6080                 // Get a URI for the current URL.
6081                 Uri currentUri = Uri.parse(url);
6082
6083                 // Get the IP addresses for the host.
6084                 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6085
6086                 // Replace Refresh with Stop if the options menu has been created.  (The first WebView typically begins loading before the menu items are instantiated.)
6087                 if (optionsMenu != null) {
6088                     // Set the title.
6089                     optionsRefreshMenuItem.setTitle(R.string.stop);
6090
6091                     // Set the icon if it is displayed in the AppBar.
6092                     if (displayAdditionalAppBarIcons)
6093                         optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
6094                 }
6095             }
6096
6097             @Override
6098             public void onPageFinished(WebView view, String url) {
6099                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
6100                 if (nestedScrollWebView.getAcceptCookies()) {
6101                     CookieManager.getInstance().flush();
6102                 }
6103
6104                 // Update the Refresh menu item if the options menu has been created.
6105                 if (optionsMenu != null) {
6106                     // Reset the Refresh title.
6107                     optionsRefreshMenuItem.setTitle(R.string.refresh);
6108
6109                     // Reset the icon if it is displayed in the app bar.
6110                     if (displayAdditionalAppBarIcons)
6111                         optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
6112                 }
6113
6114                  // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6115                 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6116                 String privateDataDirectoryString = getApplicationInfo().dataDir;
6117
6118                 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6119                 if (incognitoModeEnabled) {
6120                     // Clear the cache.  `true` includes disk files.
6121                     nestedScrollWebView.clearCache(true);
6122
6123                     // Clear the back/forward history.
6124                     nestedScrollWebView.clearHistory();
6125
6126                     // Manually delete cache folders.
6127                     try {
6128                         // Delete the main cache directory.
6129                         Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6130                     } catch (IOException exception) {
6131                         // Do nothing if an error is thrown.
6132                     }
6133
6134                     // Clear the logcat.
6135                     try {
6136                         // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
6137                         Runtime.getRuntime().exec("logcat -b all -c");
6138                     } catch (IOException exception) {
6139                         // Do nothing.
6140                     }
6141                 }
6142
6143                 // Clear the `Service Worker` directory.
6144                 try {
6145                     // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6146                     Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
6147                 } catch (IOException exception) {
6148                     // Do nothing.
6149                 }
6150
6151                 // Get the current page position.
6152                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6153
6154                 // Get the current URL from the nested scroll WebView.  This is more accurate than using the URL passed into the method, which is sometimes not the final one.
6155                 String currentUrl = nestedScrollWebView.getUrl();
6156
6157                 // Get the current tab.
6158                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6159
6160                 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6161                 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6162                 // Probably some sort of race condition when Privacy Browser is being resumed.
6163                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6164                     // Check to see if the URL is `about:blank`.
6165                     if (currentUrl.equals("about:blank")) {  // The WebView is blank.
6166                         // Display the hint in the URL edit text.
6167                         urlEditText.setText("");
6168
6169                         // Request focus for the URL text box.
6170                         urlEditText.requestFocus();
6171
6172                         // Display the keyboard.
6173                         inputMethodManager.showSoftInput(urlEditText, 0);
6174
6175                         // Apply the domain settings.  This clears any settings from the previous domain.
6176                         applyDomainSettings(nestedScrollWebView, "", true, false, false);
6177
6178                         // Only populate the title text view if the tab has been fully created.
6179                         if (tab != null) {
6180                             // Get the custom view from the tab.
6181                             View tabView = tab.getCustomView();
6182
6183                             // Remove the incorrect warning below that the current tab view might be null.
6184                             assert tabView != null;
6185
6186                             // Get the title text view from the tab.
6187                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6188
6189                             // Set the title as the tab text.
6190                             tabTitleTextView.setText(R.string.new_tab);
6191                         }
6192                     } else {  // The WebView has loaded a webpage.
6193                         // Update the URL edit text if it is not currently being edited.
6194                         if (!urlEditText.hasFocus()) {
6195                             // Sanitize the current URL.  This removes unwanted URL elements that were added by redirects, so that they won't be included if the URL is shared.
6196                             String sanitizedUrl = sanitizeUrl(currentUrl);
6197
6198                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6199                             urlEditText.setText(sanitizedUrl);
6200
6201                             // Apply text highlighting to the URL.
6202                             highlightUrlText();
6203                         }
6204
6205                         // Only populate the title text view if the tab has been fully created.
6206                         if (tab != null) {
6207                             // Get the custom view from the tab.
6208                             View tabView = tab.getCustomView();
6209
6210                             // Remove the incorrect warning below that the current tab view might be null.
6211                             assert tabView != null;
6212
6213                             // Get the title text view from the tab.
6214                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6215
6216                             // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6217                             tabTitleTextView.setText(nestedScrollWebView.getTitle());
6218                         }
6219                     }
6220                 }
6221             }
6222
6223             // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
6224             @SuppressLint("WebViewClientOnReceivedSslError")
6225             @Override
6226             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6227                 // Get the current website SSL certificate.
6228                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6229
6230                 // Extract the individual pieces of information from the current website SSL certificate.
6231                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6232                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6233                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6234                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6235                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6236                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6237                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6238                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6239
6240                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6241                 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6242                     // Get the pinned SSL certificate.
6243                     Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6244
6245                     // Extract the arrays from the array list.
6246                     String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6247                     Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6248
6249                     // Check if the current SSL certificate matches the pinned certificate.
6250                     if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6251                         currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6252                         currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6253                         currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6254
6255                         // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
6256                         handler.proceed();
6257                     }
6258                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6259                     // Store the SSL error handler.
6260                     nestedScrollWebView.setSslErrorHandler(handler);
6261
6262                     // Instantiate an SSL certificate error alert dialog.
6263                     DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6264
6265                     // Try to show the dialog.  The SSL error handler continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
6266                     try {
6267                         // Show the SSL certificate error dialog.
6268                         sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6269                     } catch (Exception exception) {
6270                         // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
6271                         pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6272                     }
6273                 }
6274             }
6275         });
6276
6277         // Check to see if the state is being restored.
6278         if (restoringState) {  // The state is being restored.
6279             // Resume the nested scroll WebView JavaScript timers.
6280             nestedScrollWebView.resumeTimers();
6281         } else if (pageNumber == 0) {  // The first page is being loaded.
6282             // Set this nested scroll WebView as the current WebView.
6283             currentWebView = nestedScrollWebView;
6284
6285             // Initialize the URL to load string.
6286             String urlToLoadString;
6287
6288             // Get the intent that started the app.
6289             Intent launchingIntent = getIntent();
6290
6291             // Reset the intent.  This prevents a duplicate tab from being created on restart.
6292             setIntent(new Intent());
6293
6294             // Get the information from the intent.
6295             String launchingIntentAction = launchingIntent.getAction();
6296             Uri launchingIntentUriData = launchingIntent.getData();
6297             String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6298
6299             // Parse the launching intent URL.
6300             if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
6301                 // Create an encoded URL string.
6302                 String encodedUrlString;
6303
6304                 // Sanitize the search input and convert it to a search.
6305                 try {
6306                     encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6307                 } catch (UnsupportedEncodingException exception) {
6308                     encodedUrlString = "";
6309                 }
6310
6311                 // Store the web search as the URL to load.
6312                 urlToLoadString = searchURL + encodedUrlString;
6313             } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
6314                 // Store the URI as a URL.
6315                 urlToLoadString = launchingIntentUriData.toString();
6316             } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
6317                 // Store the URL.
6318                 urlToLoadString = launchingIntentStringExtra;
6319             } else if (!url.equals("")) {  // The activity has been restarted.
6320                 // Load the saved URL.
6321                 urlToLoadString = url;
6322             } else {  // The is no URL in the intent.
6323                 // Store the homepage to be loaded.
6324                 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6325             }
6326
6327             // Load the website if not waiting for the proxy.
6328             if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
6329                 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6330             } else {  // Load the URL.
6331                 loadUrl(nestedScrollWebView, urlToLoadString);
6332             }
6333
6334             // Reset the intent.  This prevents a duplicate tab from being created on a subsequent restart if loading an link from a new intent on restart.
6335             // For example, this prevents a duplicate tab if a link is loaded from the Guide after changing the theme in the guide and then changing the theme again in the main activity.
6336             setIntent(new Intent());
6337         } else {  // This is not the first tab.
6338             // Load the URL.
6339             loadUrl(nestedScrollWebView, url);
6340
6341             // Set the focus and display the keyboard if the URL is blank.
6342             if (url.equals("")) {
6343                 // Request focus for the URL text box.
6344                 urlEditText.requestFocus();
6345
6346                 // Create a display keyboard handler.
6347                 Handler displayKeyboardHandler = new Handler();
6348
6349                 // Create a display keyboard runnable.
6350                 Runnable displayKeyboardRunnable = () -> {
6351                     // Display the keyboard.
6352                     inputMethodManager.showSoftInput(urlEditText, 0);
6353                 };
6354
6355                 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6356                 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);
6357             }
6358         }
6359     }
6360 }