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