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