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