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