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