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