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