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