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