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