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