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