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