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