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