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