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