]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
a363ef1dc718de05fdbe46e28d7000064969d5ee
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2019 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DownloadManager;
28 import android.app.SearchManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.text.Editable;
56 import android.text.Spanned;
57 import android.text.TextWatcher;
58 import android.text.style.ForegroundColorSpan;
59 import android.util.Patterns;
60 import android.view.ContextMenu;
61 import android.view.GestureDetector;
62 import android.view.KeyEvent;
63 import android.view.Menu;
64 import android.view.MenuItem;
65 import android.view.MotionEvent;
66 import android.view.View;
67 import android.view.ViewGroup;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.HttpAuthHandler;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.ValueCallback;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebSettings;
77 import android.webkit.WebStorage;
78 import android.webkit.WebView;
79 import android.webkit.WebViewClient;
80 import android.webkit.WebViewDatabase;
81 import android.widget.ArrayAdapter;
82 import android.widget.CursorAdapter;
83 import android.widget.EditText;
84 import android.widget.FrameLayout;
85 import android.widget.ImageView;
86 import android.widget.LinearLayout;
87 import android.widget.ListView;
88 import android.widget.ProgressBar;
89 import android.widget.RadioButton;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
92
93 import androidx.annotation.NonNull;
94 import androidx.appcompat.app.ActionBar;
95 import androidx.appcompat.app.ActionBarDrawerToggle;
96 import androidx.appcompat.app.AppCompatActivity;
97 import androidx.appcompat.widget.Toolbar;
98 import androidx.core.app.ActivityCompat;
99 import androidx.core.content.ContextCompat;
100 import androidx.core.view.GravityCompat;
101 import androidx.drawerlayout.widget.DrawerLayout;
102 import androidx.fragment.app.DialogFragment;
103 import androidx.fragment.app.FragmentManager;
104 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
105 import androidx.viewpager.widget.ViewPager;
106
107 import com.google.android.material.floatingactionbutton.FloatingActionButton;
108 import com.google.android.material.navigation.NavigationView;
109 import com.google.android.material.snackbar.Snackbar;
110 import com.google.android.material.tabs.TabLayout;
111
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
115 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
116 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
118 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
120 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
121 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
122 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
123 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
124 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
125 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
126 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
127 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
128 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
129 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
130 import com.stoutner.privacybrowser.helpers.AdHelper;
131 import com.stoutner.privacybrowser.helpers.BlockListHelper;
132 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
133 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
134 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
135 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
136 import com.stoutner.privacybrowser.views.NestedScrollWebView;
137
138 import java.io.ByteArrayInputStream;
139 import java.io.ByteArrayOutputStream;
140 import java.io.File;
141 import java.io.IOException;
142 import java.io.UnsupportedEncodingException;
143 import java.net.MalformedURLException;
144 import java.net.URL;
145 import java.net.URLDecoder;
146 import java.net.URLEncoder;
147 import java.util.ArrayList;
148 import java.util.Date;
149 import java.util.HashMap;
150 import java.util.HashSet;
151 import java.util.List;
152 import java.util.Map;
153 import java.util.Set;
154
155 // TODO.  New tabs are white in dark mode.
156
157 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
158 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
159         DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
160         EditBookmarkFolderDialog.EditBookmarkFolderListener, NavigationView.OnNavigationItemSelectedListener, WebViewTabFragment.NewTabListener {
161
162     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
163     public static String orbotStatus;
164
165     // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`.  It is also used in `onCreate()`, `onResume()`, and `addTab()`.
166     public static WebViewPagerAdapter webViewPagerAdapter;
167
168     // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`.  They are used in `onRestart()`.
169     public static boolean loadUrlOnRestart;
170     public static String urlToLoadOnRestart;
171
172     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
173     public static boolean restartFromBookmarksActivity;
174
175     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
176     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
177     public static String currentBookmarksFolder;
178
179     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
180     public final static int UNRECOGNIZED_USER_AGENT = -1;
181     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
182     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
183     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
184     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
185     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
186
187
188
189     // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
190     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxyThroughOrbot()`, and `applyDomainSettings()`.
191     private NestedScrollWebView currentWebView;
192
193     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
194     private final Map<String, String> customHeaders = new HashMap<>();
195
196     // The search URL is set in `applyProxyThroughOrbot()` and used in `onCreate()`, `onNewIntent()`, `loadURLFromTextBox()`, and `initializeWebView()`.
197     private String searchURL;
198
199     // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
200     private Menu optionsMenu;
201
202     // The blocklists are populated in `onCreate()` and accessed from `initializeWebView()`.
203     private ArrayList<List<String[]>> easyList;
204     private ArrayList<List<String[]>> easyPrivacy;
205     private ArrayList<List<String[]>> fanboysAnnoyanceList;
206     private ArrayList<List<String[]>> fanboysSocialList;
207     private ArrayList<List<String[]>> ultraPrivacy;
208
209     // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
210     private String webViewDefaultUserAgent;
211
212     // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
213     private boolean proxyThroughOrbot;
214
215     // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
216     private boolean incognitoModeEnabled;
217
218     // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
219     private boolean fullScreenBrowsingModeEnabled;
220
221     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
222     private boolean inFullScreenBrowsingMode;
223
224     // The hide app bar tracker is used in `applyAppSettings()` and `initializeWebView()`.
225     private boolean hideAppBar;
226
227     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
228     private boolean reapplyDomainSettingsOnRestart;
229
230     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
231     private boolean reapplyAppSettingsOnRestart;
232
233     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
234     private boolean displayingFullScreenVideo;
235
236     // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
237     private BroadcastReceiver orbotStatusBroadcastReceiver;
238
239     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
240     private boolean waitingForOrbot;
241
242     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
243     private ActionBarDrawerToggle actionBarDrawerToggle;
244
245     // The color spans are used in `onCreate()` and `highlightUrlText()`.
246     private ForegroundColorSpan redColorSpan;
247     private ForegroundColorSpan initialGrayColorSpan;
248     private ForegroundColorSpan finalGrayColorSpan;
249
250     // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
251     private int drawerHeaderPaddingLeftAndRight;
252     private int drawerHeaderPaddingTop;
253     private int drawerHeaderPaddingBottom;
254
255     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
256     // and `loadBookmarksFolder()`.
257     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
258
259     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
260     private Cursor bookmarksCursor;
261
262     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
263     private CursorAdapter bookmarksCursorAdapter;
264
265     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
266     private String oldFolderNameString;
267
268     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
269     private ValueCallback<Uri[]> fileChooserCallback;
270
271     // The download strings are used in `onCreate()`, `onRequestPermissionResult()` and `initializeWebView()`.
272     private String downloadUrl;
273     private String downloadContentDisposition;
274     private long downloadContentLength;
275
276     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
277     private String downloadImageUrl;
278
279     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, `onRequestPermissionResult()`, and `initializeWebView()`.
280     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
281     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
282
283     @Override
284     // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
285     @SuppressLint("ClickableViewAccessibility")
286     protected void onCreate(Bundle savedInstanceState) {
287         // Get a handle for the shared preferences.
288         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
289
290         // Get the theme and screenshot preferences.
291         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
292         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
293
294         // Disable screenshots if not allowed.
295         if (!allowScreenshots) {
296             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
297         }
298
299         // Set the activity theme.
300         if (darkTheme) {
301             setTheme(R.style.PrivacyBrowserDark);
302         } else {
303             setTheme(R.style.PrivacyBrowserLight);
304         }
305
306         // Run the default commands.
307         super.onCreate(savedInstanceState);
308
309         // Set the content view.
310         setContentView(R.layout.main_framelayout);
311
312         // Get a handle for the input method.
313         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
314
315         // Remove the lint warning below that the input method manager might be null.
316         assert inputMethodManager != null;
317
318         // Get a handle for the toolbar.
319         Toolbar toolbar = findViewById(R.id.toolbar);
320
321         // Set the action bar.  `SupportActionBar` must be used until the minimum API is >= 21.
322         setSupportActionBar(toolbar);
323
324         // Get a handle for the action bar.
325         ActionBar actionBar = getSupportActionBar();
326
327         // This is needed to get rid of the Android Studio warning that the action bar might be null.
328         assert actionBar != null;
329
330         // Add the custom layout, which shows the URL text bar.
331         actionBar.setCustomView(R.layout.url_app_bar);
332         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
333
334         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
335         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
336         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
337         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
338
339         // Get handles for the URL views.
340         EditText urlEditText = findViewById(R.id.url_edittext);
341
342         // Remove the formatting from `urlTextBar` when the user is editing the text.
343         urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
344             if (hasFocus) {  // The user is editing the URL text box.
345                 // Remove the highlighting.
346                 urlEditText.getText().removeSpan(redColorSpan);
347                 urlEditText.getText().removeSpan(initialGrayColorSpan);
348                 urlEditText.getText().removeSpan(finalGrayColorSpan);
349             } else {  // The user has stopped editing the URL text box.
350                 // Move to the beginning of the string.
351                 urlEditText.setSelection(0);
352
353                 // Reapply the highlighting.
354                 highlightUrlText();
355             }
356         });
357
358         // Set the go button on the keyboard to load the URL in `urlTextBox`.
359         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
360             // If the event is a key-down event on the `enter` button, load the URL.
361             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
362                 // Load the URL into the mainWebView and consume the event.
363                 loadUrlFromTextBox();
364
365                 // If the enter key was pressed, consume the event.
366                 return true;
367             } else {
368                 // If any other key was pressed, do not consume the event.
369                 return false;
370             }
371         });
372
373         // Initialize the Orbot status and the waiting for Orbot trackers.
374         orbotStatus = "unknown";
375         waitingForOrbot = false;
376
377         // Create an Orbot status `BroadcastReceiver`.
378         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
379             @Override
380             public void onReceive(Context context, Intent intent) {
381                 // Store the content of the status message in `orbotStatus`.
382                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
383
384                 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
385                 if (orbotStatus.equals("ON") && waitingForOrbot) {
386                     // Reset the waiting for Orbot status.
387                     waitingForOrbot = false;
388
389                     // Get the intent that started the app.
390                     Intent launchingIntent = getIntent();
391
392                     // Get the information from the intent.
393                     String launchingIntentAction = launchingIntent.getAction();
394                     Uri launchingIntentUriData = launchingIntent.getData();
395
396                     // If the intent action is a web search, perform the search.
397                     if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
398                         // Create an encoded URL string.
399                         String encodedUrlString;
400
401                         // Sanitize the search input and convert it to a search.
402                         try {
403                             encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
404                         } catch (UnsupportedEncodingException exception) {
405                             encodedUrlString = "";
406                         }
407
408                         // Load the completed search URL.
409                         loadUrl(searchURL + encodedUrlString);
410                     } else if (launchingIntentUriData != null){  // Check to see if the intent contains a new URL.
411                         // Load the URL from the intent.
412                         loadUrl(launchingIntentUriData.toString());
413                     } else {  // The is no URL in the intent.
414                         // Select the homepage based on the proxy through Orbot status.
415                         if (proxyThroughOrbot) {
416                             // Load the Tor homepage.
417                             loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
418                         } else {
419                             // Load the normal homepage.
420                             loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
421                         }
422                     }
423                 }
424             }
425         };
426
427         // Register `orbotStatusBroadcastReceiver` on `this` context.
428         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
429
430         // Instantiate the blocklist helper.
431         BlockListHelper blockListHelper = new BlockListHelper();
432
433         // Parse the block lists.
434         easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
435         easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
436         fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
437         fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
438         ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
439
440         // Get handles for views that need to be modified.
441         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
442         NavigationView navigationView = findViewById(R.id.navigationview);
443         TabLayout tabLayout = findViewById(R.id.tablayout);
444         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
445         ViewPager webViewPager = findViewById(R.id.webviewpager);
446         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
447         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
448         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
449         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
450         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
451
452         // Listen for touches on the navigation menu.
453         navigationView.setNavigationItemSelectedListener(this);
454
455         // Get handles for the navigation menu and the back and forward menu items.  The menu is zero-based.
456         Menu navigationMenu = navigationView.getMenu();
457         MenuItem navigationCloseTabMenuItem = navigationMenu.getItem(0);
458         MenuItem navigationBackMenuItem = navigationMenu.getItem(3);
459         MenuItem navigationForwardMenuItem = navigationMenu.getItem(4);
460         MenuItem navigationHistoryMenuItem = navigationMenu.getItem(5);
461         MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
462
463         // Initialize the web view pager adapter.
464         webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
465
466         // Set the pager adapter on the web view pager.
467         webViewPager.setAdapter(webViewPagerAdapter);
468
469         // Store up to 100 tabs in memory.
470         webViewPager.setOffscreenPageLimit(100);
471
472         // Update the web view pager every time a tab is modified.
473         webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
474             @Override
475             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
476                 // Do nothing.
477             }
478
479             @Override
480             public void onPageSelected(int position) {
481                 // Close the find on page bar if it is open.
482                 closeFindOnPage(null);
483
484                 // Set the current WebView.
485                 setCurrentWebView(position);
486
487                 // Select the corresponding tab if it does not match the currently selected page.  This will happen if the page was scrolled via swiping in the view pager or by creating a new tab.
488                 if (tabLayout.getSelectedTabPosition() != position) {
489                     // Create a handler to select the tab.
490                     Handler selectTabHandler = new Handler();
491
492                     // Create a runnable select the new tab.
493                     Runnable selectTabRunnable = () -> {
494                         // Get a handle for the tab.
495                         TabLayout.Tab tab = tabLayout.getTabAt(position);
496
497                         // Assert that the tab is not null.
498                         assert tab != null;
499
500                         // Select the tab.
501                         tab.select();
502                     };
503
504                     // Select the tab layout after 100 milliseconds, which leaves enough time for a new tab to be created.
505                     selectTabHandler.postDelayed(selectTabRunnable, 100);
506                 }
507             }
508
509             @Override
510             public void onPageScrollStateChanged(int state) {
511                 // Do nothing.
512             }
513         });
514
515         // Display the View SSL Certificate dialog when the currently selected tab is reselected.
516         tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
517             @Override
518             public void onTabSelected(TabLayout.Tab tab) {
519                 // Select the same page in the view pager.
520                 webViewPager.setCurrentItem(tab.getPosition());
521             }
522
523             @Override
524             public void onTabUnselected(TabLayout.Tab tab) {
525                 // Do nothing.
526             }
527
528             @Override
529             public void onTabReselected(TabLayout.Tab tab) {
530                 // Instantiate the View SSL Certificate dialog.
531                 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
532
533                 // Display the View SSL Certificate dialog.
534                 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
535             }
536         });
537
538         // Add the first tab.
539         addTab(null);
540
541         // Set the bookmarks drawer resources according to the theme.  This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
542         // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
543         if (darkTheme) {
544             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
545             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
546             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
547             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
548         } else {
549             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
550             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
551             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
552             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
553         }
554
555         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
556         launchBookmarksActivityFab.setOnClickListener(v -> {
557             // Get a copy of the favorite icon bitmap.
558             Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
559
560             // Create a favorite icon byte array output stream.
561             ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
562
563             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
564             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
565
566             // Convert the favorite icon byte array stream to a byte array.
567             byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
568
569             // Create an intent to launch the bookmarks activity.
570             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
571
572             // Add the extra information to the intent.
573             bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
574             bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
575             bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
576             bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
577
578             // Make it so.
579             startActivity(bookmarksIntent);
580         });
581
582         // Set the create new bookmark folder FAB to display an alert dialog.
583         createBookmarkFolderFab.setOnClickListener(v -> {
584             // Create a create bookmark folder dialog.
585             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
586
587             // Show the create bookmark folder dialog.
588             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
589         });
590
591         // Set the create new bookmark FAB to display an alert dialog.
592         createBookmarkFab.setOnClickListener(view -> {
593             // Instantiate the create bookmark dialog.
594             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
595
596             // Display the create bookmark dialog.
597             createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
598         });
599
600         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
601         findOnPageEditText.addTextChangedListener(new TextWatcher() {
602             @Override
603             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
604                 // Do nothing.
605             }
606
607             @Override
608             public void onTextChanged(CharSequence s, int start, int before, int count) {
609                 // Do nothing.
610             }
611
612             @Override
613             public void afterTextChanged(Editable s) {
614                 // Search for the text in `mainWebView`.
615                 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
616             }
617         });
618
619         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
620         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
621             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
622                 // Hide the soft keyboard.
623                 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
624
625                 // Consume the event.
626                 return true;
627             } else {  // A different key was pressed.
628                 // Do not consume the event.
629                 return false;
630             }
631         });
632
633         // Implement swipe to refresh.
634         swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
635
636         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
637         swipeRefreshLayout.setProgressViewOffset(false, swipeRefreshLayout.getProgressViewStartOffset() - 10, swipeRefreshLayout.getProgressViewEndOffset());
638
639         // Set the swipe to refresh color according to the theme.
640         if (darkTheme) {
641             swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
642             swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
643         } else {
644             swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
645         }
646
647         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
648         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
649         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
650
651         // Initialize the bookmarks database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
652         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
653
654         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
655         currentBookmarksFolder = "";
656
657         // Load the home folder, which is `""` in the database.
658         loadBookmarksFolder();
659
660         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
661             // Convert the id from long to int to match the format of the bookmarks database.
662             int databaseID = (int) id;
663
664             // Get the bookmark cursor for this ID and move it to the first row.
665             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseID);
666             bookmarkCursor.moveToFirst();
667
668             // Act upon the bookmark according to the type.
669             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
670                 // Store the new folder name in `currentBookmarksFolder`.
671                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
672
673                 // Load the new folder.
674                 loadBookmarksFolder();
675             } else {  // The selected bookmark is not a folder.
676                 // Load the bookmark URL.
677                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
678
679                 // Close the bookmarks drawer.
680                 drawerLayout.closeDrawer(GravityCompat.END);
681             }
682
683             // Close the `Cursor`.
684             bookmarkCursor.close();
685         });
686
687         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
688             // Convert the database ID from `long` to `int`.
689             int databaseId = (int) id;
690
691             // Find out if the selected bookmark is a folder.
692             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
693
694             if (isFolder) {
695                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
696                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
697
698                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
699                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
700                 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
701             } else {
702                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
703                 DialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
704                 editBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.edit_bookmark));
705             }
706
707             // Consume the event.
708             return true;
709         });
710
711         // Get the status bar pixel size.
712         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
713         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
714
715         // Get the resource density.
716         float screenDensity = getResources().getDisplayMetrics().density;
717
718         // Calculate the drawer header padding.  This is used to move the text in the drawer headers below any cutouts.
719         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
720         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
721         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
722
723         // The drawer listener is used to update the navigation menu.`
724         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
725             @Override
726             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
727             }
728
729             @Override
730             public void onDrawerOpened(@NonNull View drawerView) {
731             }
732
733             @Override
734             public void onDrawerClosed(@NonNull View drawerView) {
735             }
736
737             @Override
738             public void onDrawerStateChanged(int newState) {
739                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
740                     // Get handles for the drawer headers.
741                     TextView navigationHeaderTextView = findViewById(R.id.navigationText);
742                     TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
743
744                     // Apply the navigation header paddings if the view is not null (sometimes it is null if another activity has already started).  This moves the text in the header below any cutouts.
745                     if (navigationHeaderTextView != null) {
746                         navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
747                     }
748
749                     // Apply the bookmarks header paddings if the view is not null (sometimes it is null if another activity has already started).  This moves the text in the header below any cutouts.
750                     if (bookmarksHeaderTextView != null) {
751                         bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
752                     }
753
754                     // Update the navigation menu items.
755                     navigationCloseTabMenuItem.setEnabled(tabLayout.getTabCount() > 1);
756                     navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
757                     navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
758                     navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
759                     navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
760
761                     // Hide the keyboard (if displayed).
762                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
763
764                     // Clear the focus from from the URL text box and the WebView.  This removes any text selection markers and context menus, which otherwise draw above the open drawers.
765                     urlEditText.clearFocus();
766                     currentWebView.clearFocus();
767                 }
768             }
769         });
770
771         // Create the hamburger icon at the start of the AppBar.
772         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
773
774         // Replace the header that `WebView` creates for `X-Requested-With` with a null value.  The default value is the application ID (com.stoutner.privacybrowser.standard).
775         customHeaders.put("X-Requested-With", "");
776
777         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
778         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
779
780         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
781         @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
782
783         // Get a handle for the WebView.
784         WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
785
786         // Store the default user agent.
787         webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
788
789         // Destroy the bare WebView.
790         bareWebView.destroy();
791     }
792
793     @Override
794     protected void onNewIntent(Intent intent) {
795         // Get the information from the intent.
796         String intentAction = intent.getAction();
797         Uri intentUriData = intent.getData();
798
799         // Only process the URI if it contains data.  If the user pressed the desktop icon after the app was already running the URI will be null.
800         if (intentUriData != null) {
801             // Sets the new intent as the activity intent, which replaces the one that originally started the app.
802             setIntent(intent);
803
804             // Add a new tab.
805             addTab(null);
806
807             // Create a URL string.
808             String url;
809
810             // If the intent action is a web search, perform the search.
811             if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
812                 // Create an encoded URL string.
813                 String encodedUrlString;
814
815                 // Sanitize the search input and convert it to a search.
816                 try {
817                     encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
818                 } catch (UnsupportedEncodingException exception) {
819                     encodedUrlString = "";
820                 }
821
822                 // Add the base search URL.
823                 url = searchURL + encodedUrlString;
824             } else {  // The intent should contain a URL.
825                 // Set the intent data as the URL.
826                 url = intentUriData.toString();
827             }
828
829             // Load the URL.
830             loadUrl(url);
831
832             // Get a handle for the drawer layout.
833             DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
834
835             // Close the navigation drawer if it is open.
836             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
837                 drawerLayout.closeDrawer(GravityCompat.START);
838             }
839
840             // Close the bookmarks drawer if it is open.
841             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
842                 drawerLayout.closeDrawer(GravityCompat.END);
843             }
844
845             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
846             currentWebView.requestFocus();
847         }
848     }
849
850     @Override
851     public void onRestart() {
852         // Run the default commands.
853         super.onRestart();
854
855         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
856         if (proxyThroughOrbot) {
857             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
858             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
859
860             // Send the intent to the Orbot package.
861             orbotIntent.setPackage("org.torproject.android");
862
863             // Make it so.
864             sendBroadcast(orbotIntent);
865         }
866
867         // Apply the app settings if returning from the Settings activity.
868         if (reapplyAppSettingsOnRestart) {
869             // Reset the reapply app settings on restart tracker.
870             reapplyAppSettingsOnRestart = false;
871
872             // Apply the app settings.
873             applyAppSettings();
874         }
875
876         // Apply the domain settings if returning from the settings or domains activity.
877         if (reapplyDomainSettingsOnRestart) {
878             // Reset the reapply domain settings on restart tracker.
879             reapplyDomainSettingsOnRestart = false;
880
881             // Reapply the domain settings for each tab.
882             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
883                 // Get the WebView tab fragment.
884                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
885
886                 // Get the fragment view.
887                 View fragmentView = webViewTabFragment.getView();
888
889                 // Only reload the WebViews if they exist.
890                 if (fragmentView != null) {
891                     // Get the nested scroll WebView from the tab fragment.
892                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
893
894                     // Reset the current domain name so the domain settings will be reapplied.
895                     nestedScrollWebView.resetCurrentDomainName();
896
897                     // Reapply the domain settings.
898                     applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
899                 }
900             }
901         }
902
903         // Load the URL on restart (used when loading a bookmark).
904         if (loadUrlOnRestart) {
905             // Load the specified URL.
906             loadUrl(urlToLoadOnRestart);
907
908             // Reset the load on restart tracker.
909             loadUrlOnRestart = false;
910         }
911
912         // Update the bookmarks drawer if returning from the Bookmarks activity.
913         if (restartFromBookmarksActivity) {
914             // Get a handle for the drawer layout.
915             DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
916
917             // Close the bookmarks drawer.
918             drawerLayout.closeDrawer(GravityCompat.END);
919
920             // Reload the bookmarks drawer.
921             loadBookmarksFolder();
922
923             // Reset `restartFromBookmarksActivity`.
924             restartFromBookmarksActivity = false;
925         }
926
927         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
928         updatePrivacyIcons(true);
929     }
930
931     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
932     @Override
933     public void onResume() {
934         // Run the default commands.
935         super.onResume();
936
937         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
938             // Get the WebView tab fragment.
939             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
940
941             // Get the fragment view.
942             View fragmentView = webViewTabFragment.getView();
943
944             // Only resume the WebViews if they exist (they won't when the app is first created).
945             if (fragmentView != null) {
946                 // Get the nested scroll WebView from the tab fragment.
947                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
948
949                 // Resume the nested scroll WebView JavaScript timers.
950                 nestedScrollWebView.resumeTimers();
951
952                 // Resume the nested scroll WebView.
953                 nestedScrollWebView.onResume();
954             }
955         }
956
957         // Display a message to the user if waiting for Orbot.
958         if (waitingForOrbot && !orbotStatus.equals("ON")) {
959             // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
960             currentWebView.getSettings().setUseWideViewPort(false);
961
962             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
963             currentWebView.loadData("<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>", "text/html", null);
964         }
965
966         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {
967             // Get a handle for the root frame layouts.
968             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
969
970             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
971             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
972
973             /* Hide the system bars.
974              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
975              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
976              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
977              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
978              */
979             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
980                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
981         } else if (BuildConfig.FLAVOR.contentEquals("free")) {  // Resume the adView for the free flavor.
982             // Resume the ad.
983             AdHelper.resumeAd(findViewById(R.id.adview));
984         }
985     }
986
987     @Override
988     public void onPause() {
989         // Run the default commands.
990         super.onPause();
991
992         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
993             // Get the WebView tab fragment.
994             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
995
996             // Get the fragment view.
997             View fragmentView = webViewTabFragment.getView();
998
999             // Only pause the WebViews if they exist (they won't when the app is first created).
1000             if (fragmentView != null) {
1001                 // Get the nested scroll WebView from the tab fragment.
1002                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
1003
1004                 // Pause the nested scroll WebView.
1005                 nestedScrollWebView.onPause();
1006
1007                 // Pause the nested scroll WebView JavaScript timers.
1008                 nestedScrollWebView.pauseTimers();
1009             }
1010         }
1011
1012         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1013         if (BuildConfig.FLAVOR.contentEquals("free")) {
1014             // Pause the ad.
1015             AdHelper.pauseAd(findViewById(R.id.adview));
1016         }
1017     }
1018
1019     @Override
1020     public void onDestroy() {
1021         // Unregister the Orbot status broadcast receiver.
1022         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1023
1024         // Close the bookmarks cursor and database.
1025         bookmarksCursor.close();
1026         bookmarksDatabaseHelper.close();
1027
1028         // Run the default commands.
1029         super.onDestroy();
1030     }
1031
1032     @Override
1033     public boolean onCreateOptionsMenu(Menu menu) {
1034         // Inflate the menu.  This adds items to the action bar if it is present.
1035         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1036
1037         // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
1038         optionsMenu = menu;
1039
1040         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1041         updatePrivacyIcons(false);
1042
1043         // Get handles for the menu items.
1044         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1045         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1046         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1047         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1048         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1049         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1050         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1051
1052         // Only display third-party cookies if API >= 21
1053         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1054
1055         // Only display the form data menu items if the API < 26.
1056         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1057         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1058
1059         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1060         clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
1061
1062         // Only show Ad Consent if this is the free flavor.
1063         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1064
1065         // Get the shared preference values.
1066         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1067
1068         // Get the dark theme and app bar preferences..
1069         boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1070         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
1071
1072         // Set the status of the additional app bar icons.  Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
1073         if (displayAdditionalAppBarIcons) {
1074             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1075             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1076             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1077         } else { //Do not display the additional icons.
1078             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1079             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1080             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1081         }
1082
1083         // Replace Refresh with Stop if a URL is already loading.
1084         if (currentWebView != null && currentWebView.getProgress() != 100) {
1085             // Set the title.
1086             refreshMenuItem.setTitle(R.string.stop);
1087
1088             // If the icon is displayed in the AppBar, set it according to the theme.
1089             if (displayAdditionalAppBarIcons) {
1090                 if (darkTheme) {
1091                     refreshMenuItem.setIcon(R.drawable.close_dark);
1092                 } else {
1093                     refreshMenuItem.setIcon(R.drawable.close_light);
1094                 }
1095             }
1096         }
1097
1098         return true;
1099     }
1100
1101     @Override
1102     public boolean onPrepareOptionsMenu(Menu menu) {
1103         // Get handles for the menu items.
1104         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1105         MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1106         MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1107         MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1108         MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1109         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1110         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1111         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1112         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1113         MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
1114         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1115         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1116         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1117         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1118         MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1119         MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1120         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1121         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1122         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1123         MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
1124         MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
1125
1126         // Get a handle for the cookie manager.
1127         CookieManager cookieManager = CookieManager.getInstance();
1128
1129         // Initialize the current user agent string and the font size.
1130         String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1131         int fontSize = 100;
1132
1133         // Set items that require the current web view to be populated.  It will be null when the program is first opened, as `onPrepareOptionsMenu()` is called before the first WebView is initialized.
1134         if (currentWebView != null) {
1135             // Set the add or edit domain text.
1136             if (currentWebView.getDomainSettingsApplied()) {
1137                 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1138             } else {
1139                 addOrEditDomain.setTitle(R.string.add_domain_settings);
1140             }
1141
1142             // Get the current user agent from the WebView.
1143             currentUserAgent = currentWebView.getSettings().getUserAgentString();
1144
1145             // Get the current font size from the
1146             fontSize = currentWebView.getSettings().getTextZoom();
1147
1148             // Set the status of the menu item checkboxes.
1149             domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1150             saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData());  // Form data can be removed once the minimum API >= 26.
1151             easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1152             easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1153             fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1154             fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1155             ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1156             blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1157             swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1158             displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1159             nightModeMenuItem.setChecked(currentWebView.getNightMode());
1160
1161             // Initialize the display names for the blocklists with the number of blocked requests.
1162             blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1163             easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_LIST) + " - " + getString(R.string.easylist));
1164             easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASY_PRIVACY) + " - " + getString(R.string.easyprivacy));
1165             fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1166             fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1167             ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRA_PRIVACY) + " - " + getString(R.string.ultraprivacy));
1168             blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1169
1170             // Only modify third-party cookies if the API >= 21.
1171             if (Build.VERSION.SDK_INT >= 21) {
1172                 // Set the status of the third-party cookies checkbox.
1173                 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1174
1175                 // Enable third-party cookies if first-party cookies are enabled.
1176                 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
1177             }
1178
1179             // Enable DOM Storage if JavaScript is enabled.
1180             domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1181         }
1182
1183         // Set the status of the menu item checkboxes.
1184         firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1185         proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
1186
1187         // Enable Clear Cookies if there are any.
1188         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1189
1190         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1191         String privateDataDirectoryString = getApplicationInfo().dataDir;
1192
1193         // Get a count of the number of files in the Local Storage directory.
1194         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1195         int localStorageDirectoryNumberOfFiles = 0;
1196         if (localStorageDirectory.exists()) {
1197             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1198         }
1199
1200         // Get a count of the number of files in the IndexedDB directory.
1201         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1202         int indexedDBDirectoryNumberOfFiles = 0;
1203         if (indexedDBDirectory.exists()) {
1204             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1205         }
1206
1207         // Enable Clear DOM Storage if there is any.
1208         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1209
1210         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1211         if (Build.VERSION.SDK_INT < 26) {
1212             // Get the WebView database.
1213             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1214
1215             // Enable the clear form data menu item if there is anything to clear.
1216             clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1217         }
1218
1219         // Enable Clear Data if any of the submenu items are enabled.
1220         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1221
1222         // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1223         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
1224
1225         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1226         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1227             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
1228         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1229             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
1230         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1231             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
1232         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1233             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
1234         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1235             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
1236         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1237             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
1238         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1239             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
1240         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1241             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
1242         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1243             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
1244         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1245             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
1246         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1247             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
1248         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1249             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
1250         } else {  // Custom user agent.
1251             menu.findItem(R.id.user_agent_custom).setChecked(true);
1252         }
1253
1254         // Instantiate the font size title and the selected font size menu item.
1255         String fontSizeTitle;
1256         MenuItem selectedFontSizeMenuItem;
1257
1258         // Prepare the font size title and current size menu item.
1259         switch (fontSize) {
1260             case 25:
1261                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1262                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1263                 break;
1264
1265             case 50:
1266                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1267                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1268                 break;
1269
1270             case 75:
1271                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1272                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1273                 break;
1274
1275             case 100:
1276                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1277                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1278                 break;
1279
1280             case 125:
1281                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1282                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1283                 break;
1284
1285             case 150:
1286                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1287                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1288                 break;
1289
1290             case 175:
1291                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1292                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1293                 break;
1294
1295             case 200:
1296                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1297                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1298                 break;
1299
1300             default:
1301                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1302                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1303                 break;
1304         }
1305
1306         // Set the font size title and select the current size menu item.
1307         fontSizeMenuItem.setTitle(fontSizeTitle);
1308         selectedFontSizeMenuItem.setChecked(true);
1309
1310         // Run all the other default commands.
1311         super.onPrepareOptionsMenu(menu);
1312
1313         // Display the menu.
1314         return true;
1315     }
1316
1317     @Override
1318     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1319     @SuppressLint("SetJavaScriptEnabled")
1320     public boolean onOptionsItemSelected(MenuItem menuItem) {
1321         // Reenter full screen browsing mode if it was interrupted by the options menu.  <https://redmine.stoutner.com/issues/389>
1322         if (inFullScreenBrowsingMode) {
1323             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
1324             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1325
1326             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
1327
1328             /* Hide the system bars.
1329              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1330              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
1331              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1332              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1333              */
1334             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
1335                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1336         }
1337
1338         // Get the selected menu item ID.
1339         int menuItemId = menuItem.getItemId();
1340
1341         // Get a handle for the shared preferences.
1342         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1343
1344         // Get a handle for the cookie manager.
1345         CookieManager cookieManager = CookieManager.getInstance();
1346
1347         // Run the commands that correlate to the selected menu item.
1348         switch (menuItemId) {
1349             case R.id.toggle_javascript:
1350                 // Toggle the JavaScript status.
1351                 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1352
1353                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1354                 updatePrivacyIcons(true);
1355
1356                 // Display a `Snackbar`.
1357                 if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
1358                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1359                 } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
1360                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1361                 } else {  // Privacy mode.
1362                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1363                 }
1364
1365                 // Reload the current WebView.
1366                 currentWebView.reload();
1367                 return true;
1368
1369             case R.id.add_or_edit_domain:
1370                 if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1371                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1372                     reapplyDomainSettingsOnRestart = true;
1373
1374                     // Create an intent to launch the domains activity.
1375                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1376
1377                     // Add the extra information to the intent.
1378                     domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1379                     domainsIntent.putExtra("close_on_back", true);
1380                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1381
1382                     // Get the current certificate.
1383                     SslCertificate sslCertificate = currentWebView.getCertificate();
1384
1385                     // Check to see if the SSL certificate is populated.
1386                     if (sslCertificate != null) {
1387                         // Extract the certificate to strings.
1388                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1389                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1390                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1391                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1392                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1393                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1394                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1395                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1396
1397                         // Add the certificate to the intent.
1398                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1399                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1400                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1401                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1402                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1403                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1404                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1405                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1406                     }
1407
1408                     // Check to see if the current IP addresses have been received.
1409                     if (currentWebView.hasCurrentIpAddresses()) {
1410                         // Add the current IP addresses to the intent.
1411                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1412                     }
1413
1414                     // Make it so.
1415                     startActivity(domainsIntent);
1416                 } else {  // Add a new domain.
1417                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1418                     reapplyDomainSettingsOnRestart = true;
1419
1420                     // Get the current domain
1421                     Uri currentUri = Uri.parse(currentWebView.getUrl());
1422                     String currentDomain = currentUri.getHost();
1423
1424                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1425                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1426
1427                     // Create the domain and store the database ID.
1428                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1429
1430                     // Create an intent to launch the domains activity.
1431                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1432
1433                     // Add the extra information to the intent.
1434                     domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1435                     domainsIntent.putExtra("close_on_back", true);
1436                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1437
1438                     // Get the current certificate.
1439                     SslCertificate sslCertificate = currentWebView.getCertificate();
1440
1441                     // Check to see if the SSL certificate is populated.
1442                     if (sslCertificate != null) {
1443                         // Extract the certificate to strings.
1444                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1445                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1446                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1447                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1448                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1449                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1450                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1451                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1452
1453                         // Add the certificate to the intent.
1454                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1455                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1456                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1457                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1458                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1459                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1460                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1461                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1462                     }
1463
1464                     // Check to see if the current IP addresses have been received.
1465                     if (currentWebView.hasCurrentIpAddresses()) {
1466                         // Add the current IP addresses to the intent.
1467                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1468                     }
1469
1470                     // Make it so.
1471                     startActivity(domainsIntent);
1472                 }
1473                 return true;
1474
1475             case R.id.toggle_first_party_cookies:
1476                 // Switch the first-party cookie status.
1477                 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1478
1479                 // Store the first-party cookie status.
1480                 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1481
1482                 // Update the menu checkbox.
1483                 menuItem.setChecked(cookieManager.acceptCookie());
1484
1485                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1486                 updatePrivacyIcons(true);
1487
1488                 // Display a snackbar.
1489                 if (cookieManager.acceptCookie()) {  // First-party cookies are enabled.
1490                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1491                 } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1492                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1493                 } else {  // Privacy mode.
1494                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1495                 }
1496
1497                 // Reload the current WebView.
1498                 currentWebView.reload();
1499                 return true;
1500
1501             case R.id.toggle_third_party_cookies:
1502                 if (Build.VERSION.SDK_INT >= 21) {
1503                     // Switch the status of thirdPartyCookiesEnabled.
1504                     cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1505
1506                     // Update the menu checkbox.
1507                     menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1508
1509                     // Display a snackbar.
1510                     if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1511                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1512                     } else {
1513                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1514                     }
1515
1516                     // Reload the current WebView.
1517                     currentWebView.reload();
1518                 } // Else do nothing because SDK < 21.
1519                 return true;
1520
1521             case R.id.toggle_dom_storage:
1522                 // Toggle the status of domStorageEnabled.
1523                 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1524
1525                 // Update the menu checkbox.
1526                 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1527
1528                 // Update the privacy icon.  `true` refreshes the app bar icons.
1529                 updatePrivacyIcons(true);
1530
1531                 // Display a snackbar.
1532                 if (currentWebView.getSettings().getDomStorageEnabled()) {
1533                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1534                 } else {
1535                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1536                 }
1537
1538                 // Reload the current WebView.
1539                 currentWebView.reload();
1540                 return true;
1541
1542             // Form data can be removed once the minimum API >= 26.
1543             case R.id.toggle_save_form_data:
1544                 // Switch the status of saveFormDataEnabled.
1545                 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1546
1547                 // Update the menu checkbox.
1548                 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1549
1550                 // Display a snackbar.
1551                 if (currentWebView.getSettings().getSaveFormData()) {
1552                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1553                 } else {
1554                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1555                 }
1556
1557                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1558                 updatePrivacyIcons(true);
1559
1560                 // Reload the current WebView.
1561                 currentWebView.reload();
1562                 return true;
1563
1564             case R.id.clear_cookies:
1565                 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1566                         .setAction(R.string.undo, v -> {
1567                             // Do nothing because everything will be handled by `onDismissed()` below.
1568                         })
1569                         .addCallback(new Snackbar.Callback() {
1570                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1571                             @Override
1572                             public void onDismissed(Snackbar snackbar, int event) {
1573                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1574                                     // Delete the cookies, which command varies by SDK.
1575                                     if (Build.VERSION.SDK_INT < 21) {
1576                                         cookieManager.removeAllCookie();
1577                                     } else {
1578                                         cookieManager.removeAllCookies(null);
1579                                     }
1580                                 }
1581                             }
1582                         })
1583                         .show();
1584                 return true;
1585
1586             case R.id.clear_dom_storage:
1587                 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1588                         .setAction(R.string.undo, v -> {
1589                             // Do nothing because everything will be handled by `onDismissed()` below.
1590                         })
1591                         .addCallback(new Snackbar.Callback() {
1592                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1593                             @Override
1594                             public void onDismissed(Snackbar snackbar, int event) {
1595                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1596                                     // Delete the DOM Storage.
1597                                     WebStorage webStorage = WebStorage.getInstance();
1598                                     webStorage.deleteAllData();
1599
1600                                     // Initialize a handler to manually delete the DOM storage files and directories.
1601                                     Handler deleteDomStorageHandler = new Handler();
1602
1603                                     // Setup a runnable to manually delete the DOM storage files and directories.
1604                                     Runnable deleteDomStorageRunnable = () -> {
1605                                         try {
1606                                             // Get a handle for the runtime.
1607                                             Runtime runtime = Runtime.getRuntime();
1608
1609                                             // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1610                                             // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1611                                             String privateDataDirectoryString = getApplicationInfo().dataDir;
1612
1613                                             // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1614                                             Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1615
1616                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1617                                             Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1618                                             Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1619                                             Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1620                                             Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1621
1622                                             // Wait for the processes to finish.
1623                                             deleteLocalStorageProcess.waitFor();
1624                                             deleteIndexProcess.waitFor();
1625                                             deleteQuotaManagerProcess.waitFor();
1626                                             deleteQuotaManagerJournalProcess.waitFor();
1627                                             deleteDatabasesProcess.waitFor();
1628                                         } catch (Exception exception) {
1629                                             // Do nothing if an error is thrown.
1630                                         }
1631                                     };
1632
1633                                     // Manually delete the DOM storage files after 200 milliseconds.
1634                                     deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1635                                 }
1636                             }
1637                         })
1638                         .show();
1639                 return true;
1640
1641             // Form data can be remove once the minimum API >= 26.
1642             case R.id.clear_form_data:
1643                 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1644                         .setAction(R.string.undo, v -> {
1645                             // Do nothing because everything will be handled by `onDismissed()` below.
1646                         })
1647                         .addCallback(new Snackbar.Callback() {
1648                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1649                             @Override
1650                             public void onDismissed(Snackbar snackbar, int event) {
1651                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1652                                     // Delete the form data.
1653                                     WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1654                                     mainWebViewDatabase.clearFormData();
1655                                 }
1656                             }
1657                         })
1658                         .show();
1659                 return true;
1660
1661             case R.id.easylist:
1662                 // Toggle the EasyList status.
1663                 currentWebView.enableBlocklist(NestedScrollWebView.EASY_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1664
1665                 // Update the menu checkbox.
1666                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_LIST));
1667
1668                 // Reload the current WebView.
1669                 currentWebView.reload();
1670                 return true;
1671
1672             case R.id.easyprivacy:
1673                 // Toggle the EasyPrivacy status.
1674                 currentWebView.enableBlocklist(NestedScrollWebView.EASY_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1675
1676                 // Update the menu checkbox.
1677                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASY_PRIVACY));
1678
1679                 // Reload the current WebView.
1680                 currentWebView.reload();
1681                 return true;
1682
1683             case R.id.fanboys_annoyance_list:
1684                 // Toggle Fanboy's Annoyance List status.
1685                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1686
1687                 // Update the menu checkbox.
1688                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1689
1690                 // Update the staus of Fanboy's Social Blocking List.
1691                 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1692                 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1693
1694                 // Reload the current WebView.
1695                 currentWebView.reload();
1696                 return true;
1697
1698             case R.id.fanboys_social_blocking_list:
1699                 // Toggle Fanboy's Social Blocking List status.
1700                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1701
1702                 // Update the menu checkbox.
1703                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1704
1705                 // Reload the current WebView.
1706                 currentWebView.reload();
1707                 return true;
1708
1709             case R.id.ultraprivacy:
1710                 // Toggle the UltraPrivacy status.
1711                 currentWebView.enableBlocklist(NestedScrollWebView.ULTRA_PRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1712
1713                 // Update the menu checkbox.
1714                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRA_PRIVACY));
1715
1716                 // Reload the current WebView.
1717                 currentWebView.reload();
1718                 return true;
1719
1720             case R.id.block_all_third_party_requests:
1721                 //Toggle the third-party requests blocker status.
1722                 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1723
1724                 // Update the menu checkbox.
1725                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1726
1727                 // Reload the current WebView.
1728                 currentWebView.reload();
1729                 return true;
1730
1731             case R.id.user_agent_privacy_browser:
1732                 // Update the user agent.
1733                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1734
1735                 // Reload the current WebView.
1736                 currentWebView.reload();
1737                 return true;
1738
1739             case R.id.user_agent_webview_default:
1740                 // Update the user agent.
1741                 currentWebView.getSettings().setUserAgentString("");
1742
1743                 // Reload the current WebView.
1744                 currentWebView.reload();
1745                 return true;
1746
1747             case R.id.user_agent_firefox_on_android:
1748                 // Update the user agent.
1749                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1750
1751                 // Reload the current WebView.
1752                 currentWebView.reload();
1753                 return true;
1754
1755             case R.id.user_agent_chrome_on_android:
1756                 // Update the user agent.
1757                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1758
1759                 // Reload the current WebView.
1760                 currentWebView.reload();
1761                 return true;
1762
1763             case R.id.user_agent_safari_on_ios:
1764                 // Update the user agent.
1765                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1766
1767                 // Reload the current WebView.
1768                 currentWebView.reload();
1769                 return true;
1770
1771             case R.id.user_agent_firefox_on_linux:
1772                 // Update the user agent.
1773                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1774
1775                 // Reload the current WebView.
1776                 currentWebView.reload();
1777                 return true;
1778
1779             case R.id.user_agent_chromium_on_linux:
1780                 // Update the user agent.
1781                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1782
1783                 // Reload the current WebView.
1784                 currentWebView.reload();
1785                 return true;
1786
1787             case R.id.user_agent_firefox_on_windows:
1788                 // Update the user agent.
1789                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1790
1791                 // Reload the current WebView.
1792                 currentWebView.reload();
1793                 return true;
1794
1795             case R.id.user_agent_chrome_on_windows:
1796                 // Update the user agent.
1797                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1798
1799                 // Reload the current WebView.
1800                 currentWebView.reload();
1801                 return true;
1802
1803             case R.id.user_agent_edge_on_windows:
1804                 // Update the user agent.
1805                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1806
1807                 // Reload the current WebView.
1808                 currentWebView.reload();
1809                 return true;
1810
1811             case R.id.user_agent_internet_explorer_on_windows:
1812                 // Update the user agent.
1813                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1814
1815                 // Reload the current WebView.
1816                 currentWebView.reload();
1817                 return true;
1818
1819             case R.id.user_agent_safari_on_macos:
1820                 // Update the user agent.
1821                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1822
1823                 // Reload the current WebView.
1824                 currentWebView.reload();
1825                 return true;
1826
1827             case R.id.user_agent_custom:
1828                 // Update the user agent.
1829                 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1830
1831                 // Reload the current WebView.
1832                 currentWebView.reload();
1833                 return true;
1834
1835             case R.id.font_size_twenty_five_percent:
1836                 currentWebView.getSettings().setTextZoom(25);
1837                 return true;
1838
1839             case R.id.font_size_fifty_percent:
1840                 currentWebView.getSettings().setTextZoom(50);
1841                 return true;
1842
1843             case R.id.font_size_seventy_five_percent:
1844                 currentWebView.getSettings().setTextZoom(75);
1845                 return true;
1846
1847             case R.id.font_size_one_hundred_percent:
1848                 currentWebView.getSettings().setTextZoom(100);
1849                 return true;
1850
1851             case R.id.font_size_one_hundred_twenty_five_percent:
1852                 currentWebView.getSettings().setTextZoom(125);
1853                 return true;
1854
1855             case R.id.font_size_one_hundred_fifty_percent:
1856                 currentWebView.getSettings().setTextZoom(150);
1857                 return true;
1858
1859             case R.id.font_size_one_hundred_seventy_five_percent:
1860                 currentWebView.getSettings().setTextZoom(175);
1861                 return true;
1862
1863             case R.id.font_size_two_hundred_percent:
1864                 currentWebView.getSettings().setTextZoom(200);
1865                 return true;
1866
1867             case R.id.swipe_to_refresh:
1868                 // Toggle the stored status of swipe to refresh.
1869                 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1870
1871                 // Get a handle for the swipe refresh layout.
1872                 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1873
1874                 // Update the swipe refresh layout.
1875                 if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1876                     if (Build.VERSION.SDK_INT >= 23) {  // For API >= 23, the status of the scroll refresh listener is continuously updated by the on scroll change listener.
1877                         // Only enable the swipe refresh layout if the WebView is scrolled to the top.
1878                         swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1879                     } else {  // For API < 23, the swipe refresh layout is always enabled.
1880                         // Enable the swipe refresh layout.
1881                         swipeRefreshLayout.setEnabled(true);
1882                     }
1883                 } else {  // Swipe to refresh is disabled.
1884                     // Disable the swipe refresh layout.
1885                     swipeRefreshLayout.setEnabled(false);
1886                 }
1887                 return true;
1888
1889             case R.id.display_images:
1890                 if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1891                     // Disable loading of images.
1892                     currentWebView.getSettings().setLoadsImagesAutomatically(false);
1893
1894                     // Reload the website to remove existing images.
1895                     currentWebView.reload();
1896                 } else {  // Images are not currently loaded automatically.
1897                     // Enable loading of images.  Missing images will be loaded without the need for a reload.
1898                     currentWebView.getSettings().setLoadsImagesAutomatically(true);
1899                 }
1900                 return true;
1901
1902             case R.id.night_mode:
1903                 // Toggle night mode.
1904                 currentWebView.setNightMode(!currentWebView.getNightMode());
1905
1906                 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1907                 if (currentWebView.getNightMode()) {  // Night mode is enabled, which requires JavaScript.
1908                     // Enable JavaScript.
1909                     currentWebView.getSettings().setJavaScriptEnabled(true);
1910                 } else if (currentWebView.getDomainSettingsApplied()) {  // Night mode is disabled and domain settings are applied.  Set JavaScript according to the domain settings.
1911                     // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1912                     currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1913                 } else {  // Night mode is disabled and domain settings are not applied.  Set JavaScript according to the global preference.
1914                     // Apply the JavaScript preference.
1915                     currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1916                 }
1917
1918                 // Update the privacy icons.
1919                 updatePrivacyIcons(false);
1920
1921                 // Reload the website.
1922                 currentWebView.reload();
1923                 return true;
1924
1925             case R.id.find_on_page:
1926                 // Get a handle for the views.
1927                 Toolbar toolbar = findViewById(R.id.toolbar);
1928                 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1929                 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1930
1931                 // Set the minimum height of the find on page linear layout to match the toolbar.
1932                 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1933
1934                 // Hide the toolbar.
1935                 toolbar.setVisibility(View.GONE);
1936
1937                 // Show the find on page linear layout.
1938                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1939
1940                 // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1941                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1942                 findOnPageEditText.postDelayed(() -> {
1943                     // Set the focus on `findOnPageEditText`.
1944                     findOnPageEditText.requestFocus();
1945
1946                     // Get a handle for the input method manager.
1947                     InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1948
1949                     // Remove the lint warning below that the input method manager might be null.
1950                     assert inputMethodManager != null;
1951
1952                     // Display the keyboard.  `0` sets no input flags.
1953                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
1954                 }, 200);
1955                 return true;
1956
1957             case R.id.view_source:
1958                 // Create an intent to launch the view source activity.
1959                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1960
1961                 // Add the variables to the intent.
1962                 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1963                 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1964
1965                 // Make it so.
1966                 startActivity(viewSourceIntent);
1967                 return true;
1968
1969             case R.id.share_url:
1970                 // Setup the share string.
1971                 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1972
1973                 // Create the share intent.
1974                 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1975                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1976                 shareIntent.setType("text/plain");
1977
1978                 // Make it so.
1979                 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1980                 return true;
1981
1982             case R.id.print:
1983                 // Get a print manager instance.
1984                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1985
1986                 // Remove the lint error below that print manager might be null.
1987                 assert printManager != null;
1988
1989                 // Create a print document adapter from the current WebView.
1990                 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1991
1992                 // Print the document.
1993                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1994                 return true;
1995
1996             case R.id.open_with_app:
1997                 openWithApp(currentWebView.getUrl());
1998                 return true;
1999
2000             case R.id.open_with_browser:
2001                 openWithBrowser(currentWebView.getUrl());
2002                 return true;
2003
2004             case R.id.add_to_homescreen:
2005                 // Instantiate the create home screen shortcut dialog.
2006                 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
2007                         currentWebView.getFavoriteOrDefaultIcon());
2008
2009                 // Show the create home screen shortcut dialog.
2010                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2011                 return true;
2012
2013             case R.id.proxy_through_orbot:
2014                 // Toggle the proxy through Orbot variable.
2015                 proxyThroughOrbot = !proxyThroughOrbot;
2016
2017                 // Apply the proxy through Orbot settings.
2018                 applyProxyThroughOrbot(true);
2019                 return true;
2020
2021             case R.id.refresh:
2022                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2023                     // Reload the current WebView.
2024                     currentWebView.reload();
2025                 } else {  // The stop button was pushed.
2026                     // Stop the loading of the WebView.
2027                     currentWebView.stopLoading();
2028                 }
2029                 return true;
2030
2031             case R.id.ad_consent:
2032                 // Display the ad consent dialog.
2033                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2034                 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
2035                 return true;
2036
2037             default:
2038                 // Don't consume the event.
2039                 return super.onOptionsItemSelected(menuItem);
2040         }
2041     }
2042
2043     // removeAllCookies is deprecated, but it is required for API < 21.
2044     @Override
2045     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2046         // Get the menu item ID.
2047         int menuItemId = menuItem.getItemId();
2048
2049         // Get a handle for the shared preferences.
2050         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2051
2052         // Run the commands that correspond to the selected menu item.
2053         switch (menuItemId) {
2054             case R.id.close_tab:
2055                 // Get a handle for the tab layout and the view pager.
2056                 TabLayout tabLayout = findViewById(R.id.tablayout);
2057                 ViewPager webViewPager = findViewById(R.id.webviewpager);
2058
2059                 // Get the current tab number.
2060                 int currentTabNumber = tabLayout.getSelectedTabPosition();
2061
2062                 // Delete the current tab.
2063                 tabLayout.removeTabAt(currentTabNumber);
2064
2065                 // Delete the current page.  If the selected page number did not change during the delete, it will return true, meaning that the current WebView must be reset.
2066                 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
2067                     setCurrentWebView(currentTabNumber);
2068                 }
2069                 break;
2070
2071             case R.id.clear_and_exit:
2072                 // Close the bookmarks cursor and database.
2073                 bookmarksCursor.close();
2074                 bookmarksDatabaseHelper.close();
2075
2076                 // Get the status of the clear everything preference.
2077                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2078
2079                 // Get a handle for the runtime.
2080                 Runtime runtime = Runtime.getRuntime();
2081
2082                 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
2083                 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
2084                 String privateDataDirectoryString = getApplicationInfo().dataDir;
2085
2086                 // Clear cookies.
2087                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2088                     // The command to remove cookies changed slightly in API 21.
2089                     if (Build.VERSION.SDK_INT >= 21) {
2090                         CookieManager.getInstance().removeAllCookies(null);
2091                     } else {
2092                         CookieManager.getInstance().removeAllCookie();
2093                     }
2094
2095                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2096                     try {
2097                         // Two commands must be used because `Runtime.exec()` does not like `*`.
2098                         Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2099                         Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2100
2101                         // Wait until the processes have finished.
2102                         deleteCookiesProcess.waitFor();
2103                         deleteCookiesJournalProcess.waitFor();
2104                     } catch (Exception exception) {
2105                         // Do nothing if an error is thrown.
2106                     }
2107                 }
2108
2109                 // Clear DOM storage.
2110                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2111                     // Ask `WebStorage` to clear the DOM storage.
2112                     WebStorage webStorage = WebStorage.getInstance();
2113                     webStorage.deleteAllData();
2114
2115                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2116                     try {
2117                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2118                         Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2119
2120                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2121                         Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2122                         Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2123                         Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2124                         Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2125
2126                         // Wait until the processes have finished.
2127                         deleteLocalStorageProcess.waitFor();
2128                         deleteIndexProcess.waitFor();
2129                         deleteQuotaManagerProcess.waitFor();
2130                         deleteQuotaManagerJournalProcess.waitFor();
2131                         deleteDatabaseProcess.waitFor();
2132                     } catch (Exception exception) {
2133                         // Do nothing if an error is thrown.
2134                     }
2135                 }
2136
2137                 // Clear form data if the API < 26.
2138                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2139                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2140                     webViewDatabase.clearFormData();
2141
2142                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2143                     try {
2144                         // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
2145                         Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2146                         Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2147
2148                         // Wait until the processes have finished.
2149                         deleteWebDataProcess.waitFor();
2150                         deleteWebDataJournalProcess.waitFor();
2151                     } catch (Exception exception) {
2152                         // Do nothing if an error is thrown.
2153                     }
2154                 }
2155
2156                 // Clear the cache.
2157                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2158                     // Clear the cache from each WebView.
2159                     for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2160                         // Get the WebView tab fragment.
2161                         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2162
2163                         // Get the fragment view.
2164                         View fragmentView = webViewTabFragment.getView();
2165
2166                         // Only clear the cache if the WebView exists.
2167                         if (fragmentView != null) {
2168                             // Get the nested scroll WebView from the tab fragment.
2169                             NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2170
2171                             // Clear the cache for this WebView.
2172                             nestedScrollWebView.clearCache(true);
2173                         }
2174                     }
2175
2176                     // Manually delete the cache directories.
2177                     try {
2178                         // Delete the main cache directory.
2179                         Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2180
2181                         // Delete the secondary `Service Worker` cache directory.
2182                         // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2183                         Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2184
2185                         // Wait until the processes have finished.
2186                         deleteCacheProcess.waitFor();
2187                         deleteServiceWorkerProcess.waitFor();
2188                     } catch (Exception exception) {
2189                         // Do nothing if an error is thrown.
2190                     }
2191                 }
2192
2193                 // Wipe out each WebView.
2194                 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
2195                     // Get the WebView tab fragment.
2196                     WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
2197
2198                     // Get the fragment view.
2199                     View fragmentView = webViewTabFragment.getView();
2200
2201                     // Only wipe out the WebView if it exists.
2202                     if (fragmentView != null) {
2203                         // Get the nested scroll WebView from the tab fragment.
2204                         NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
2205
2206                         // Clear SSL certificate preferences for this WebView.
2207                         nestedScrollWebView.clearSslPreferences();
2208
2209                         // Clear the back/forward history for this WebView.
2210                         nestedScrollWebView.clearHistory();
2211
2212                         // Destroy the internal state of `mainWebView`.
2213                         nestedScrollWebView.destroy();
2214                     }
2215                 }
2216
2217                 // Clear the custom headers.
2218                 customHeaders.clear();
2219
2220                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2221                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2222                 if (clearEverything) {
2223                     try {
2224                         // Delete the folder.
2225                         Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2226
2227                         // Wait until the process has finished.
2228                         deleteAppWebviewProcess.waitFor();
2229                     } catch (Exception exception) {
2230                         // Do nothing if an error is thrown.
2231                     }
2232                 }
2233
2234                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2235                 if (Build.VERSION.SDK_INT >= 21) {
2236                     finishAndRemoveTask();
2237                 } else {
2238                     finish();
2239                 }
2240
2241                 // Remove the terminated program from RAM.  The status code is `0`.
2242                 System.exit(0);
2243                 break;
2244
2245             case R.id.home:
2246                 // Select the homepage based on the proxy through Orbot status.
2247                 if (proxyThroughOrbot) {
2248                     // Load the Tor homepage.
2249                     loadUrl(sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value)));
2250                 } else {
2251                     // Load the normal homepage.
2252                     loadUrl(sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2253                 }
2254                 break;
2255
2256             case R.id.back:
2257                 if (currentWebView.canGoBack()) {
2258                     // Reset the current domain name so that navigation works if third-party requests are blocked.
2259                     currentWebView.resetCurrentDomainName();
2260
2261                     // Set navigating history so that the domain settings are applied when the new URL is loaded.
2262                     currentWebView.setNavigatingHistory(true);
2263
2264                     // Load the previous website in the history.
2265                     currentWebView.goBack();
2266                 }
2267                 break;
2268
2269             case R.id.forward:
2270                 if (currentWebView.canGoForward()) {
2271                     // Reset the current domain name so that navigation works if third-party requests are blocked.
2272                     currentWebView.resetCurrentDomainName();
2273
2274                     // Set navigating history so that the domain settings are applied when the new URL is loaded.
2275                     currentWebView.setNavigatingHistory(true);
2276
2277                     // Load the next website in the history.
2278                     currentWebView.goForward();
2279                 }
2280                 break;
2281
2282             case R.id.history:
2283                 // Instantiate the URL history dialog.
2284                 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2285
2286                 // Show the URL history dialog.
2287                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2288                 break;
2289
2290             case R.id.requests:
2291                 // Populate the resource requests.
2292                 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2293
2294                 // Create an intent to launch the Requests activity.
2295                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2296
2297                 // Add the block third-party requests status to the intent.
2298                 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
2299
2300                 // Make it so.
2301                 startActivity(requestsIntent);
2302                 break;
2303
2304             case R.id.downloads:
2305                 // Launch the system Download Manager.
2306                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2307
2308                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2309                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2310
2311                 startActivity(downloadManagerIntent);
2312                 break;
2313
2314             case R.id.domains:
2315                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2316                 reapplyDomainSettingsOnRestart = true;
2317
2318                 // Launch the domains activity.
2319                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2320
2321                 // Add the extra information to the intent.
2322                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
2323
2324                 // Get the current certificate.
2325                 SslCertificate sslCertificate = currentWebView.getCertificate();
2326
2327                 // Check to see if the SSL certificate is populated.
2328                 if (sslCertificate != null) {
2329                     // Extract the certificate to strings.
2330                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
2331                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
2332                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
2333                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
2334                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
2335                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
2336                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2337                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2338
2339                     // Add the certificate to the intent.
2340                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2341                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2342                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2343                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2344                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2345                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2346                     domainsIntent.putExtra("ssl_start_date", startDateLong);
2347                     domainsIntent.putExtra("ssl_end_date", endDateLong);
2348                 }
2349
2350                 // Check to see if the current IP addresses have been received.
2351                 if (currentWebView.hasCurrentIpAddresses()) {
2352                     // Add the current IP addresses to the intent.
2353                     domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2354                 }
2355
2356                 // Make it so.
2357                 startActivity(domainsIntent);
2358                 break;
2359
2360             case R.id.settings:
2361                 // Set the flag to reapply app settings on restart when returning from Settings.
2362                 reapplyAppSettingsOnRestart = true;
2363
2364                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2365                 reapplyDomainSettingsOnRestart = true;
2366
2367                 // Launch the settings activity.
2368                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2369                 startActivity(settingsIntent);
2370                 break;
2371
2372             case R.id.import_export:
2373                 // Launch the import/export activity.
2374                 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2375                 startActivity(importExportIntent);
2376                 break;
2377
2378             case R.id.logcat:
2379                 // Launch the logcat activity.
2380                 Intent logcatIntent = new Intent(this, LogcatActivity.class);
2381                 startActivity(logcatIntent);
2382                 break;
2383
2384             case R.id.guide:
2385                 // Launch `GuideActivity`.
2386                 Intent guideIntent = new Intent(this, GuideActivity.class);
2387                 startActivity(guideIntent);
2388                 break;
2389
2390             case R.id.about:
2391                 // Create an intent to launch the about activity.
2392                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2393
2394                 // Create a string array for the blocklist versions.
2395                 String[] blocklistVersions = new String[] {easyList.get(0).get(0)[0], easyPrivacy.get(0).get(0)[0], fanboysAnnoyanceList.get(0).get(0)[0], fanboysSocialList.get(0).get(0)[0],
2396                         ultraPrivacy.get(0).get(0)[0]};
2397
2398                 // Add the blocklist versions to the intent.
2399                 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2400
2401                 // Make it so.
2402                 startActivity(aboutIntent);
2403                 break;
2404         }
2405
2406         // Get a handle for the drawer layout.
2407         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2408
2409         // Close the navigation drawer.
2410         drawerLayout.closeDrawer(GravityCompat.START);
2411         return true;
2412     }
2413
2414     @Override
2415     public void onPostCreate(Bundle savedInstanceState) {
2416         // Run the default commands.
2417         super.onPostCreate(savedInstanceState);
2418
2419         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2420         actionBarDrawerToggle.syncState();
2421     }
2422
2423     @Override
2424     public void onConfigurationChanged(Configuration newConfig) {
2425         // Run the default commands.
2426         super.onConfigurationChanged(newConfig);
2427
2428         // Get the status bar pixel size.
2429         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2430         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2431
2432         // Get the resource density.
2433         float screenDensity = getResources().getDisplayMetrics().density;
2434
2435         // Recalculate the drawer header padding.
2436         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2437         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2438         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2439
2440         // Reload the ad for the free flavor if not in full screen mode.
2441         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2442             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2443             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2444         }
2445
2446         // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
2447         // https://code.google.com/p/android/issues/detail?id=20493#c8
2448         // ActivityCompat.invalidateOptionsMenu(this);
2449     }
2450
2451     @Override
2452     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2453         // Store the hit test result.
2454         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2455
2456         // Create the URL strings.
2457         final String imageUrl;
2458         final String linkUrl;
2459
2460         // Get handles for the system managers.
2461         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2462         FragmentManager fragmentManager = getSupportFragmentManager();
2463         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2464
2465         // Remove the lint errors below that the clipboard manager might be null.
2466         assert clipboardManager != null;
2467
2468         // Process the link according to the type.
2469         switch (hitTestResult.getType()) {
2470             // `SRC_ANCHOR_TYPE` is a link.
2471             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2472                 // Get the target URL.
2473                 linkUrl = hitTestResult.getExtra();
2474
2475                 // Set the target URL as the title of the `ContextMenu`.
2476                 menu.setHeaderTitle(linkUrl);
2477
2478                 // Add a Load URL entry.
2479                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2480                     // Add a new tab.
2481                     addTab(null);
2482
2483                     // Load the URL.
2484                     loadUrl(linkUrl);
2485                     return false;
2486                 });
2487
2488                 // Add an Open with App entry.
2489                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2490                     openWithApp(linkUrl);
2491                     return false;
2492                 });
2493
2494                 // Add an Open with Browser entry.
2495                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2496                     openWithBrowser(linkUrl);
2497                     return false;
2498                 });
2499
2500                 // Add a Copy URL entry.
2501                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2502                     // Save the link URL in a `ClipData`.
2503                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2504
2505                     // Set the `ClipData` as the clipboard's primary clip.
2506                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2507                     return false;
2508                 });
2509
2510                 // Add a Download URL entry.
2511                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2512                     // Check if the download should be processed by an external app.
2513                     if (sharedPreferences.getBoolean("download_with_external_app", false)) {  // Download with an external app.
2514                         openUrlWithExternalApp(linkUrl);
2515                     } else {  // Download with Android's download manager.
2516                         // Check to see if the storage permission has already been granted.
2517                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2518                             // Store the variables for future use by `onRequestPermissionsResult()`.
2519                             downloadUrl = linkUrl;
2520                             downloadContentDisposition = "none";
2521                             downloadContentLength = -1;
2522
2523                             // Show a dialog if the user has previously denied the permission.
2524                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2525                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2526                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2527
2528                                 // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2529                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2530                             } else {  // Show the permission request directly.
2531                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2532                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2533                             }
2534                         } else {  // The storage permission has already been granted.
2535                             // Get a handle for the download file alert dialog.
2536                             DialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2537
2538                             // Show the download file alert dialog.
2539                             downloadFileDialogFragment.show(fragmentManager, getString(R.string.download));
2540                         }
2541                     }
2542                     return false;
2543                 });
2544
2545                 // Add a Cancel entry, which by default closes the context menu.
2546                 menu.add(R.string.cancel);
2547                 break;
2548
2549             case WebView.HitTestResult.EMAIL_TYPE:
2550                 // Get the target URL.
2551                 linkUrl = hitTestResult.getExtra();
2552
2553                 // Set the target URL as the title of the `ContextMenu`.
2554                 menu.setHeaderTitle(linkUrl);
2555
2556                 // Add a Write Email entry.
2557                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2558                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2559                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2560
2561                     // Parse the url and set it as the data for the `Intent`.
2562                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2563
2564                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2565                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2566
2567                     // Make it so.
2568                     startActivity(emailIntent);
2569                     return false;
2570                 });
2571
2572                 // Add a Copy Email Address entry.
2573                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2574                     // Save the email address in a `ClipData`.
2575                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2576
2577                     // Set the `ClipData` as the clipboard's primary clip.
2578                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2579                     return false;
2580                 });
2581
2582                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2583                 menu.add(R.string.cancel);
2584                 break;
2585
2586             // `IMAGE_TYPE` is an image.
2587             case WebView.HitTestResult.IMAGE_TYPE:
2588                 // Get the image URL.
2589                 imageUrl = hitTestResult.getExtra();
2590
2591                 // Set the image URL as the title of the `ContextMenu`.
2592                 menu.setHeaderTitle(imageUrl);
2593
2594                 // Add a View Image entry.
2595                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2596                     loadUrl(imageUrl);
2597                     return false;
2598                 });
2599
2600                 // Add a Download Image entry.
2601                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2602                     // Check if the download should be processed by an external app.
2603                     if (sharedPreferences.getBoolean("download_with_external_app", false)) {  // Download with an external app.
2604                         openUrlWithExternalApp(imageUrl);
2605                     } else {  // Download with Android's download manager.
2606                         // Check to see if the storage permission has already been granted.
2607                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2608                             // Store the image URL for use by `onRequestPermissionResult()`.
2609                             downloadImageUrl = imageUrl;
2610
2611                             // Show a dialog if the user has previously denied the permission.
2612                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2613                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2614                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2615
2616                                 // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2617                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2618                             } else {  // Show the permission request directly.
2619                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2620                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2621                             }
2622                         } else {  // The storage permission has already been granted.
2623                             // Get a handle for the download image alert dialog.
2624                             DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2625
2626                             // Show the download image alert dialog.
2627                             downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2628                         }
2629                     }
2630                     return false;
2631                 });
2632
2633                 // Add a Copy URL entry.
2634                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2635                     // Save the image URL in a `ClipData`.
2636                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2637
2638                     // Set the `ClipData` as the clipboard's primary clip.
2639                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
2640                     return false;
2641                 });
2642
2643                 // Add an Open with App entry.
2644                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2645                     openWithApp(imageUrl);
2646                     return false;
2647                 });
2648
2649                 // Add an Open with Browser entry.
2650                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2651                     openWithBrowser(imageUrl);
2652                     return false;
2653                 });
2654
2655                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2656                 menu.add(R.string.cancel);
2657                 break;
2658
2659
2660             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2661             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2662                 // Get the image URL.
2663                 imageUrl = hitTestResult.getExtra();
2664
2665                 // Set the image URL as the title of the `ContextMenu`.
2666                 menu.setHeaderTitle(imageUrl);
2667
2668                 // Add a `View Image` entry.
2669                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2670                     loadUrl(imageUrl);
2671                     return false;
2672                 });
2673
2674                 // Add a `Download Image` entry.
2675                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2676                     // Check if the download should be processed by an external app.
2677                     if (sharedPreferences.getBoolean("download_with_external_app", false)) {  // Download with an external app.
2678                         openUrlWithExternalApp(imageUrl);
2679                     } else {  // Download with Android's download manager.
2680                         // Check to see if the storage permission has already been granted.
2681                         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {  // The storage permission needs to be requested.
2682                             // Store the image URL for use by `onRequestPermissionResult()`.
2683                             downloadImageUrl = imageUrl;
2684
2685                             // Show a dialog if the user has previously denied the permission.
2686                             if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2687                                 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2688                                 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2689
2690                                 // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2691                                 downloadLocationPermissionDialogFragment.show(fragmentManager, getString(R.string.download_location));
2692                             } else {  // Show the permission request directly.
2693                                 // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2694                                 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2695                             }
2696                         } else {  // The storage permission has already been granted.
2697                             // Get a handle for the download image alert dialog.
2698                             DialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2699
2700                             // Show the download image alert dialog.
2701                             downloadImageDialogFragment.show(fragmentManager, getString(R.string.download));
2702                         }
2703                     }
2704                     return false;
2705                 });
2706
2707                 // Add a `Copy URL` entry.
2708                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2709                     // Save the image URL in a `ClipData`.
2710                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2711
2712                     // Set the `ClipData` as the clipboard's primary clip.
2713                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2714                     return false;
2715                 });
2716
2717                 // Add an Open with App entry.
2718                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2719                     openWithApp(imageUrl);
2720                     return false;
2721                 });
2722
2723                 // Add an Open with Browser entry.
2724                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2725                     openWithBrowser(imageUrl);
2726                     return false;
2727                 });
2728
2729                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2730                 menu.add(R.string.cancel);
2731                 break;
2732         }
2733     }
2734
2735     @Override
2736     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2737         // Get a handle for the bookmarks list view.
2738         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2739
2740         // Get the views from the dialog fragment.
2741         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2742         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2743
2744         // Extract the strings from the edit texts.
2745         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2746         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2747
2748         // Create a favorite icon byte array output stream.
2749         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2750
2751         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2752         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2753
2754         // Convert the favorite icon byte array stream to a byte array.
2755         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2756
2757         // Display the new bookmark below the current items in the (0 indexed) list.
2758         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2759
2760         // Create the bookmark.
2761         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2762
2763         // Update the bookmarks cursor with the current contents of this folder.
2764         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2765
2766         // Update the list view.
2767         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2768
2769         // Scroll to the new bookmark.
2770         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2771     }
2772
2773     @Override
2774     public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2775         // Get a handle for the bookmarks list view.
2776         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2777
2778         // Get handles for the views in the dialog fragment.
2779         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2780         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2781         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2782
2783         // Get new folder name string.
2784         String folderNameString = createFolderNameEditText.getText().toString();
2785
2786         // Create a folder icon bitmap.
2787         Bitmap folderIconBitmap;
2788
2789         // Set the folder icon bitmap according to the dialog.
2790         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2791             // Get the default folder icon drawable.
2792             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2793
2794             // Convert the folder icon drawable to a bitmap drawable.
2795             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2796
2797             // Convert the folder icon bitmap drawable to a bitmap.
2798             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2799         } else {  // Use the WebView favorite icon.
2800             // Copy the favorite icon bitmap to the folder icon bitmap.
2801             folderIconBitmap = favoriteIconBitmap;
2802         }
2803
2804         // Create a folder icon byte array output stream.
2805         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2806
2807         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2808         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2809
2810         // Convert the folder icon byte array stream to a byte array.
2811         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2812
2813         // Move all the bookmarks down one in the display order.
2814         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2815             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2816             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2817         }
2818
2819         // Create the folder, which will be placed at the top of the `ListView`.
2820         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2821
2822         // Update the bookmarks cursor with the current contents of this folder.
2823         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2824
2825         // Update the `ListView`.
2826         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2827
2828         // Scroll to the new folder.
2829         bookmarksListView.setSelection(0);
2830     }
2831
2832     @Override
2833     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2834         // Get handles for the views from `dialogFragment`.
2835         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2836         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2837         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2838
2839         // Store the bookmark strings.
2840         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2841         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2842
2843         // Update the bookmark.
2844         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
2845             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2846         } else {  // Update the bookmark using the `WebView` favorite icon.
2847             // Create a favorite icon byte array output stream.
2848             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2849
2850             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2851             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2852
2853             // Convert the favorite icon byte array stream to a byte array.
2854             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2855
2856             //  Update the bookmark and the favorite icon.
2857             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2858         }
2859
2860         // Update the bookmarks cursor with the current contents of this folder.
2861         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2862
2863         // Update the list view.
2864         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2865     }
2866
2867     @Override
2868     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2869         // Get handles for the views from `dialogFragment`.
2870