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