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