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