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