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