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