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