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