]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Fix “Waiting for Orbot”. https://redmine.stoutner.com/issues/307
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.ActivityNotFoundException;
29 import android.content.BroadcastReceiver;
30 import android.content.ClipData;
31 import android.content.ClipboardManager;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageManager;
37 import android.content.res.Configuration;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Typeface;
42 import android.graphics.drawable.BitmapDrawable;
43 import android.graphics.drawable.Drawable;
44 import android.net.Uri;
45 import android.net.http.SslCertificate;
46 import android.net.http.SslError;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.Environment;
50 import android.os.Handler;
51 import android.preference.PreferenceManager;
52 import android.print.PrintDocumentAdapter;
53 import android.print.PrintManager;
54 import android.support.annotation.NonNull;
55 import android.support.design.widget.CoordinatorLayout;
56 import android.support.design.widget.FloatingActionButton;
57 import android.support.design.widget.NavigationView;
58 import android.support.design.widget.Snackbar;
59 import android.support.v4.app.ActivityCompat;
60 import android.support.v4.content.ContextCompat;
61 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
62 import android.support.v4.content.pm.ShortcutInfoCompat;
63 import android.support.v4.content.pm.ShortcutManagerCompat;
64 import android.support.v4.graphics.drawable.IconCompat;
65 import android.support.v4.view.GravityCompat;
66 import android.support.v4.widget.DrawerLayout;
67 import android.support.v4.widget.SwipeRefreshLayout;
68 import android.support.v7.app.ActionBar;
69 import android.support.v7.app.ActionBarDrawerToggle;
70 import android.support.v7.app.AppCompatActivity;
71 import android.support.v7.app.AppCompatDialogFragment;
72 import android.support.v7.widget.Toolbar;
73 import android.text.Editable;
74 import android.text.Spanned;
75 import android.text.TextWatcher;
76 import android.text.style.ForegroundColorSpan;
77 import android.util.Patterns;
78 import android.view.ContextMenu;
79 import android.view.GestureDetector;
80 import android.view.KeyEvent;
81 import android.view.Menu;
82 import android.view.MenuItem;
83 import android.view.MotionEvent;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.WindowManager;
87 import android.view.inputmethod.InputMethodManager;
88 import android.webkit.CookieManager;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.SslErrorHandler;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebBackForwardList;
93 import android.webkit.WebChromeClient;
94 import android.webkit.WebResourceResponse;
95 import android.webkit.WebStorage;
96 import android.webkit.WebView;
97 import android.webkit.WebViewClient;
98 import android.webkit.WebViewDatabase;
99 import android.widget.ArrayAdapter;
100 import android.widget.CursorAdapter;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.ImageView;
104 import android.widget.LinearLayout;
105 import android.widget.ListView;
106 import android.widget.ProgressBar;
107 import android.widget.RadioButton;
108 import android.widget.RelativeLayout;
109 import android.widget.TextView;
110
111 import com.stoutner.privacybrowser.BuildConfig;
112 import com.stoutner.privacybrowser.R;
113 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
122 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
123 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
124 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
125 import com.stoutner.privacybrowser.helpers.AdHelper;
126 import com.stoutner.privacybrowser.helpers.BlockListHelper;
127 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
128 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
130 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
131 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
132
133 import java.io.ByteArrayInputStream;
134 import java.io.ByteArrayOutputStream;
135 import java.io.File;
136 import java.io.IOException;
137 import java.io.UnsupportedEncodingException;
138 import java.net.MalformedURLException;
139 import java.net.URL;
140 import java.net.URLDecoder;
141 import java.net.URLEncoder;
142 import java.util.ArrayList;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map;
148 import java.util.Set;
149
150 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
151 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
152         CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
153         DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
154         HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
155         SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
156
157     // `darkTheme` is public static so it can be accessed from everywhere.
158     public static boolean darkTheme;
159
160     // `allowScreenshots` is public static so it can be accessed from everywhere.  It is also used in `onCreate()`.
161     public static boolean allowScreenshots;
162
163     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
164     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
165     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
166     public static Bitmap favoriteIconBitmap;
167
168     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
169     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
170     public static String formattedUrlString;
171
172     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
173     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
174     public static SslCertificate sslCertificate;
175
176     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()` and `onResume()`.
177     public static String orbotStatus;
178
179     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
180     public static String webViewTitle;
181
182     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
183     public static String appliedUserAgentString;
184
185     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
186     public static boolean reloadOnRestart;
187
188     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`.  It is also used in `onRestart()`.
189     public static boolean loadUrlOnRestart;
190
191     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
192     public static boolean restartFromBookmarksActivity;
193
194     // The block list versions are public static so they can be accessed from `AboutTabFragment`.  They are also used in `onCreate()`.
195     public static String easyListVersion;
196     public static String easyPrivacyVersion;
197     public static String fanboysAnnoyanceVersion;
198     public static String fanboysSocialVersion;
199
200     // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`.  They are also used in `onCreate()`.
201     public static List<String[]> resourceRequests;
202     public static String[] whiteListResultStringArray;
203     public final static int REQUEST_DISPOSITION = 0;
204     public final static int REQUEST_URL = 1;
205     public final static int REQUEST_BLOCKLIST = 2;
206     public final static int REQUEST_SUBLIST = 3;
207     public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
208     public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
209
210     public final static int REQUEST_DEFAULT = 0;
211     public final static int REQUEST_ALLOWED = 1;
212     public final static int REQUEST_THIRD_PARTY = 2;
213     public final static int REQUEST_BLOCKED = 3;
214
215     public final static int MAIN_WHITELIST = 1;
216     public final static int FINAL_WHITELIST = 2;
217     public final static int DOMAIN_WHITELIST = 3;
218     public final static int DOMAIN_INITIAL_WHITELIST = 4;
219     public final static int DOMAIN_FINAL_WHITELIST = 5;
220     public final static int THIRD_PARTY_WHITELIST = 6;
221     public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
222     public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
223
224     public final static int MAIN_BLACKLIST = 9;
225     public final static int INITIAL_BLACKLIST = 10;
226     public final static int FINAL_BLACKLIST = 11;
227     public final static int DOMAIN_BLACKLIST = 12;
228     public final static int DOMAIN_INITIAL_BLACKLIST = 13;
229     public final static int DOMAIN_FINAL_BLACKLIST = 14;
230     public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
231     public final static int THIRD_PARTY_BLACKLIST = 16;
232     public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
233     public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
234     public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
235     public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
236     public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
237     public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
238
239     // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
240     // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
241     public static boolean blockAllThirdPartyRequests;
242
243     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
244     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
245     public static String currentBookmarksFolder;
246
247     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
248     public static int domainSettingsDatabaseId;
249
250     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
251     public static String pinnedDomainSslIssuedToCNameString;
252     public static String pinnedDomainSslIssuedToONameString;
253     public static String pinnedDomainSslIssuedToUNameString;
254     public static String pinnedDomainSslIssuedByCNameString;
255     public static String pinnedDomainSslIssuedByONameString;
256     public static String pinnedDomainSslIssuedByUNameString;
257     public static Date pinnedDomainSslStartDate;
258     public static Date pinnedDomainSslEndDate;
259
260     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
261     public final static int UNRECOGNIZED_USER_AGENT = -1;
262     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
263     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
264     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
265     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
266     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
267
268
269     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
270     private ActionBar appBar;
271
272     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
273     private boolean navigatingHistory;
274
275     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
276     private Bitmap favoriteIconDefaultBitmap;
277
278     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
279     private DrawerLayout drawerLayout;
280
281     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
282     private CoordinatorLayout rootCoordinatorLayout;
283
284     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
285     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
286     private WebView mainWebView;
287
288     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
289     private FrameLayout fullScreenVideoFrameLayout;
290
291     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
292     private SwipeRefreshLayout swipeRefreshLayout;
293
294     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
295     private RelativeLayout urlAppBarRelativeLayout;
296
297     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
298     private ImageView favoriteIconImageView;
299
300     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
301     private CookieManager cookieManager;
302
303     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
304     private final Map<String, String> customHeaders = new HashMap<>();
305
306     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
307     private boolean javaScriptEnabled;
308
309     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
310     private boolean firstPartyCookiesEnabled;
311
312     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
313     private boolean thirdPartyCookiesEnabled;
314
315     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
316     private boolean domStorageEnabled;
317
318     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.  It can be removed once the minimum API >= 26.
319     private boolean saveFormDataEnabled;
320
321     // `nightMode` is used in `onCreate()` and  `applyDomainSettings()`.
322     private boolean nightMode;
323
324     // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
325     private boolean displayWebpageImagesBoolean;
326
327     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
328     private String homepage;
329
330     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
331     private String searchURL;
332
333     // The block list variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
334     private boolean easyListEnabled;
335     private boolean easyPrivacyEnabled;
336     private boolean fanboysAnnoyanceListEnabled;
337     private boolean fanboysSocialBlockingListEnabled;
338
339     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
340     private Runtime privacyBrowserRuntime;
341
342     // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
343     private boolean proxyThroughOrbot;
344
345     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
346     private boolean incognitoModeEnabled;
347
348     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
349     private boolean fullScreenBrowsingModeEnabled;
350
351     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
352     private boolean inFullScreenBrowsingMode;
353
354     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
355     private boolean hideSystemBarsOnFullscreen;
356
357     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
358     private boolean translucentNavigationBarOnFullscreen;
359
360     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
361     private boolean reapplyDomainSettingsOnRestart;
362
363     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
364     private boolean reapplyAppSettingsOnRestart;
365
366     // `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()`, `onResume()`, 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                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1193                     formattedUrlString = "";
1194
1195                     // Apply the domain settings for the new URL.  `applyDomainSettings` doesn't do anything if the domain has not changed.
1196                     applyDomainSettings(url, true, false);
1197
1198                     // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1199                     return false;
1200                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1201                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1202                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1203
1204                     // Parse the url and set it as the data for the intent.
1205                     emailIntent.setData(Uri.parse(url));
1206
1207                     // Open the email program in a new task instead of as part of Privacy Browser.
1208                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1209
1210                     // Make it so.
1211                     startActivity(emailIntent);
1212
1213                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1214                     return true;
1215                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1216                     // Open the dialer and load the phone number, but wait for the user to place the call.
1217                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1218
1219                     // Add the phone number to the intent.
1220                     dialIntent.setData(Uri.parse(url));
1221
1222                     // Open the dialer in a new task instead of as part of Privacy Browser.
1223                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1224
1225                     // Make it so.
1226                     startActivity(dialIntent);
1227
1228                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1229                     return true;
1230                 } else {  // Load a system chooser to select an app that can handle the URL.
1231                     // Open an app that can handle the URL.
1232                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1233
1234                     // Add the URL to the intent.
1235                     genericIntent.setData(Uri.parse(url));
1236
1237                     // List all apps that can handle the URL instead of just opening the first one.
1238                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1239
1240                     // Open the app in a new task instead of as part of Privacy Browser.
1241                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1242
1243                     // Start the app or display a snackbar if no app is available to handle the URL.
1244                     try {
1245                         startActivity(genericIntent);
1246                     } catch (ActivityNotFoundException exception) {
1247                         Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
1248                     }
1249
1250                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1251                     return true;
1252                 }
1253             }
1254
1255             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1256             @SuppressWarnings("deprecation")
1257             @Override
1258             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1259                 // Create an empty web resource response to be used if the resource request is blocked.
1260                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1261
1262                 // Reset `whiteListResultStringArray`.
1263                 whiteListResultStringArray = null;
1264
1265                 // Initialize the third party request tracker.
1266                 boolean isThirdPartyRequest = false;
1267
1268                 // Initialize the current domain string.
1269                 String currentDomain = "";
1270
1271                 // Nobody is happy when comparing null strings.
1272                 if (!(formattedUrlString == null) && !(url == null)) {
1273                     // Get the domain strings to URIs.
1274                     Uri currentDomainUri = Uri.parse(formattedUrlString);
1275                     Uri requestDomainUri = Uri.parse(url);
1276
1277                     // Get the domain host names.
1278                     String currentBaseDomain = currentDomainUri.getHost();
1279                     String requestBaseDomain = requestDomainUri.getHost();
1280
1281                     // Update the current domain variable.
1282                     currentDomain = currentBaseDomain;
1283
1284                     // Only compare the current base domain and the request base domain if neither is null.
1285                     if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1286                         // Determine the current base domain.
1287                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1288                             // Remove the first subdomain.
1289                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1290                         }
1291
1292                         // Determine the request base domain.
1293                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1294                             // Remove the first subdomain.
1295                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1296                         }
1297
1298                         // Update the third party request tracker.
1299                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1300                     }
1301                 }
1302
1303                 // Block third-party requests if enabled.
1304                 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1305                     // Add the request to the log.
1306                     resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1307
1308                     // Return an empty web resource response.
1309                     return emptyWebResourceResponse;
1310                 }
1311
1312                 // Check EasyList if it is enabled.
1313                 if (easyListEnabled) {
1314                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1315                         // The resource request was blocked.  Return an empty web resource response.
1316                         return emptyWebResourceResponse;
1317                     }
1318                 }
1319
1320                 // Check EasyPrivacy if it is enabled.
1321                 if (easyPrivacyEnabled) {
1322                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1323                         // The resource request was blocked.  Return an empty web resource response.
1324                         return emptyWebResourceResponse;
1325                     }
1326                 }
1327
1328                 // Check Fanboy’s Annoyance List if it is enabled.
1329                 if (fanboysAnnoyanceListEnabled) {
1330                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1331                         // The resource request was blocked.  Return an empty web resource response.
1332                         return emptyWebResourceResponse;
1333                     }
1334                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1335                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1336                         // The resource request was blocked.  Return an empty web resource response.
1337                         return emptyWebResourceResponse;
1338                     }
1339                 }
1340
1341                 // Add the request to the log because it hasn't been processed by any of the previous checks.
1342                 if (whiteListResultStringArray != null ) {  // The request was processed by a whitelist.
1343                     resourceRequests.add(whiteListResultStringArray);
1344                 } else {  // The request didn't match any blocklist entry.  Log it as a defult request.
1345                     resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1346                 }
1347
1348                 // The resource request has not been blocked.  `return null` loads the requested resource.
1349                 return null;
1350             }
1351
1352             // Handle HTTP authentication requests.
1353             @Override
1354             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1355                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1356                 httpAuthHandler = handler;
1357
1358                 // Display the HTTP authentication dialog.
1359                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1360                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1361             }
1362
1363             // Update the URL in urlTextBox when the page starts to load.
1364             @Override
1365             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1366                 // Reset the list of resource requests.
1367                 resourceRequests.clear();
1368
1369                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1370                 if (nightMode) {
1371                     mainWebView.setVisibility(View.INVISIBLE);
1372                 }
1373
1374                 // Hide the keyboard.  `0` indicates no additional flags.
1375                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1376
1377                 // Check to see if Privacy Browser is waiting on Orbot.
1378                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1379                     // 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.
1380                     formattedUrlString = url;
1381
1382                     // Display the formatted URL text.
1383                     urlTextBox.setText(formattedUrlString);
1384
1385                     // Apply text highlighting to `urlTextBox`.
1386                     highlightUrlText();
1387
1388                     // Apply any custom domain settings if the URL was loaded by navigating history.
1389                     if (navigatingHistory) {
1390                         // Reset `navigatingHistory`.
1391                         navigatingHistory = false;
1392
1393                         // Apply the domain settings.
1394                         applyDomainSettings(url, true, false);
1395                     }
1396
1397                     // 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.
1398                     urlIsLoading = true;
1399                 }
1400             }
1401
1402             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1403             @Override
1404             public void onPageFinished(WebView view, String url) {
1405                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1406                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1407                     cookieManager.flush();
1408                 }
1409
1410                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1411                 urlIsLoading = false;
1412
1413                 // Clear the cache and history if Incognito Mode is enabled.
1414                 if (incognitoModeEnabled) {
1415                     // Clear the cache.  `true` includes disk files.
1416                     mainWebView.clearCache(true);
1417
1418                     // Clear the back/forward history.
1419                     mainWebView.clearHistory();
1420
1421                     // Manually delete cache folders.
1422                     try {
1423                         // Delete the main cache directory.
1424                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1425
1426                         // Delete the secondary `Service Worker` cache directory.
1427                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1428                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1429                     } catch (IOException e) {
1430                         // Do nothing if an error is thrown.
1431                     }
1432                 }
1433
1434                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1435                 if (!waitingForOrbot) {
1436                     // Check to see if `WebView` has set `url` to be `about:blank`.
1437                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1438                         // Set `formattedUrlString` to `""`.
1439                         formattedUrlString = "";
1440
1441                         urlTextBox.setText(formattedUrlString);
1442
1443                         // Request focus for `urlTextBox`.
1444                         urlTextBox.requestFocus();
1445
1446                         // Display the keyboard.
1447                         inputMethodManager.showSoftInput(urlTextBox, 0);
1448
1449                         // Apply the domain settings.  This clears any settings from the previous domain.
1450                         applyDomainSettings(formattedUrlString, true, false);
1451                     } else {  // `WebView` has loaded a webpage.
1452                         // Set `formattedUrlString`.
1453                         formattedUrlString = url;
1454
1455                         // Only update `urlTextBox` if the user is not typing in it.
1456                         if (!urlTextBox.hasFocus()) {
1457                             // Display the formatted URL text.
1458                             urlTextBox.setText(formattedUrlString);
1459
1460                             // Apply text highlighting to `urlTextBox`.
1461                             highlightUrlText();
1462                         }
1463                     }
1464
1465                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1466                     sslCertificate = mainWebView.getCertificate();
1467
1468                     // 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.
1469                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1470                         // Initialize the current SSL certificate variables.
1471                         String currentWebsiteIssuedToCName = "";
1472                         String currentWebsiteIssuedToOName = "";
1473                         String currentWebsiteIssuedToUName = "";
1474                         String currentWebsiteIssuedByCName = "";
1475                         String currentWebsiteIssuedByOName = "";
1476                         String currentWebsiteIssuedByUName = "";
1477                         Date currentWebsiteSslStartDate = null;
1478                         Date currentWebsiteSslEndDate = null;
1479
1480
1481                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1482                         if (sslCertificate != null) {
1483                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1484                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1485                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1486                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1487                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1488                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1489                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1490                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1491                         }
1492
1493                         // 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`.
1494                         String currentWebsiteSslStartDateString = "";
1495                         String currentWebsiteSslEndDateString = "";
1496                         String pinnedDomainSslStartDateString = "";
1497                         String pinnedDomainSslEndDateString = "";
1498
1499                         // Convert the `Dates` to `Strings` if they are not `null`.
1500                         if (currentWebsiteSslStartDate != null) {
1501                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1502                         }
1503
1504                         if (currentWebsiteSslEndDate != null) {
1505                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1506                         }
1507
1508                         if (pinnedDomainSslStartDate != null) {
1509                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1510                         }
1511
1512                         if (pinnedDomainSslEndDate != null) {
1513                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1514                         }
1515
1516                         // Check to see if the pinned SSL certificate matches the current website certificate.
1517                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1518                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1519                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1520                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1521                             // The pinned SSL certificate doesn't match the current domain certificate.
1522                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1523                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1524                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1525                         }
1526                     }
1527                 }
1528             }
1529
1530             // Handle SSL Certificate errors.
1531             @Override
1532             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1533                 // Get the current website SSL certificate.
1534                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1535
1536                 // Extract the individual pieces of information from the current website SSL certificate.
1537                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1538                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1539                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1540                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1541                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1542                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1543                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1544                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1545
1546                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1547                 if (pinnedDomainSslCertificate &&
1548                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1549                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1550                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1551                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1552                     // An SSL certificate is pinned and matches the current domain certificate.
1553                     // Proceed to the website without displaying an error.
1554                     handler.proceed();
1555                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1556                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1557                     sslErrorHandler = handler;
1558
1559                     // Display the SSL error `AlertDialog`.
1560                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1561                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1562                 }
1563             }
1564         });
1565
1566         // Load the website if not waiting for Orbot to connect.
1567         if (!waitingForOrbot) {
1568             loadUrl(formattedUrlString);
1569         }
1570     }
1571
1572     @Override
1573     protected void onNewIntent(Intent intent) {
1574         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1575         setIntent(intent);
1576
1577         // Check to see if the intent contains a new URL.
1578         if (intent.getData() != null) {
1579             // Get the intent data.
1580             final Uri intentUriData = intent.getData();
1581
1582             // Load the website.
1583             loadUrl(intentUriData.toString());
1584
1585             // Close the navigation drawer if it is open.
1586             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1587                 drawerLayout.closeDrawer(GravityCompat.START);
1588             }
1589
1590             // Close the bookmarks drawer if it is open.
1591             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1592                 drawerLayout.closeDrawer(GravityCompat.END);
1593             }
1594
1595             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1596             mainWebView.requestFocus();
1597         }
1598     }
1599
1600     @Override
1601     public void onRestart() {
1602         // Run the default commands.
1603         super.onRestart();
1604
1605         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1606         if (proxyThroughOrbot) {
1607             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1608             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1609
1610             // Send the intent to the Orbot package.
1611             orbotIntent.setPackage("org.torproject.android");
1612
1613             // Make it so.
1614             sendBroadcast(orbotIntent);
1615         }
1616
1617         // Apply the app settings if returning from the Settings activity..
1618         if (reapplyAppSettingsOnRestart) {
1619             // Apply the app settings.
1620             applyAppSettings();
1621
1622             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1623             if (reloadOnRestart) {
1624                 // Reload `mainWebView`.
1625                 mainWebView.reload();
1626
1627                 // Reset `reloadOnRestartBoolean`.
1628                 reloadOnRestart = false;
1629             }
1630
1631             // Reset the return from settings flag.
1632             reapplyAppSettingsOnRestart = false;
1633         }
1634
1635         // Apply the domain settings if returning from the Domains activity.
1636         if (reapplyDomainSettingsOnRestart) {
1637             // Reapply the domain settings.
1638             applyDomainSettings(formattedUrlString, false, true);
1639
1640             // Reset `reapplyDomainSettingsOnRestart`.
1641             reapplyDomainSettingsOnRestart = false;
1642         }
1643
1644         // Load the URL on restart to apply changes to night mode.
1645         if (loadUrlOnRestart) {
1646             // Load the current `formattedUrlString`.
1647             loadUrl(formattedUrlString);
1648
1649             // Reset `loadUrlOnRestart.
1650             loadUrlOnRestart = false;
1651         }
1652
1653         // Update the bookmarks drawer if returning from the Bookmarks activity.
1654         if (restartFromBookmarksActivity) {
1655             // Close the bookmarks drawer.
1656             drawerLayout.closeDrawer(GravityCompat.END);
1657
1658             // Reload the bookmarks drawer.
1659             loadBookmarksFolder();
1660
1661             // Reset `restartFromBookmarksActivity`.
1662             restartFromBookmarksActivity = false;
1663         }
1664
1665         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1666         updatePrivacyIcons(true);
1667     }
1668
1669     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1670     @Override
1671     public void onResume() {
1672         // Run the default commands.
1673         super.onResume();
1674
1675         // Resume JavaScript (if enabled).
1676         mainWebView.resumeTimers();
1677
1678         // Resume `mainWebView`.
1679         mainWebView.onResume();
1680
1681         // Resume the adView for the free flavor.
1682         if (BuildConfig.FLAVOR.contentEquals("free")) {
1683             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1684             AdHelper.resumeAd(findViewById(R.id.adview));
1685         }
1686
1687         // Display a message to the user if waiting for Orbot.
1688         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1689             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1690             mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1691         }
1692     }
1693
1694     @Override
1695     public void onPause() {
1696         // Pause `mainWebView`.
1697         mainWebView.onPause();
1698
1699         // Stop all JavaScript.
1700         mainWebView.pauseTimers();
1701
1702         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1703         if (BuildConfig.FLAVOR.contentEquals("free")) {
1704             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1705             AdHelper.pauseAd(findViewById(R.id.adview));
1706         }
1707
1708         super.onPause();
1709     }
1710
1711     @Override
1712     public boolean onCreateOptionsMenu(Menu menu) {
1713         // Inflate the menu; this adds items to the action bar if it is present.
1714         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1715
1716         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1717         mainMenu = menu;
1718
1719         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1720         updatePrivacyIcons(false);
1721
1722         // Get handles for the menu items.
1723         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1724         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1725         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1726         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1727         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1728         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1729         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1730
1731         // Only display third-party cookies if API >= 21
1732         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1733
1734         // Only display the form data menu items if the API < 26.
1735         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1736         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1737
1738         // Only show Ad Consent if this is the free flavor.
1739         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1740
1741         // Get the shared preference values.  `this` references the current context.
1742         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1743
1744         // 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.
1745         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1746             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1747             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1748             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1749         } else { //Do not display the additional icons.
1750             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1751             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1752             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1753         }
1754
1755         return true;
1756     }
1757
1758     @Override
1759     public boolean onPrepareOptionsMenu(Menu menu) {
1760         // Get handles for the menu items.
1761         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1762         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1763         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1764         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1765         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1766         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1767         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1768         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1769         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1770         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1771         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1772         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1773         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1774         MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1775         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1776         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1777         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1778
1779         // Set the text for the domain menu item.
1780         if (domainSettingsApplied) {
1781             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1782         } else {
1783             addOrEditDomain.setTitle(R.string.add_domain_settings);
1784         }
1785
1786         // Set the status of the menu item checkboxes.
1787         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1788         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1789         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1790         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1791         easyListMenuItem.setChecked(easyListEnabled);
1792         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1793         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1794         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1795         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1796         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1797         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1798
1799         // Enable third-party cookies if first-party cookies are enabled.
1800         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1801
1802         // Enable DOM Storage if JavaScript is enabled.
1803         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1804
1805         // Enable Clear Cookies if there are any.
1806         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1807
1808         // Get a count of the number of files in the Local Storage directory.
1809         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1810         int localStorageDirectoryNumberOfFiles = 0;
1811         if (localStorageDirectory.exists()) {
1812             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1813         }
1814
1815         // Get a count of the number of files in the IndexedDB directory.
1816         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1817         int indexedDBDirectoryNumberOfFiles = 0;
1818         if (indexedDBDirectory.exists()) {
1819             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1820         }
1821
1822         // Enable Clear DOM Storage if there is any.
1823         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1824
1825         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1826         if (Build.VERSION.SDK_INT < 26) {
1827             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1828             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1829         }
1830
1831         // Enable Clear Data if any of the submenu items are enabled.
1832         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1833
1834         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1835         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1836
1837         // Initialize font size variables.
1838         int fontSize = mainWebView.getSettings().getTextZoom();
1839         String fontSizeTitle;
1840         MenuItem selectedFontSizeMenuItem;
1841
1842         // Prepare the font size title and current size menu item.
1843         switch (fontSize) {
1844             case 25:
1845                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1846                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1847                 break;
1848
1849             case 50:
1850                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1851                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1852                 break;
1853
1854             case 75:
1855                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1856                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1857                 break;
1858
1859             case 100:
1860                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1861                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1862                 break;
1863
1864             case 125:
1865                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1866                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1867                 break;
1868
1869             case 150:
1870                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1871                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1872                 break;
1873
1874             case 175:
1875                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1876                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1877                 break;
1878
1879             case 200:
1880                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1881                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1882                 break;
1883
1884             default:
1885                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1886                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1887                 break;
1888         }
1889
1890         // Set the font size title and select the current size menu item.
1891         fontSizeMenuItem.setTitle(fontSizeTitle);
1892         selectedFontSizeMenuItem.setChecked(true);
1893
1894         // Run all the other default commands.
1895         super.onPrepareOptionsMenu(menu);
1896
1897         // Display the menu.
1898         return true;
1899     }
1900
1901     @Override
1902     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1903     @SuppressLint("SetJavaScriptEnabled")
1904     // removeAllCookies is deprecated, but it is required for API < 21.
1905     @SuppressWarnings("deprecation")
1906     public boolean onOptionsItemSelected(MenuItem menuItem) {
1907         // Get the selected menu item ID.
1908         int menuItemId = menuItem.getItemId();
1909
1910         // Set the commands that relate to the menu entries.
1911         switch (menuItemId) {
1912             case R.id.toggle_javascript:
1913                 // Switch the status of javaScriptEnabled.
1914                 javaScriptEnabled = !javaScriptEnabled;
1915
1916                 // Apply the new JavaScript status.
1917                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1918
1919                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1920                 updatePrivacyIcons(true);
1921
1922                 // Display a `Snackbar`.
1923                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1924                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1925                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1926                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1927                 } else {  // Privacy mode.
1928                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1929                 }
1930
1931                 // Reload the WebView.
1932                 mainWebView.reload();
1933                 return true;
1934
1935             case R.id.add_or_edit_domain:
1936                 if (domainSettingsApplied) {  // Edit the current domain settings.
1937                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1938                     reapplyDomainSettingsOnRestart = true;
1939                     currentDomainName = "";
1940
1941                     // Create an intent to launch the domains activity.
1942                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1943
1944                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1945                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1946                     domainsIntent.putExtra("closeOnBack", true);
1947
1948                     // Make it so.
1949                     startActivity(domainsIntent);
1950                 } else {  // Add a new domain.
1951                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1952                     reapplyDomainSettingsOnRestart = true;
1953                     currentDomainName = "";
1954
1955                     // Get the current domain
1956                     Uri currentUri = Uri.parse(formattedUrlString);
1957                     String currentDomain = currentUri.getHost();
1958
1959                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1960                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1961
1962                     // Create the domain and store the database ID.
1963                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1964
1965                     // Create an intent to launch the domains activity.
1966                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1967
1968                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1969                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1970                     domainsIntent.putExtra("closeOnBack", true);
1971
1972                     // Make it so.
1973                     startActivity(domainsIntent);
1974                 }
1975                 return true;
1976
1977             case R.id.toggle_first_party_cookies:
1978                 // Switch the status of firstPartyCookiesEnabled.
1979                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1980
1981                 // Update the menu checkbox.
1982                 menuItem.setChecked(firstPartyCookiesEnabled);
1983
1984                 // Apply the new cookie status.
1985                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1986
1987                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1988                 updatePrivacyIcons(true);
1989
1990                 // Display a `Snackbar`.
1991                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1992                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1993                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
1994                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1995                 } else {  // Privacy mode.
1996                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1997                 }
1998
1999                 // Reload the WebView.
2000                 mainWebView.reload();
2001                 return true;
2002
2003             case R.id.toggle_third_party_cookies:
2004                 if (Build.VERSION.SDK_INT >= 21) {
2005                     // Switch the status of thirdPartyCookiesEnabled.
2006                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2007
2008                     // Update the menu checkbox.
2009                     menuItem.setChecked(thirdPartyCookiesEnabled);
2010
2011                     // Apply the new cookie status.
2012                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2013
2014                     // Display a `Snackbar`.
2015                     if (thirdPartyCookiesEnabled) {
2016                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2017                     } else {
2018                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2019                     }
2020
2021                     // Reload the WebView.
2022                     mainWebView.reload();
2023                 } // Else do nothing because SDK < 21.
2024                 return true;
2025
2026             case R.id.toggle_dom_storage:
2027                 // Switch the status of domStorageEnabled.
2028                 domStorageEnabled = !domStorageEnabled;
2029
2030                 // Update the menu checkbox.
2031                 menuItem.setChecked(domStorageEnabled);
2032
2033                 // Apply the new DOM Storage status.
2034                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2035
2036                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2037                 updatePrivacyIcons(true);
2038
2039                 // Display a `Snackbar`.
2040                 if (domStorageEnabled) {
2041                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2042                 } else {
2043                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2044                 }
2045
2046                 // Reload the WebView.
2047                 mainWebView.reload();
2048                 return true;
2049
2050             // Form data can be removed once the minimum API >= 26.
2051             case R.id.toggle_save_form_data:
2052                 // Switch the status of saveFormDataEnabled.
2053                 saveFormDataEnabled = !saveFormDataEnabled;
2054
2055                 // Update the menu checkbox.
2056                 menuItem.setChecked(saveFormDataEnabled);
2057
2058                 // Apply the new form data status.
2059                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2060
2061                 // Display a `Snackbar`.
2062                 if (saveFormDataEnabled) {
2063                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2064                 } else {
2065                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2066                 }
2067
2068                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2069                 updatePrivacyIcons(true);
2070
2071                 // Reload the WebView.
2072                 mainWebView.reload();
2073                 return true;
2074
2075             case R.id.clear_cookies:
2076                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2077                         .setAction(R.string.undo, v -> {
2078                             // Do nothing because everything will be handled by `onDismissed()` below.
2079                         })
2080                         .addCallback(new Snackbar.Callback() {
2081                             @Override
2082                             public void onDismissed(Snackbar snackbar, int event) {
2083                                 switch (event) {
2084                                     // The user pushed the `Undo` button.
2085                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2086                                         // Do nothing.
2087                                         break;
2088
2089                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2090                                     default:
2091                                         // `cookieManager.removeAllCookie()` varies by SDK.
2092                                         if (Build.VERSION.SDK_INT < 21) {
2093                                             cookieManager.removeAllCookie();
2094                                         } else {
2095                                             // `null` indicates no callback.
2096                                             cookieManager.removeAllCookies(null);
2097                                         }
2098                                 }
2099                             }
2100                         })
2101                         .show();
2102                 return true;
2103
2104             case R.id.clear_dom_storage:
2105                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2106                         .setAction(R.string.undo, v -> {
2107                             // Do nothing because everything will be handled by `onDismissed()` below.
2108                         })
2109                         .addCallback(new Snackbar.Callback() {
2110                             @Override
2111                             public void onDismissed(Snackbar snackbar, int event) {
2112                                 switch (event) {
2113                                     // The user pushed the `Undo` button.
2114                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2115                                         // Do nothing.
2116                                         break;
2117
2118                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2119                                     default:
2120                                         // Delete the DOM Storage.
2121                                         WebStorage webStorage = WebStorage.getInstance();
2122                                         webStorage.deleteAllData();
2123
2124                                         // Manually delete the DOM storage files and directories.
2125                                         try {
2126                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2127                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2128
2129                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2130                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2131                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2132                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2133                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2134                                         } catch (IOException e) {
2135                                             // Do nothing if an error is thrown.
2136                                         }
2137                                 }
2138                             }
2139                         })
2140                         .show();
2141                 return true;
2142
2143             // Form data can be remove once the minimum API >= 26.
2144             case R.id.clear_form_data:
2145                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2146                         .setAction(R.string.undo, v -> {
2147                             // Do nothing because everything will be handled by `onDismissed()` below.
2148                         })
2149                         .addCallback(new Snackbar.Callback() {
2150                             @Override
2151                             public void onDismissed(Snackbar snackbar, int event) {
2152                                 switch (event) {
2153                                     // The user pushed the `Undo` button.
2154                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2155                                         // Do nothing.
2156                                         break;
2157
2158                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2159                                     default:
2160                                         // Delete the form data.
2161                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2162                                         mainWebViewDatabase.clearFormData();
2163                                 }
2164                             }
2165                         })
2166                         .show();
2167                 return true;
2168
2169             case R.id.font_size_twenty_five_percent:
2170                 mainWebView.getSettings().setTextZoom(25);
2171                 return true;
2172
2173             case R.id.font_size_fifty_percent:
2174                 mainWebView.getSettings().setTextZoom(50);
2175                 return true;
2176
2177             case R.id.font_size_seventy_five_percent:
2178                 mainWebView.getSettings().setTextZoom(75);
2179                 return true;
2180
2181             case R.id.font_size_one_hundred_percent:
2182                 mainWebView.getSettings().setTextZoom(100);
2183                 return true;
2184
2185             case R.id.font_size_one_hundred_twenty_five_percent:
2186                 mainWebView.getSettings().setTextZoom(125);
2187                 return true;
2188
2189             case R.id.font_size_one_hundred_fifty_percent:
2190                 mainWebView.getSettings().setTextZoom(150);
2191                 return true;
2192
2193             case R.id.font_size_one_hundred_seventy_five_percent:
2194                 mainWebView.getSettings().setTextZoom(175);
2195                 return true;
2196
2197             case R.id.font_size_two_hundred_percent:
2198                 mainWebView.getSettings().setTextZoom(200);
2199                 return true;
2200
2201             case R.id.swipe_to_refresh:
2202                 // Toggle swipe to refresh.
2203                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2204                 return true;
2205
2206             case R.id.display_images:
2207                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2208                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2209                     mainWebView.reload();
2210                 } else {  // Images are not currently loaded automatically.
2211                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2212                 }
2213
2214                 // Set `onTheFlyDisplayImagesSet`.
2215                 onTheFlyDisplayImagesSet = true;
2216                 return true;
2217
2218             case R.id.view_source:
2219                 // Launch the View Source activity.
2220                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2221                 startActivity(viewSourceIntent);
2222                 return true;
2223
2224             case R.id.easylist:
2225                 // Toggle the EasyList status.
2226                 easyListEnabled = !easyListEnabled;
2227
2228                 // Update the menu checkbox.
2229                 menuItem.setChecked(easyListEnabled);
2230
2231                 // Reload the main WebView.
2232                 mainWebView.reload();
2233                 return true;
2234
2235             case R.id.easyprivacy:
2236                 // Toggle the EasyPrivacy status.
2237                 easyPrivacyEnabled = !easyPrivacyEnabled;
2238
2239                 // Update the menu checkbox.
2240                 menuItem.setChecked(easyPrivacyEnabled);
2241
2242                 // Reload the main WebView.
2243                 mainWebView.reload();
2244                 return true;
2245
2246             case R.id.fanboys_annoyance_list:
2247                 // Toggle Fanboy's Annoyance List status.
2248                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2249
2250                 // Update the menu checkbox.
2251                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2252
2253                 // Update the staus of Fanboy's Social Blocking List.
2254                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2255                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2256
2257                 // Reload the main WebView.
2258                 mainWebView.reload();
2259                 return true;
2260
2261             case R.id.fanboys_social_blocking_list:
2262                 // Toggle Fanboy's Social Blocking List status.
2263                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2264
2265                 // Update the menu checkbox.
2266                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2267
2268                 // Reload the main WebView.
2269                 mainWebView.reload();
2270                 return true;
2271
2272             case R.id.block_all_third_party_requests:
2273                 //Toggle the third-party requests blocker status.
2274                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2275
2276                 // Update the menu checkbox.
2277                 menuItem.setChecked(blockAllThirdPartyRequests);
2278
2279                 // Reload the main WebView.
2280                 mainWebView.reload();
2281                 return true;
2282
2283             case R.id.share:
2284                 // Setup the share string.
2285                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2286
2287                 // Create the share intent.
2288                 Intent shareIntent = new Intent();
2289                 shareIntent.setAction(Intent.ACTION_SEND);
2290                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2291                 shareIntent.setType("text/plain");
2292
2293                 // Make it so.
2294                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2295                 return true;
2296
2297             case R.id.find_on_page:
2298                 // Hide the URL app bar.
2299                 supportAppBar.setVisibility(View.GONE);
2300
2301                 // Show the Find on Page `RelativeLayout`.
2302                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2303
2304                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2305                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2306                 findOnPageEditText.postDelayed(() -> {
2307                     // Set the focus on `findOnPageEditText`.
2308                     findOnPageEditText.requestFocus();
2309
2310                     // Display the keyboard.  `0` sets no input flags.
2311                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2312                 }, 200);
2313                 return true;
2314
2315             case R.id.print:
2316                 // Get a `PrintManager` instance.
2317                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2318
2319                 // Convert `mainWebView` to `printDocumentAdapter`.
2320                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2321
2322                 // Remove the lint error below that `printManager` might be `null`.
2323                 assert printManager != null;
2324
2325                 // Print the document.  The print attributes are `null`.
2326                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2327                 return true;
2328
2329             case R.id.add_to_homescreen:
2330                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2331                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2332                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2333
2334                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2335                 return true;
2336
2337             case R.id.refresh:
2338                 mainWebView.reload();
2339                 return true;
2340
2341             case R.id.ad_consent:
2342                 // Display the ad consent dialog.
2343                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2344                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2345                 return true;
2346
2347             default:
2348                 // Don't consume the event.
2349                 return super.onOptionsItemSelected(menuItem);
2350         }
2351     }
2352
2353     // removeAllCookies is deprecated, but it is required for API < 21.
2354     @SuppressWarnings("deprecation")
2355     @Override
2356     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2357         int menuItemId = menuItem.getItemId();
2358
2359         switch (menuItemId) {
2360             case R.id.home:
2361                 loadUrl(homepage);
2362                 break;
2363
2364             case R.id.back:
2365                 if (mainWebView.canGoBack()) {
2366                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2367                     formattedUrlString = "";
2368
2369                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2370                     navigatingHistory = true;
2371
2372                     // Load the previous website in the history.
2373                     mainWebView.goBack();
2374                 }
2375                 break;
2376
2377             case R.id.forward:
2378                 if (mainWebView.canGoForward()) {
2379                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2380                     formattedUrlString = "";
2381
2382                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2383                     navigatingHistory = true;
2384
2385                     // Load the next website in the history.
2386                     mainWebView.goForward();
2387                 }
2388                 break;
2389
2390             case R.id.history:
2391                 // Get the `WebBackForwardList`.
2392                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2393
2394                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2395                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2396                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2397                 break;
2398
2399             case R.id.requests:
2400                 // Launch the requests activity.
2401                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2402                 startActivity(requestsIntent);
2403                 break;
2404
2405             case R.id.downloads:
2406                 // Launch the system Download Manager.
2407                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2408
2409                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2410                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2411
2412                 startActivity(downloadManagerIntent);
2413                 break;
2414
2415             case R.id.domains:
2416                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2417                 reapplyDomainSettingsOnRestart = true;
2418                 currentDomainName = "";
2419
2420                 // Launch the domains activity.
2421                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2422                 startActivity(domainsIntent);
2423                 break;
2424
2425             case R.id.settings:
2426                 // Set the flag to reapply app settings on restart when returning from Settings.
2427                 reapplyAppSettingsOnRestart = true;
2428
2429                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2430                 reapplyDomainSettingsOnRestart = true;
2431                 currentDomainName = "";
2432
2433                 // Launch the settings activity.
2434                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2435                 startActivity(settingsIntent);
2436                 break;
2437
2438             case R.id.guide:
2439                 // Launch `GuideActivity`.
2440                 Intent guideIntent = new Intent(this, GuideActivity.class);
2441                 startActivity(guideIntent);
2442                 break;
2443
2444             case R.id.about:
2445                 // Launch `AboutActivity`.
2446                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2447                 startActivity(aboutIntent);
2448                 break;
2449
2450             case R.id.clearAndExit:
2451                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2452                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2453
2454                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2455
2456                 // Clear cookies.
2457                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2458                     // The command to remove cookies changed slightly in API 21.
2459                     if (Build.VERSION.SDK_INT >= 21) {
2460                         cookieManager.removeAllCookies(null);
2461                     } else {
2462                         cookieManager.removeAllCookie();
2463                     }
2464
2465                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2466                     try {
2467                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2468                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2469                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2470                     } catch (IOException e) {
2471                         // Do nothing if an error is thrown.
2472                     }
2473                 }
2474
2475                 // Clear DOM storage.
2476                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2477                     // Ask `WebStorage` to clear the DOM storage.
2478                     WebStorage webStorage = WebStorage.getInstance();
2479                     webStorage.deleteAllData();
2480
2481                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2482                     try {
2483                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2484                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2485
2486                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2487                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2488                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2489                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2490                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2491                     } catch (IOException e) {
2492                         // Do nothing if an error is thrown.
2493                     }
2494                 }
2495
2496                 // Clear form data if the API < 26.
2497                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2498                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2499                     webViewDatabase.clearFormData();
2500
2501                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2502                     try {
2503                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2504                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2505                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2506                     } catch (IOException e) {
2507                         // Do nothing if an error is thrown.
2508                     }
2509                 }
2510
2511                 // Clear the cache.
2512                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2513                     // `true` includes disk files.
2514                     mainWebView.clearCache(true);
2515
2516                     // Manually delete the cache directories.
2517                     try {
2518                         // Delete the main cache directory.
2519                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2520
2521                         // Delete the secondary `Service Worker` cache directory.
2522                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2523                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2524                     } catch (IOException e) {
2525                         // Do nothing if an error is thrown.
2526                     }
2527                 }
2528
2529                 // Clear SSL certificate preferences.
2530                 mainWebView.clearSslPreferences();
2531
2532                 // Clear the back/forward history.
2533                 mainWebView.clearHistory();
2534
2535                 // Clear `formattedUrlString`.
2536                 formattedUrlString = null;
2537
2538                 // Clear `customHeaders`.
2539                 customHeaders.clear();
2540
2541                 // Detach all views from `mainWebViewRelativeLayout`.
2542                 mainWebViewRelativeLayout.removeAllViews();
2543
2544                 // Destroy the internal state of `mainWebView`.
2545                 mainWebView.destroy();
2546
2547                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2548                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2549                 if (clearEverything) {
2550                     try {
2551                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2552                     } catch (IOException e) {
2553                         // Do nothing if an error is thrown.
2554                     }
2555                 }
2556
2557                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2558                 if (Build.VERSION.SDK_INT >= 21) {
2559                     finishAndRemoveTask();
2560                 } else {
2561                     finish();
2562                 }
2563
2564                 // Remove the terminated program from RAM.  The status code is `0`.
2565                 System.exit(0);
2566                 break;
2567         }
2568
2569         // Close the navigation drawer.
2570         drawerLayout.closeDrawer(GravityCompat.START);
2571         return true;
2572     }
2573
2574     @Override
2575     public void onPostCreate(Bundle savedInstanceState) {
2576         super.onPostCreate(savedInstanceState);
2577
2578         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2579         drawerToggle.syncState();
2580     }
2581
2582     @Override
2583     public void onConfigurationChanged(Configuration newConfig) {
2584         super.onConfigurationChanged(newConfig);
2585
2586         // Reload the ad for the free flavor if we are not in full screen mode.
2587         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2588             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2589             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2590         }
2591
2592         // `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:
2593         // https://code.google.com/p/android/issues/detail?id=20493#c8
2594         // ActivityCompat.invalidateOptionsMenu(this);
2595     }
2596
2597     @Override
2598     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2599         // Store the `HitTestResult`.
2600         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2601
2602         // Create strings.
2603         final String imageUrl;
2604         final String linkUrl;
2605
2606         // Get a handle for the `ClipboardManager`.
2607         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2608
2609         // Remove the lint errors below that `clipboardManager` might be `null`.
2610         assert clipboardManager != null;
2611
2612         switch (hitTestResult.getType()) {
2613             // `SRC_ANCHOR_TYPE` is a link.
2614             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2615                 // Get the target URL.
2616                 linkUrl = hitTestResult.getExtra();
2617
2618                 // Set the target URL as the title of the `ContextMenu`.
2619                 menu.setHeaderTitle(linkUrl);
2620
2621                 // Add a Load URL entry.
2622                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2623                     loadUrl(linkUrl);
2624                     return false;
2625                 });
2626
2627                 // Add a Copy URL entry.
2628                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2629                     // Save the link URL in a `ClipData`.
2630                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2631
2632                     // Set the `ClipData` as the clipboard's primary clip.
2633                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2634                     return false;
2635                 });
2636
2637                 // Add a Download URL entry.
2638                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2639                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2640                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2641                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2642
2643                         // Store the variables for future use by `onRequestPermissionsResult()`.
2644                         downloadUrl = linkUrl;
2645                         downloadContentDisposition = "none";
2646                         downloadContentLength = -1;
2647
2648                         // Show a dialog if the user has previously denied the permission.
2649                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2650                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2651                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2652
2653                             // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2654                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2655                         } else {  // Show the permission request directly.
2656                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2657                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2658                         }
2659                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2660                         // Get a handle for the download file alert dialog.
2661                         AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2662
2663                         // Show the download file alert dialog.
2664                         downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2665                     }
2666                     return false;
2667                 });
2668
2669                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2670                 menu.add(R.string.cancel);
2671                 break;
2672
2673             case WebView.HitTestResult.EMAIL_TYPE:
2674                 // Get the target URL.
2675                 linkUrl = hitTestResult.getExtra();
2676
2677                 // Set the target URL as the title of the `ContextMenu`.
2678                 menu.setHeaderTitle(linkUrl);
2679
2680                 // Add a `Write Email` entry.
2681                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2682                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2683                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2684
2685                     // Parse the url and set it as the data for the `Intent`.
2686                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2687
2688                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2689                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2690
2691                     // Make it so.
2692                     startActivity(emailIntent);
2693                     return false;
2694                 });
2695
2696                 // Add a `Copy Email Address` entry.
2697                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2698                     // Save the email address in a `ClipData`.
2699                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2700
2701                     // Set the `ClipData` as the clipboard's primary clip.
2702                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2703                     return false;
2704                 });
2705
2706                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2707                 menu.add(R.string.cancel);
2708                 break;
2709
2710             // `IMAGE_TYPE` is an image.
2711             case WebView.HitTestResult.IMAGE_TYPE:
2712                 // Get the image URL.
2713                 imageUrl = hitTestResult.getExtra();
2714
2715                 // Set the image URL as the title of the `ContextMenu`.
2716                 menu.setHeaderTitle(imageUrl);
2717
2718                 // Add a `View Image` entry.
2719                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2720                     loadUrl(imageUrl);
2721                     return false;
2722                 });
2723
2724                 // Add a `Download Image` entry.
2725                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2726                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2727                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2728                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2729
2730                         // Store the image URL for use by `onRequestPermissionResult()`.
2731                         downloadImageUrl = imageUrl;
2732
2733                         // Show a dialog if the user has previously denied the permission.
2734                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2735                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2736                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2737
2738                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2739                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2740                         } else {  // Show the permission request directly.
2741                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2742                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2743                         }
2744                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2745                         // Get a handle for the download image alert dialog.
2746                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2747
2748                         // Show the download image alert dialog.
2749                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2750                     }
2751                     return false;
2752                 });
2753
2754                 // Add a `Copy URL` entry.
2755                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2756                     // Save the image URL in a `ClipData`.
2757                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2758
2759                     // Set the `ClipData` as the clipboard's primary clip.
2760                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
2761                     return false;
2762                 });
2763
2764                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2765                 menu.add(R.string.cancel);
2766                 break;
2767
2768
2769             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2770             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2771                 // Get the image URL.
2772                 imageUrl = hitTestResult.getExtra();
2773
2774                 // Set the image URL as the title of the `ContextMenu`.
2775                 menu.setHeaderTitle(imageUrl);
2776
2777                 // Add a `View Image` entry.
2778                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2779                     loadUrl(imageUrl);
2780                     return false;
2781                 });
2782
2783                 // Add a `Download Image` entry.
2784                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2785                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2786                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2787                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2788
2789                         // Store the image URL for use by `onRequestPermissionResult()`.
2790                         downloadImageUrl = imageUrl;
2791
2792                         // Show a dialog if the user has previously denied the permission.
2793                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2794                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2795                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2796
2797                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2798                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2799                         } else {  // Show the permission request directly.
2800                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2801                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2802                         }
2803                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2804                         // Get a handle for the download image alert dialog.
2805                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2806
2807                         // Show the download image alert dialog.
2808                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2809                     }
2810                     return false;
2811                 });
2812
2813                 // Add a `Copy URL` entry.
2814                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2815                     // Save the image URL in a `ClipData`.
2816                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2817
2818                     // Set the `ClipData` as the clipboard's primary clip.
2819                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2820                     return false;
2821                 });
2822
2823                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2824                 menu.add(R.string.cancel);
2825                 break;
2826         }
2827     }
2828
2829     @Override
2830     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2831         // Get the `EditTexts` from the `dialogFragment`.
2832         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2833         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2834
2835         // Extract the strings from the `EditTexts`.
2836         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2837         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2838
2839         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2840         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2841         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2842         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2843
2844         // Display the new bookmark below the current items in the (0 indexed) list.
2845         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2846
2847         // Create the bookmark.
2848         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2849
2850         // Update `bookmarksCursor` with the current contents of this folder.
2851         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2852
2853         // Update the `ListView`.
2854         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2855
2856         // Scroll to the new bookmark.
2857         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2858     }
2859
2860     @Override
2861     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2862         // Get handles for the views in `dialogFragment`.
2863         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2864         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2865         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2866
2867         // Get new folder name string.
2868         String folderNameString = createFolderNameEditText.getText().toString();
2869
2870         // Get the new folder icon `Bitmap`.
2871         Bitmap folderIconBitmap;
2872         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2873             // Get the default folder icon and convert it to a `Bitmap`.
2874             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2875             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2876             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2877         } else {  // Use the `WebView` favorite icon.
2878             folderIconBitmap = favoriteIconBitmap;
2879         }
2880
2881         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2882         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2883         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2884         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2885
2886         // Move all the bookmarks down one in the display order.
2887         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2888             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2889             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2890         }
2891
2892         // Create the folder, which will be placed at the top of the `ListView`.
2893         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2894
2895         // Update `bookmarksCursor` with the current contents of this folder.
2896         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2897
2898         // Update the `ListView`.
2899         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2900
2901         // Scroll to the new folder.
2902         bookmarksListView.setSelection(0);
2903     }
2904
2905     @Override
2906     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2907         // Get the shortcut name.
2908         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2909         String shortcutNameString = shortcutNameEditText.getText().toString();
2910
2911         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
2912         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2913
2914         // Setup the shortcut intent.
2915         Intent shortcutIntent = new Intent();
2916         shortcutIntent.setAction(Intent.ACTION_VIEW);
2917         shortcutIntent.setData(Uri.parse(formattedUrlString));
2918
2919         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
2920         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2921
2922         // Add the required fields to the shortcut info builder.
2923         shortcutInfoBuilder.setIcon(favoriteIcon);
2924         shortcutInfoBuilder.setIntent(shortcutIntent);
2925         shortcutInfoBuilder.setShortLabel(shortcutNameString);
2926
2927         // Request the pin.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2928         ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2929     }
2930
2931     @Override
2932     public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2933         switch (downloadType) {
2934             case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2935                 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2936                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2937                 break;
2938
2939             case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2940                 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2941                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2942                 break;
2943         }
2944     }
2945
2946     @Override
2947     public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2948         switch (requestCode) {
2949             case DOWNLOAD_FILE_REQUEST_CODE:
2950                 // Show the download file alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
2951                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2952
2953                 // On API 23, displaying the fragment must be delayed or the app will crash.
2954                 if (Build.VERSION.SDK_INT == 23) {
2955                     new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2956                 } else {
2957                     downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2958                 }
2959
2960                 // Reset the download variables.
2961                 downloadUrl = "";
2962                 downloadContentDisposition = "";
2963                 downloadContentLength = 0;
2964                 break;
2965
2966             case DOWNLOAD_IMAGE_REQUEST_CODE:
2967                 // Show the download image alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
2968                 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2969
2970                 // On API 23, displaying the fragment must be delayed or the app will crash.
2971                 if (Build.VERSION.SDK_INT == 23) {
2972                     new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2973                 } else {
2974                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2975                 }
2976
2977                 // Reset the image URL variable.
2978                 downloadImageUrl = "";
2979                 break;
2980         }
2981     }
2982
2983     @Override
2984     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2985         // Download the image if it has an HTTP or HTTPS URI.
2986         if (imageUrl.startsWith("http")) {
2987             // Get a handle for the system `DOWNLOAD_SERVICE`.
2988             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2989
2990             // Parse `imageUrl`.
2991             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2992
2993             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
2994             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2995             if (firstPartyCookiesEnabled) {
2996                 // Get the cookies for `imageUrl`.
2997                 String cookies = cookieManager.getCookie(imageUrl);
2998
2999                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3000                 downloadRequest.addRequestHeader("Cookie", cookies);
3001             }
3002
3003             // Get the file name from the dialog fragment.
3004             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3005             String imageName = downloadImageNameEditText.getText().toString();
3006
3007             // Specify the download location.
3008             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3009                 // Download to the public download directory.
3010                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3011             } else {  // External write permission denied.
3012                 // Download to the app's external download directory.
3013                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3014             }
3015
3016             // Allow `MediaScanner` to index the download if it is a media file.
3017             downloadRequest.allowScanningByMediaScanner();
3018
3019             // Add the URL as the description for the download.
3020             downloadRequest.setDescription(imageUrl);
3021
3022             // Show the download notification after the download is completed.
3023             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3024
3025             // Remove the lint warning below that `downloadManager` might be `null`.
3026             assert downloadManager != null;
3027
3028             // Initiate the download.
3029             downloadManager.enqueue(downloadRequest);
3030         } else {  // The image is not an HTTP or HTTPS URI.
3031             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3032         }
3033     }
3034
3035     @Override
3036     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3037         // Download the file if it has an HTTP or HTTPS URI.
3038         if (downloadUrl.startsWith("http")) {
3039             // Get a handle for the system `DOWNLOAD_SERVICE`.
3040             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3041
3042             // Parse `downloadUrl`.
3043             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3044
3045             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
3046             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3047             if (firstPartyCookiesEnabled) {
3048                 // Get the cookies for `downloadUrl`.
3049                 String cookies = cookieManager.getCookie(downloadUrl);
3050
3051                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3052                 downloadRequest.addRequestHeader("Cookie", cookies);
3053             }
3054
3055             // Get the file name from the dialog fragment.
3056             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3057             String fileName = downloadFileNameEditText.getText().toString();
3058
3059             // Specify the download location.
3060             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3061                 // Download to the public download directory.
3062                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3063             } else {  // External write permission denied.
3064                 // Download to the app's external download directory.
3065                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3066             }
3067
3068             // Allow `MediaScanner` to index the download if it is a media file.
3069             downloadRequest.allowScanningByMediaScanner();
3070
3071             // Add the URL as the description for the download.
3072             downloadRequest.setDescription(downloadUrl);
3073
3074             // Show the download notification after the download is completed.
3075             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3076
3077             // Remove the lint warning below that `downloadManager` might be `null`.
3078             assert downloadManager != null;
3079
3080             // Initiate the download.
3081             downloadManager.enqueue(downloadRequest);
3082         } else {  // The download is not an HTTP or HTTPS URI.
3083             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3084         }
3085     }
3086
3087     @Override
3088     public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3089         // Get handles for the views from `dialogFragment`.
3090         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3091         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3092         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3093
3094         // Store the bookmark strings.
3095         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3096         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3097
3098         // Update the bookmark.
3099         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
3100             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3101         } else {  // Update the bookmark using the `WebView` favorite icon.
3102             // Convert the favorite icon to a byte array.  `0` is for lossless compression (the only option for a PNG).
3103             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3104             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3105             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3106
3107             //  Update the bookmark and the favorite icon.
3108             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3109         }
3110
3111         // Update `bookmarksCursor` with the current contents of this folder.
3112         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3113
3114         // Update the `ListView`.
3115         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3116     }
3117
3118     @Override
3119     public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3120         // Get handles for the views from `dialogFragment`.
3121         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3122         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3123         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3124         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3125
3126         // Get the new folder name.
3127         String newFolderNameString = editFolderNameEditText.getText().toString();
3128
3129         // Check if the favorite icon has changed.
3130         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
3131             // Update the name in the database.
3132             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3133         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
3134             // Get the new folder icon `Bitmap`.
3135             Bitmap folderIconBitmap;
3136             if (defaultFolderIconRadioButton.isChecked()) {
3137                 // Get the default folder icon and convert it to a `Bitmap`.
3138                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3139                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3140                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3141             } else {  // Use the `WebView` favorite icon.
3142                 folderIconBitmap = favoriteIconBitmap;
3143             }
3144
3145             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3146             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3147             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3148             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3149
3150             // Update the folder icon in the database.
3151             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3152         } else {  // The folder icon and the name have changed.
3153             // Get the new folder icon `Bitmap`.
3154             Bitmap folderIconBitmap;
3155             if (defaultFolderIconRadioButton.isChecked()) {
3156                 // Get the default folder icon and convert it to a `Bitmap`.
3157                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3158                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3159                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3160             } else {  // Use the `WebView` favorite icon.
3161                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3162             }
3163
3164             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3165             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3166             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3167             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3168
3169             // Update the folder name and icon in the database.
3170             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3171         }
3172
3173         // Update `bookmarksCursor` with the current contents of this folder.
3174         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3175
3176         // Update the `ListView`.
3177         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3178     }
3179
3180     @Override
3181     public void onHttpAuthenticationCancel() {
3182         // Cancel the `HttpAuthHandler`.
3183         httpAuthHandler.cancel();
3184     }
3185
3186     @Override
3187     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3188         // Get handles for the `EditTexts`.
3189         EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3190         EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3191
3192         // Proceed with the HTTP authentication.
3193         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3194     }
3195
3196     public void viewSslCertificate(View view) {
3197         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3198         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3199         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3200     }
3201
3202     @Override
3203     public void onSslErrorCancel() {
3204         sslErrorHandler.cancel();
3205     }
3206
3207     @Override
3208     public void onSslErrorProceed() {
3209         sslErrorHandler.proceed();
3210     }
3211
3212     @Override
3213     public void onSslMismatchBack() {
3214         if (mainWebView.canGoBack()) {  // There is a back page in the history.
3215             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3216             formattedUrlString = "";
3217
3218             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3219             navigatingHistory = true;
3220
3221             // Go back.
3222             mainWebView.goBack();
3223         } else {  // There are no pages to go back to.
3224             // Load a blank page
3225             loadUrl("");
3226         }
3227     }
3228
3229     @Override
3230     public void onSslMismatchProceed() {
3231         // Do not check the pinned SSL certificate for this domain again until the domain changes.
3232         ignorePinnedSslCertificate = true;
3233     }
3234
3235     @Override
3236     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3237         // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3238         formattedUrlString = "";
3239
3240         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3241         navigatingHistory = true;
3242
3243         // Load the history entry.
3244         mainWebView.goBackOrForward(moveBackOrForwardSteps);
3245     }
3246
3247     @Override
3248     public void onClearHistory() {
3249         // Clear the history.
3250         mainWebView.clearHistory();
3251     }
3252
3253     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3254     @Override
3255     public void onBackPressed() {
3256         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
3257             // Close the navigation drawer.
3258             drawerLayout.closeDrawer(GravityCompat.START);
3259         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
3260             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
3261                 // close the bookmarks drawer.
3262                 drawerLayout.closeDrawer(GravityCompat.END);
3263             } else {  // A subfolder is displayed.
3264                 // Place the former parent folder in `currentFolder`.
3265                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3266
3267                 // Load the new folder.
3268                 loadBookmarksFolder();
3269             }
3270
3271         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
3272             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3273             formattedUrlString = "";
3274
3275             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3276             navigatingHistory = true;
3277
3278             // Go back.
3279             mainWebView.goBack();
3280         } else {  // There isn't anything to do in Privacy Browser.
3281             // Pass `onBackPressed()` to the system.
3282             super.onBackPressed();
3283         }
3284     }
3285
3286     // Process the results of an upload file chooser.  Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
3287     @Override
3288     public void onActivityResult(int requestCode, int resultCode, Intent data) {
3289         // File uploads only work on API >= 21.
3290         if (Build.VERSION.SDK_INT >= 21) {
3291             // Pass the file to the WebView.
3292             fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3293         }
3294     }
3295
3296     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3297         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
3298         String unformattedUrlString = urlTextBox.getText().toString().trim();
3299
3300         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
3301         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3302             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
3303             if (!unformattedUrlString.startsWith("http")) {
3304                 unformattedUrlString = "http://" + unformattedUrlString;
3305             }
3306
3307             // Initialize `unformattedUrl`.
3308             URL unformattedUrl = null;
3309
3310             // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
3311             try {
3312                 unformattedUrl = new URL(unformattedUrlString);
3313             } catch (MalformedURLException e) {
3314                 e.printStackTrace();
3315             }
3316
3317             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3318             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3319             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3320             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3321             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3322             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3323
3324             // Build the URI.
3325             Uri.Builder formattedUri = new Uri.Builder();
3326             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3327
3328             // Decode `formattedUri` as a `String` in `UTF-8`.
3329             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3330         } else if (unformattedUrlString.isEmpty()){  // Load a blank web site.
3331             // Load a blank string.
3332             formattedUrlString = "";
3333         } else {  // Search for the contents of the URL box.
3334             // Sanitize the search input and convert it to a search.
3335             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3336
3337             // Add the base search URL.
3338             formattedUrlString = searchURL + encodedUrlString;
3339         }
3340
3341         // Clear the focus from the URL text box.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3342         urlTextBox.clearFocus();
3343
3344         // Make it so.
3345         loadUrl(formattedUrlString);
3346     }
3347
3348     private void loadUrl(String url) {// Apply any custom domain settings.
3349         // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3350         formattedUrlString = url;
3351
3352         // Apply the domain settings.
3353         applyDomainSettings(url, true, false);
3354
3355         // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3356         urlIsLoading = true;
3357
3358         // Load the URL.
3359         mainWebView.loadUrl(url, customHeaders);
3360     }
3361
3362     public void findPreviousOnPage(View view) {
3363         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
3364         mainWebView.findNext(false);
3365     }
3366
3367     public void findNextOnPage(View view) {
3368         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3369         mainWebView.findNext(true);
3370     }
3371
3372     public void closeFindOnPage(View view) {
3373         // Delete the contents of `find_on_page_edittext`.
3374         findOnPageEditText.setText(null);
3375
3376         // Clear the highlighted phrases.
3377         mainWebView.clearMatches();
3378
3379         // Hide the Find on Page `RelativeLayout`.
3380         findOnPageLinearLayout.setVisibility(View.GONE);
3381
3382         // Show the URL app bar.
3383         supportAppBar.setVisibility(View.VISIBLE);
3384
3385         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
3386         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3387     }
3388
3389     private void applyAppSettings() {
3390         // Get a handle for the shared preferences.
3391         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3392
3393         // Store the values from the shared preferences in variables.
3394         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3395         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3396         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3397         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3398         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3399         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3400         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3401         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3402         proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3403         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3404         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3405         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3406         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3407
3408         // Set the homepage, search, and proxy options.
3409         if (proxyThroughOrbot) {  // Set the Tor options.
3410             // Set `torHomepageString` as `homepage`.
3411             homepage = torHomepageString;
3412
3413             // If formattedUrlString is null assign the homepage to it.
3414             if (formattedUrlString == null) {
3415                 formattedUrlString = homepage;
3416             }
3417
3418             // Set the search URL.
3419             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
3420                 searchURL = torSearchCustomURLString;
3421             } else {  // Use the string from the pre-built list.
3422                 searchURL = torSearchString;
3423             }
3424
3425             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
3426             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3427
3428             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
3429             if (darkTheme) {
3430                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3431             } else {
3432                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3433             }
3434
3435             // Display a message to the user if waiting for Orbot.
3436             if (!orbotStatus.equals("ON")) {
3437                 // Set `waitingForOrbot`.
3438                 waitingForOrbot = true;
3439
3440                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
3441                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3442             }
3443         } else {  // Set the non-Tor options.
3444             // Set `homepageString` as `homepage`.
3445             homepage = homepageString;
3446
3447             // If formattedUrlString is null assign the homepage to it.
3448             if (formattedUrlString == null) {
3449                 formattedUrlString = homepage;
3450             }
3451
3452             // Set the search URL.
3453             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
3454                 searchURL = searchCustomURLString;
3455             } else {  // Use the string from the pre-built list.
3456                 searchURL = searchString;
3457             }
3458
3459             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
3460             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3461
3462             // Set the default `appBar` background.  `this` refers to the context.
3463             if (darkTheme) {
3464                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3465             } else {
3466                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3467             }
3468
3469             // Reset `waitingForOrbot.
3470             waitingForOrbot = false;
3471         }
3472
3473         // Set Do Not Track status.
3474         if (doNotTrackEnabled) {
3475             customHeaders.put("DNT", "1");
3476         } else {
3477             customHeaders.remove("DNT");
3478         }
3479
3480         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3481         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3482             if (hideSystemBarsOnFullscreen) {  // Hide everything.
3483                 // Remove the translucent navigation setting if it is currently flagged.
3484                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3485
3486                 // Remove the translucent status bar overlay.
3487                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3488
3489                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3490                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3491
3492                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3493                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3494                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3495                  */
3496                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3497             } else {  // Hide everything except the status and navigation bars.
3498                 // Add the translucent status flag if it is unset.
3499                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3500
3501                 if (translucentNavigationBarOnFullscreen) {
3502                     // Set the navigation bar to be translucent.
3503                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3504                 } else {
3505                     // Set the navigation bar to be black.
3506                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3507                 }
3508             }
3509         } else {  // Switch to normal viewing mode.
3510             // Reset `inFullScreenBrowsingMode` to `false`.
3511             inFullScreenBrowsingMode = false;
3512
3513             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3514             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3515                 appBar.show();
3516             }
3517
3518             // Show the `BannerAd` in the free flavor.
3519             if (BuildConfig.FLAVOR.contentEquals("free")) {
3520                 // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3521                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3522             }
3523
3524             // Remove the translucent navigation bar flag if it is set.
3525             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3526
3527             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3528             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3529
3530             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3531             rootCoordinatorLayout.setSystemUiVisibility(0);
3532
3533             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3534             rootCoordinatorLayout.setFitsSystemWindows(true);
3535         }
3536     }
3537
3538     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3539     // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3540     @SuppressWarnings("deprecation")
3541     private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3542         // Parse the URL into a URI.
3543         Uri uri = Uri.parse(url);
3544
3545         // Extract the domain from `uri`.
3546         String hostName = uri.getHost();
3547
3548         // Initialize `loadingNewDomainName`.
3549         boolean loadingNewDomainName;
3550
3551         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3552         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3553         //noinspection SimplifiableIfStatement
3554         if ((hostName == null) || (currentDomainName == null)) {
3555             loadingNewDomainName = true;
3556         } else {  // Determine if `hostName` equals `currentDomainName`.
3557             loadingNewDomainName = !hostName.equals(currentDomainName);
3558         }
3559
3560         // Strings don't like to be null.
3561         if (hostName == null) {
3562             hostName = "";
3563         }
3564
3565         // Only apply the domain settings if a new domain is being loaded.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3566         if (loadingNewDomainName) {
3567             // Set the new `hostname` as the `currentDomainName`.
3568             currentDomainName = hostName;
3569
3570             // Reset `ignorePinnedSslCertificate`.
3571             ignorePinnedSslCertificate = false;
3572
3573             // Reset the favorite icon if specified.
3574             if (resetFavoriteIcon) {
3575                 favoriteIconBitmap = favoriteIconDefaultBitmap;
3576                 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3577             }
3578
3579             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3580             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3581             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3582
3583             // Get a full cursor from `domainsDatabaseHelper`.
3584             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3585
3586             // Initialize `domainSettingsSet`.
3587             Set<String> domainSettingsSet = new HashSet<>();
3588
3589             // Get the domain name column index.
3590             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3591
3592             // Populate `domainSettingsSet`.
3593             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3594                 // Move `domainsCursor` to the current row.
3595                 domainNameCursor.moveToPosition(i);
3596
3597                 // Store the domain name in `domainSettingsSet`.
3598                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3599             }
3600
3601             // Close `domainNameCursor.
3602             domainNameCursor.close();
3603
3604             // Initialize variables to track if domain settings will be applied and, if so, under which name.
3605             domainSettingsApplied = false;
3606             String domainNameInDatabase = null;
3607
3608             // Check the hostname.
3609             if (domainSettingsSet.contains(hostName)) {
3610                 domainSettingsApplied = true;
3611                 domainNameInDatabase = hostName;
3612             }
3613
3614             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3615             while (!domainSettingsApplied && hostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3616                 if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
3617                     // Apply the domain settings.
3618                     domainSettingsApplied = true;
3619
3620                     // Store the applied domain names as it appears in the database.
3621                     domainNameInDatabase = "*." + hostName;
3622                 }
3623
3624                 // Strip out the lowest subdomain of of the host name.
3625                 hostName = hostName.substring(hostName.indexOf(".") + 1);
3626             }
3627
3628
3629             // Get a handle for the shared preference.
3630             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3631
3632             // Store the general preference information.
3633             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3634             String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3635             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3636             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3637             nightMode = sharedPreferences.getBoolean("night_mode", false);
3638
3639             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
3640                 // Get a cursor for the current host and move it to the first position.
3641                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3642                 currentHostDomainSettingsCursor.moveToFirst();
3643
3644                 // Get the settings from the cursor.
3645                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3646                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3647                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3648                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3649                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3650                 // Form data can be removed once the minimum API >= 26.
3651                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3652                 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3653                 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3654                 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3655                 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3656                 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3657                 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3658                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3659                 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3660                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3661                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3662                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3663                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3664                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3665                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3666                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3667                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3668                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3669
3670                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3671                 switch (nightModeInt) {
3672                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3673                         nightMode = true;
3674                         break;
3675
3676                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3677                         nightMode = false;
3678                         break;
3679                 }
3680
3681                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3682                 if (nightMode) {
3683                     javaScriptEnabled = true;
3684                 }
3685
3686                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3687                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3688                     pinnedDomainSslStartDate = null;
3689                 } else {
3690                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3691                 }
3692
3693                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3694                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3695                     pinnedDomainSslEndDate = null;
3696                 } else {
3697                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3698                 }
3699
3700                 // Close `currentHostDomainSettingsCursor`.
3701                 currentHostDomainSettingsCursor.close();
3702
3703                 // Apply the domain settings.
3704                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3705                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3706                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3707
3708                 // Apply the form data setting if the API < 26.
3709                 if (Build.VERSION.SDK_INT < 26) {
3710                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3711                 }
3712
3713                 // Apply the font size.
3714                 if (fontSize == 0) {  // Apply the default font size.
3715                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3716                 } else {  // Apply the specified font size.
3717                     mainWebView.getSettings().setTextZoom(fontSize);
3718                 }
3719
3720                 // Set third-party cookies status if API >= 21.
3721                 if (Build.VERSION.SDK_INT >= 21) {
3722                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3723                 }
3724
3725                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
3726                 // <https://redmine.stoutner.com/issues/160>
3727                 if (!urlIsLoading) {
3728                     // Set the user agent.
3729                     if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3730                         // Get the array position of the default user agent name.
3731                         int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3732
3733                         // Set the user agent according to the system default.
3734                         switch (defaultUserAgentArrayPosition) {
3735                             case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3736                                 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3737                                 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3738                                 break;
3739
3740                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3741                                 // Set the user agent to `""`, which uses the default value.
3742                                 mainWebView.getSettings().setUserAgentString("");
3743                                 break;
3744
3745                             case SETTINGS_CUSTOM_USER_AGENT:
3746                                 // Set the custom user agent.
3747                                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3748                                 break;
3749
3750                             default:
3751                                 // Get the user agent string from the user agent data array
3752                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3753                         }
3754                     } else {  // Set the user agent according to the stored name.
3755                         // Get the array position of the user agent name.
3756                         int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3757
3758                         switch (userAgentArrayPosition) {
3759                             case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3760                                 mainWebView.getSettings().setUserAgentString(userAgentName);
3761                                 break;
3762
3763                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3764                                 // Set the user agent to `""`, which uses the default value.
3765                                 mainWebView.getSettings().setUserAgentString("");
3766                                 break;
3767
3768                             default:
3769                                 // Get the user agent string from the user agent data array.
3770                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3771                         }
3772                     }
3773
3774                     // Set swipe to refresh.
3775                     switch (swipeToRefreshInt) {
3776                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3777                             // Set swipe to refresh according to the default.
3778                             swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3779                             break;
3780
3781                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3782                             // Enable swipe to refresh.
3783                             swipeRefreshLayout.setEnabled(true);
3784                             break;
3785
3786                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3787                             // Disable swipe to refresh.
3788                             swipeRefreshLayout.setEnabled(false);
3789                     }
3790
3791                     // Store the applied user agent string, which is used in the View Source activity.
3792                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3793                 }
3794
3795                 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3796                 if (darkTheme) {
3797                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3798                 } else {
3799                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3800                 }
3801             } else {  // The new URL does not have custom domain settings.  Load the defaults.
3802                 // Store the values from `sharedPreferences` in variables.
3803                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3804                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3805                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3806                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3807                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);  // Form data can be removed once the minimum API >= 26.
3808                 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3809                 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3810                 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3811                 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3812                 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3813
3814                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3815                 if (nightMode) {
3816                     javaScriptEnabled = true;
3817                 }
3818
3819                 // Apply the default settings.
3820                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3821                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3822                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3823                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3824                 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3825
3826                 // Apply the form data setting if the API < 26.
3827                 if (Build.VERSION.SDK_INT < 26) {
3828                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3829                 }
3830
3831                 // Reset the pinned SSL certificate information.
3832                 domainSettingsDatabaseId = -1;
3833                 pinnedDomainSslCertificate = false;
3834                 pinnedDomainSslIssuedToCNameString = "";
3835                 pinnedDomainSslIssuedToONameString = "";
3836                 pinnedDomainSslIssuedToUNameString = "";
3837                 pinnedDomainSslIssuedByCNameString = "";
3838                 pinnedDomainSslIssuedByONameString = "";
3839                 pinnedDomainSslIssuedByUNameString = "";
3840                 pinnedDomainSslStartDate = null;
3841                 pinnedDomainSslEndDate = null;
3842
3843                 // Set third-party cookies status if API >= 21.
3844                 if (Build.VERSION.SDK_INT >= 21) {
3845                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3846                 }
3847
3848                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
3849                 // <https://redmine.stoutner.com/issues/160>
3850                 if (!urlIsLoading) {
3851                     // Get the array position of the user agent name.
3852                     int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3853
3854                     // Set the user agent.
3855                     switch (userAgentArrayPosition) {
3856                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3857                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3858                             mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3859                             break;
3860
3861                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3862                             // Set the user agent to `""`, which uses the default value.
3863                             mainWebView.getSettings().setUserAgentString("");
3864                             break;
3865
3866                         case SETTINGS_CUSTOM_USER_AGENT:
3867                             // Set the custom user agent.
3868                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3869                             break;
3870
3871                         default:
3872                             // Get the user agent string from the user agent data array
3873                             mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3874                     }
3875
3876                     // Store the applied user agent string, which is used in the View Source activity.
3877                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3878                 }
3879
3880                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3881                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3882             }
3883
3884             // Close `domainsDatabaseHelper`.
3885             domainsDatabaseHelper.close();
3886
3887             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
3888             onTheFlyDisplayImagesSet = false;
3889             setDisplayWebpageImages();
3890
3891             // Update the privacy icons, but only if `mainMenu` has already been populated.
3892             if (mainMenu != null) {
3893                 updatePrivacyIcons(true);
3894             }
3895         }
3896
3897         // Reload the website if returning from the Domains activity.
3898         if (reloadWebsite) {
3899             mainWebView.reload();
3900         }
3901     }
3902
3903     private void setDisplayWebpageImages() {
3904         if (!onTheFlyDisplayImagesSet) {
3905             if (domainSettingsApplied) {  // Custom domain settings are applied.
3906                 switch (displayWebpageImagesInt) {
3907                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3908                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3909                         break;
3910
3911                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3912                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
3913                         break;
3914
3915                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3916                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
3917                         break;
3918                 }
3919             } else {  // Default settings are applied.
3920                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3921             }
3922         }
3923     }
3924
3925     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3926         // Get handles for the menu items.
3927         MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3928         MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3929         MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3930         MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
3931
3932         // Update the privacy icon.
3933         if (javaScriptEnabled) {  // JavaScript is enabled.
3934             privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3935         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
3936             privacyMenuItem.setIcon(R.drawable.warning);
3937         } else {  // All the dangerous features are disabled.
3938             privacyMenuItem.setIcon(R.drawable.privacy_mode);
3939         }
3940
3941         // Update the first-party cookies icon.
3942         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
3943             firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3944         } else {  // First-party cookies are disabled.
3945             if (darkTheme) {
3946                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3947             } else {
3948                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3949             }
3950         }
3951
3952         // Update the DOM storage icon.
3953         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
3954             domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3955         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
3956             if (darkTheme) {
3957                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3958             } else {
3959                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3960             }
3961         } else {  // JavaScript is disabled, so DOM storage is ghosted.
3962             if (darkTheme) {
3963                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3964             } else {
3965                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3966             }
3967         }
3968
3969         // Update the refresh icon.
3970         if (darkTheme) {
3971             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3972         } else {
3973             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3974         }
3975
3976         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3977         if (runInvalidateOptionsMenu) {
3978             invalidateOptionsMenu();
3979         }
3980     }
3981
3982     private void highlightUrlText() {
3983         String urlString = urlTextBox.getText().toString();
3984
3985         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
3986             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3987         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
3988             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3989         }
3990
3991         // Get the index of the `/` immediately after the domain name.
3992         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3993
3994         // De-emphasize the text after the domain name.
3995         if (endOfDomainName > 0) {
3996             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3997         }
3998     }
3999
4000     private void loadBookmarksFolder() {
4001         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4002         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4003
4004         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
4005         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4006             @Override
4007             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4008                 // Inflate the individual item layout.  `false` does not attach it to the root.
4009                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4010             }
4011
4012             @Override
4013             public void bindView(View view, Context context, Cursor cursor) {
4014                 // Get handles for the views.
4015                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4016                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4017
4018                 // Get the favorite icon byte array from the cursor.
4019                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4020
4021                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4022                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4023
4024                 // Display the bitmap in `bookmarkFavoriteIcon`.
4025                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4026
4027                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4028                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4029                 bookmarkNameTextView.setText(bookmarkNameString);
4030
4031                 // Make the font bold for folders.
4032                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4033                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4034                 } else {  // Reset the font to default for normal bookmarks.
4035                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4036                 }
4037             }
4038         };
4039
4040         // Populate the `ListView` with the adapter.
4041         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4042
4043         // Set the bookmarks drawer title.
4044         if (currentBookmarksFolder.isEmpty()) {
4045             bookmarksTitleTextView.setText(R.string.bookmarks);
4046         } else {
4047             bookmarksTitleTextView.setText(currentBookmarksFolder);
4048         }
4049     }
4050 }