]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
61b94c4ba7a4771b07ee932332a4bc713e958257
[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     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
367     private boolean displayingFullScreenVideo;
368
369     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
370     private String currentDomainName;
371
372     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
373     private boolean ignorePinnedSslCertificate;
374
375     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
376     private boolean waitingForOrbot;
377
378     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
379     private boolean domainSettingsApplied;
380
381     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
382     private int displayWebpageImagesInt;
383
384     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
385     private boolean onTheFlyDisplayImagesSet;
386
387     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
388     private String waitingForOrbotHTMLString;
389
390     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
391     private String privateDataDirectoryString;
392
393     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
394     private LinearLayout findOnPageLinearLayout;
395
396     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
397     private EditText findOnPageEditText;
398
399     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
400     private Menu mainMenu;
401
402     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
403     private ActionBarDrawerToggle drawerToggle;
404
405     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
406     private Toolbar supportAppBar;
407
408     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
409     private EditText urlTextBox;
410
411     // The color spans are used in `onCreate()` and `highlightUrlText()`.
412     private ForegroundColorSpan redColorSpan;
413     private ForegroundColorSpan initialGrayColorSpan;
414     private ForegroundColorSpan finalGrayColorSpan;
415
416     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
417     private SslErrorHandler sslErrorHandler;
418
419     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
420     private static HttpAuthHandler httpAuthHandler;
421
422     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
423     private InputMethodManager inputMethodManager;
424
425     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
426     private RelativeLayout mainWebViewRelativeLayout;
427
428     // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
429     private boolean urlIsLoading;
430
431     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
432     private boolean pinnedDomainSslCertificate;
433
434     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
435     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
436
437     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
438     private ListView bookmarksListView;
439
440     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
441     private TextView bookmarksTitleTextView;
442
443     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
444     private Cursor bookmarksCursor;
445
446     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
447     private CursorAdapter bookmarksCursorAdapter;
448
449     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
450     private String oldFolderNameString;
451
452     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
453     private ValueCallback<Uri[]> fileChooserCallback;
454
455     // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
456     private String downloadUrl;
457     private String downloadContentDisposition;
458     private long downloadContentLength;
459
460     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
461     private String downloadImageUrl;
462
463     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
464     private ArrayAdapter<CharSequence> userAgentNamesArray;
465     private String[] userAgentDataArray;
466
467     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
468     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
469     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
470
471     @Override
472     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.  The whole premise of Privacy Browser is built around an understanding of these dangers.
473     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
474     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
475     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
476     @SuppressWarnings("deprecation")
477     protected void onCreate(Bundle savedInstanceState) {
478         // Get a handle for the shared preferences.
479         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
480
481         // Get the theme and screenshot preferences.
482         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
483         allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
484
485         // Disable screenshots if not allowed.
486         if (!allowScreenshots) {
487             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
488         }
489
490         // Set the activity theme.
491         if (darkTheme) {
492             setTheme(R.style.PrivacyBrowserDark);
493         } else {
494             setTheme(R.style.PrivacyBrowserLight);
495         }
496
497         // Run the default commands.
498         super.onCreate(savedInstanceState);
499
500         // Set the content view.
501         setContentView(R.layout.main_drawerlayout);
502
503         // Get a handle for `inputMethodManager`.
504         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
505
506         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
507         supportAppBar = findViewById(R.id.app_bar);
508         setSupportActionBar(supportAppBar);
509         appBar = getSupportActionBar();
510
511         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
512         assert appBar != null;
513
514         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
515         appBar.setCustomView(R.layout.url_app_bar);
516         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
517
518         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
519         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
520         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
521         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
522
523         // Get a handle for `urlTextBox`.
524         urlTextBox = findViewById(R.id.url_edittext);
525
526         // Remove the formatting from `urlTextBar` when the user is editing the text.
527         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
528             if (hasFocus) {  // The user is editing `urlTextBox`.
529                 // Remove the highlighting.
530                 urlTextBox.getText().removeSpan(redColorSpan);
531                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
532                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
533             } else {  // The user has stopped editing `urlTextBox`.
534                 // Reapply the highlighting.
535                 highlightUrlText();
536             }
537         });
538
539         // Set the go button on the keyboard to load the URL in `urlTextBox`.
540         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
541             // If the event is a key-down event on the `enter` button, load the URL.
542             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
543                 // Load the URL into the mainWebView and consume the event.
544                 try {
545                     loadUrlFromTextBox();
546                 } catch (UnsupportedEncodingException e) {
547                     e.printStackTrace();
548                 }
549                 // If the enter key was pressed, consume the event.
550                 return true;
551             } else {
552                 // If any other key was pressed, do not consume the event.
553                 return false;
554             }
555         });
556
557         // Set `waitingForOrbotHTMLString`.
558         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
559
560         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
561         currentDomainName = "";
562         orbotStatus = "unknown";
563         waitingForOrbot = false;
564
565         // Create an Orbot status `BroadcastReceiver`.
566         BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
567             @Override
568             public void onReceive(Context context, Intent intent) {
569                 // Store the content of the status message in `orbotStatus`.
570                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
571
572                 // If we are waiting on Orbot, load the website now that Orbot is connected.
573                 if (orbotStatus.equals("ON") && waitingForOrbot) {
574                     // Reset `waitingForOrbot`.
575                     waitingForOrbot = false;
576
577                     // Load `formattedUrlString
578                     loadUrl(formattedUrlString);
579                 }
580             }
581         };
582
583         // Register `orbotStatusBroadcastReceiver` on `this` context.
584         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
585
586         // Get handles for views that need to be accessed.
587         drawerLayout = findViewById(R.id.drawerlayout);
588         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
589         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
590         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
591         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
592         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
593         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
594         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
595         mainWebView = findViewById(R.id.main_webview);
596         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
597         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
598         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
599         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
600         favoriteIconImageView = findViewById(R.id.favorite_icon);
601
602         // Set the bookmarks drawer resources according to the theme.  This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
603         if (darkTheme) {
604             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
605             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
606             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
607             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
608         } else {
609             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
610             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
611             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
612             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
613         }
614
615         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
616         launchBookmarksActivityFab.setOnClickListener(v -> {
617             // Create an intent to launch the bookmarks activity.
618             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
619
620             // Include the current folder with the `Intent`.
621             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
622
623             // Make it so.
624             startActivity(bookmarksIntent);
625         });
626
627         // Set the create new bookmark folder FAB to display an alert dialog.
628         createBookmarkFolderFab.setOnClickListener(v -> {
629             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
630             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
631             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
632         });
633
634         // Set the create new bookmark FAB to display an alert dialog.
635         createBookmarkFab.setOnClickListener(view -> {
636             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
637             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
638             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
639         });
640
641         // Create a double-tap listener to toggle full-screen mode.
642         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
643             // Override `onDoubleTap()`.  All other events are handled using the default settings.
644             @Override
645             public boolean onDoubleTap(MotionEvent event) {
646                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
647                     // Toggle `inFullScreenBrowsingMode`.
648                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
649
650                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
651                         // Hide the `appBar`.
652                         appBar.hide();
653
654                         // Hide the banner ad in the free flavor.
655                         if (BuildConfig.FLAVOR.contentEquals("free")) {
656                             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
657                             AdHelper.hideAd(findViewById(R.id.adview));
658                         }
659
660                         // Modify the system bars.
661                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
662                             // Remove the translucent overlays.
663                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
664
665                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
666                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
667
668                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
669                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
670                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
671                              */
672                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
673
674                             // Set `rootCoordinatorLayout` to fill the whole screen.
675                             rootCoordinatorLayout.setFitsSystemWindows(false);
676                         } else {  // Hide everything except the status and navigation bars.
677                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
678                             rootCoordinatorLayout.setFitsSystemWindows(false);
679
680                             // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
681                             if (translucentNavigationBarOnFullscreen) {
682                                 // Set the navigation bar to be translucent.
683                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
684                             }
685                         }
686                     } else {  // Switch to normal viewing mode.
687                         // Show the `appBar`.
688                         appBar.show();
689
690                         // Show the `BannerAd` in the free flavor.
691                         if (BuildConfig.FLAVOR.contentEquals("free")) {
692                             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
693                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
694                         }
695
696                         // Remove the translucent navigation bar flag if it is set.
697                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
698
699                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
700                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
701
702                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
703                         rootCoordinatorLayout.setSystemUiVisibility(0);
704
705                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
706                         rootCoordinatorLayout.setFitsSystemWindows(true);
707                     }
708
709                     // Consume the double-tap.
710                     return true;
711                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
712                     return false;
713                 }
714             }
715         });
716
717         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
718         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
719             // Call `performClick()` on the view, which is required for accessibility.
720             v.performClick();
721
722             // Send the `event` to `gestureDetector`.
723             return gestureDetector.onTouchEvent(event);
724         });
725
726         // Update `findOnPageCountTextView`.
727         mainWebView.setFindListener(new WebView.FindListener() {
728             // Get a handle for `findOnPageCountTextView`.
729             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
730
731             @Override
732             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
733                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
734                     // Set `findOnPageCountTextView` to `0/0`.
735                     findOnPageCountTextView.setText(R.string.zero_of_zero);
736                 } else if (isDoneCounting) {  // There are matches.
737                     // `activeMatchOrdinal` is zero-based.
738                     int activeMatch = activeMatchOrdinal + 1;
739
740                     // Build the match string.
741                     String matchString = activeMatch + "/" + numberOfMatches;
742
743                     // Set `findOnPageCountTextView`.
744                     findOnPageCountTextView.setText(matchString);
745                 }
746             }
747         });
748
749         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
750         findOnPageEditText.addTextChangedListener(new TextWatcher() {
751             @Override
752             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
753                 // Do nothing.
754             }
755
756             @Override
757             public void onTextChanged(CharSequence s, int start, int before, int count) {
758                 // Do nothing.
759             }
760
761             @Override
762             public void afterTextChanged(Editable s) {
763                 // Search for the text in `mainWebView`.
764                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
765             }
766         });
767
768         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
769         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
770             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
771                 // Hide the soft keyboard.  `0` indicates no additional flags.
772                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
773
774                 // Consume the event.
775                 return true;
776             } else {  // A different key was pressed.
777                 // Do not consume the event.
778                 return false;
779             }
780         });
781
782         // Implement swipe to refresh
783         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
784         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
785         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
786
787         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
788         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
789         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
790
791         // Listen for touches on the navigation menu.
792         final NavigationView navigationView = findViewById(R.id.navigationview);
793         navigationView.setNavigationItemSelectedListener(this);
794
795         // Get handles for `navigationMenu` and the back and forward menu items.  The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
796         final Menu navigationMenu = navigationView.getMenu();
797         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
798         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
799         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
800         final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
801
802         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
803         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
804         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
805
806         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
807         currentBookmarksFolder = "";
808
809         // Load the home folder, which is `""` in the database.
810         loadBookmarksFolder();
811
812         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
813             // Convert the id from long to int to match the format of the bookmarks database.
814             int databaseID = (int) id;
815
816             // Get the bookmark cursor for this ID and move it to the first row.
817             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
818             bookmarkCursor.moveToFirst();
819
820             // Act upon the bookmark according to the type.
821             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
822                 // Store the new folder name in `currentBookmarksFolder`.
823                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
824
825                 // Load the new folder.
826                 loadBookmarksFolder();
827             } else {  // The selected bookmark is not a folder.
828                 // Load the bookmark URL.
829                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
830
831                 // Close the bookmarks drawer.
832                 drawerLayout.closeDrawer(GravityCompat.END);
833             }
834
835             // Close the `Cursor`.
836             bookmarkCursor.close();
837         });
838
839         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
840             // Convert the database ID from `long` to `int`.
841             int databaseId = (int) id;
842
843             // Find out if the selected bookmark is a folder.
844             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
845
846             if (isFolder) {
847                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
848                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
849
850                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
851                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
852                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
853             } else {
854                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
855                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
856                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
857             }
858
859             // Consume the event.
860             return true;
861         });
862
863         // The `DrawerListener` is used to update the Navigation Menu.
864         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
865             @Override
866             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
867             }
868
869             @Override
870             public void onDrawerOpened(@NonNull View drawerView) {
871             }
872
873             @Override
874             public void onDrawerClosed(@NonNull View drawerView) {
875             }
876
877             @Override
878             public void onDrawerStateChanged(int newState) {
879                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // The drawer is opening or closing.
880                     // Initialize a the blocked requests counter.
881                     int blockedRequests = 0;
882
883                     // Count the number of blocked requests.
884                     for (int i = 0; i < resourceRequests.size(); i++) {
885                         // Add the blocked requests.
886                         if (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_BLOCKED) {
887                             blockedRequests++;
888                         }
889
890                         // Add the third-party requests if they are blocked.
891                         if (blockAllThirdPartyRequests && (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_THIRD_PARTY)) {
892                             blockedRequests++;
893                         }
894                     }
895
896                     // Update the back, forward, history, and requests menu items.
897                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
898                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
899                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
900                     navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + blockedRequests);
901
902                     // Hide the keyboard (if displayed) so we can see the navigation menu.  `0` indicates no additional flags.
903                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
904
905                     // Clear the focus from `urlTextBox` if it has it.
906                     urlTextBox.clearFocus();
907                 }
908             }
909         });
910
911         // drawerToggle creates the hamburger icon at the start of the AppBar.
912         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
913
914         // Get a handle for the progress bar.
915         final ProgressBar progressBar = findViewById(R.id.progress_bar);
916
917         mainWebView.setWebChromeClient(new WebChromeClient() {
918             // Update the progress bar when a page is loading.
919             @Override
920             public void onProgressChanged(WebView view, int progress) {
921                 // Inject the night mode CSS if night mode is enabled.
922                 if (nightMode) {
923                     // `background-color: #212121` sets the background to be dark gray.  `color: #BDBDBD` sets the text color to be light gray.  `box-shadow: none` removes a lower underline on links
924                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
925                     // `border: none` removes all borders, which can also be used to underline text.
926                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
927                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
928                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
929                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
930                                 // Initialize a `Handler` to display `mainWebView`.
931                                 Handler displayWebViewHandler = new Handler();
932
933                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
934                                 Runnable displayWebViewRunnable = () -> {
935                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
936                                     if (progressBar.getVisibility() == View.GONE) {
937                                         mainWebView.setVisibility(View.VISIBLE);
938                                     }
939                                 };
940
941                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
942                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
943                             });
944                 }
945
946                 // Update the progress bar.
947                 progressBar.setProgress(progress);
948
949                 // Set the visibility of the progress bar.
950                 if (progress < 100) {
951                     // Show the progress bar.
952                     progressBar.setVisibility(View.VISIBLE);
953                 } else {
954                     // Hide the progress bar.
955                     progressBar.setVisibility(View.GONE);
956
957                     // Display `mainWebView` if night mode is disabled.
958                     // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not
959                     // currently enabled.
960                     if (!nightMode) {
961                         mainWebView.setVisibility(View.VISIBLE);
962                     }
963
964                     //Stop the swipe to refresh indicator if it is running
965                     swipeRefreshLayout.setRefreshing(false);
966                 }
967             }
968
969             // Set the favorite icon when it changes.
970             @Override
971             public void onReceivedIcon(WebView view, Bitmap icon) {
972                 // Only update the favorite icon if the website has finished loading.
973                 if (progressBar.getVisibility() == View.GONE) {
974                     // Save a copy of the favorite icon.
975                     favoriteIconBitmap = icon;
976
977                     // Place the favorite icon in the appBar.
978                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
979                 }
980             }
981
982             // Save a copy of the title when it changes.
983             @Override
984             public void onReceivedTitle(WebView view, String title) {
985                 // Save a copy of the title.
986                 webViewTitle = title;
987             }
988
989             // Enter full screen video.
990             @Override
991             public void onShowCustomView(View view, CustomViewCallback callback) {
992                 // Set the full screen video flag.
993                 displayingFullScreenVideo = true;
994
995                 // Pause the ad if this is the free flavor.
996                 if (BuildConfig.FLAVOR.contentEquals("free")) {
997                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
998                     AdHelper.pauseAd(findViewById(R.id.adview));
999                 }
1000
1001                 // Remove the translucent overlays.
1002                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1003
1004                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1005                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1006
1007                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1008                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1009                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1010                  */
1011                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1012
1013                 // Set `rootCoordinatorLayout` to fill the entire screen.
1014                 rootCoordinatorLayout.setFitsSystemWindows(false);
1015
1016                 // Disable the sliding drawers.
1017                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1018
1019                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1020                 fullScreenVideoFrameLayout.addView(view);
1021                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1022             }
1023
1024             // Exit full screen video.
1025             @Override
1026             public void onHideCustomView() {
1027                 // Unset the full screen video flag.
1028                 displayingFullScreenVideo = true;
1029
1030                 // Hide `fullScreenVideoFrameLayout`.
1031                 fullScreenVideoFrameLayout.removeAllViews();
1032                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1033
1034                 // Enable the sliding drawers.
1035                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1036
1037                 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1038                 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
1039                     if (hideSystemBarsOnFullscreen) {  // Hide everything.
1040                         // Remove the translucent navigation setting if it is currently flagged.
1041                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1042
1043                         // Remove the translucent status bar overlay.
1044                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1045
1046                         // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1047                         drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1048
1049                         /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1050                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1051                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1052                          */
1053                         rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1054                     } else {  // Hide everything except the status and navigation bars.
1055                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1056                         rootCoordinatorLayout.setSystemUiVisibility(0);
1057
1058                         // Add the translucent status flag if it is unset.
1059                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1060
1061                         if (translucentNavigationBarOnFullscreen) {
1062                             // Set the navigation bar to be translucent.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1063                             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1064                         } else {
1065                             // Set the navigation bar to be black.
1066                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1067                         }
1068                     }
1069                 } else {  // Switch to normal viewing mode.
1070                     // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1071                     if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1072                         appBar.show();
1073                     }
1074
1075                     // Show the `BannerAd` in the free flavor.
1076                     if (BuildConfig.FLAVOR.contentEquals("free")) {
1077                         // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1078                         AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1079                     }
1080
1081                     // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1082                     rootCoordinatorLayout.setSystemUiVisibility(0);
1083
1084                     // Remove the translucent navigation bar flag if it is set.
1085                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1086
1087                     // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1088                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1089
1090                     // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1091                     rootCoordinatorLayout.setFitsSystemWindows(true);
1092                 }
1093
1094                 // Show the ad if this is the free flavor.
1095                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1096                     // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1097                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1098                 }
1099             }
1100
1101             // Upload files.
1102             @Override
1103             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1104                 // Show the file chooser if the device is running API >= 21.
1105                 if (Build.VERSION.SDK_INT >= 21) {
1106                     // Store the file path callback.
1107                     fileChooserCallback = filePathCallback;
1108
1109                     // Create an intent to open a chooser based ont the file chooser parameters.
1110                     Intent fileChooserIntent = fileChooserParams.createIntent();
1111
1112                     // Open the file chooser.  Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1113                     startActivityForResult(fileChooserIntent, 0);
1114                 }
1115                 return true;
1116             }
1117         });
1118
1119         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
1120         registerForContextMenu(mainWebView);
1121
1122         // Allow the downloading of files.
1123         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1124             // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1125             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1126                 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1127
1128                 // Store the variables for future use by `onRequestPermissionsResult()`.
1129                 downloadUrl = url;
1130                 downloadContentDisposition = contentDisposition;
1131                 downloadContentLength = contentLength;
1132
1133                 // Show a dialog if the user has previously denied the permission.
1134                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
1135                     // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1136                     DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1137
1138                     // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
1139                     downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1140                 } else {  // Show the permission request directly.
1141                     // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
1142                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1143                 }
1144             } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1145                 // Get a handle for the download file alert dialog.
1146                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1147
1148                 // Show the download file alert dialog.
1149                 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1150             }
1151         });
1152
1153         // Allow pinch to zoom.
1154         mainWebView.getSettings().setBuiltInZoomControls(true);
1155
1156         // Hide zoom controls.
1157         mainWebView.getSettings().setDisplayZoomControls(false);
1158
1159         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
1160         mainWebView.getSettings().setUseWideViewPort(true);
1161
1162         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1163         mainWebView.getSettings().setLoadWithOverviewMode(true);
1164
1165         // Explicitly disable geolocation.
1166         mainWebView.getSettings().setGeolocationEnabled(false);
1167
1168         // Initialize cookieManager.
1169         cookieManager = CookieManager.getInstance();
1170
1171         // Replace the header that `WebView` creates for `X-Requested-With` with a null value.  The default value is the application ID (com.stoutner.privacybrowser.standard).
1172         customHeaders.put("X-Requested-With", "");
1173
1174         // Initialize the default preference values the first time the program is run.  `this` is the context.  `false` keeps this command from resetting any current preferences back to default.
1175         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1176
1177         // Get the intent that started the app.
1178         final Intent launchingIntent = getIntent();
1179
1180         // Extract the launching intent data as `launchingIntentUriData`.
1181         final Uri launchingIntentUriData = launchingIntent.getData();
1182
1183         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1184         if (launchingIntentUriData != null) {
1185             formattedUrlString = launchingIntentUriData.toString();
1186         }
1187
1188         // Get a handle for the `Runtime`.
1189         privacyBrowserRuntime = Runtime.getRuntime();
1190
1191         // Store the application's private data directory.
1192         privateDataDirectoryString = getApplicationInfo().dataDir;
1193         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1194
1195         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1196         inFullScreenBrowsingMode = false;
1197
1198         // Initialize the privacy settings variables.
1199         javaScriptEnabled = false;
1200         firstPartyCookiesEnabled = false;
1201         thirdPartyCookiesEnabled = false;
1202         domStorageEnabled = false;
1203         saveFormDataEnabled = false;  // Form data can be removed once the minimum API >= 26.
1204         nightMode = false;
1205
1206         // Initialize the WebView title.
1207         webViewTitle = getString(R.string.no_title);
1208
1209         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1210         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1211         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1212         assert favoriteIconBitmapDrawable != null;
1213         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1214
1215         // If the favorite icon is null, load the default.
1216         if (favoriteIconBitmap == null) {
1217             favoriteIconBitmap = favoriteIconDefaultBitmap;
1218         }
1219
1220         // Initialize the user agent array adapter and string array.
1221         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1222         userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1223
1224         // Apply the app settings from the shared preferences.
1225         applyAppSettings();
1226
1227         // Instantiate the block list helper.
1228         BlockListHelper blockListHelper = new BlockListHelper();
1229
1230         // Initialize the list of resource requests.
1231         resourceRequests = new ArrayList<>();
1232
1233         // Parse the block lists.
1234         final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1235         final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1236         final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1237         final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1238
1239         // Store the list versions.
1240         easyListVersion = easyList.get(0).get(0)[0];
1241         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1242         fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1243         fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1244
1245         mainWebView.setWebViewClient(new WebViewClient() {
1246             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1247             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1248             @SuppressWarnings("deprecation")
1249             @Override
1250             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1251                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
1252                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1253                     formattedUrlString = "";
1254
1255                     // Apply the domain settings for the new URL.  `applyDomainSettings` doesn't do anything if the domain has not changed.
1256                     applyDomainSettings(url, true, false);
1257
1258                     // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1259                     return false;
1260                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1261                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1262                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1263
1264                     // Parse the url and set it as the data for the intent.
1265                     emailIntent.setData(Uri.parse(url));
1266
1267                     // Open the email program in a new task instead of as part of Privacy Browser.
1268                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1269
1270                     // Make it so.
1271                     startActivity(emailIntent);
1272
1273                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1274                     return true;
1275                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1276                     // Open the dialer and load the phone number, but wait for the user to place the call.
1277                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1278
1279                     // Add the phone number to the intent.
1280                     dialIntent.setData(Uri.parse(url));
1281
1282                     // Open the dialer in a new task instead of as part of Privacy Browser.
1283                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1284
1285                     // Make it so.
1286                     startActivity(dialIntent);
1287
1288                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1289                     return true;
1290                 } else {  // Load a system chooser to select an app that can handle the URL.
1291                     // Open an app that can handle the URL.
1292                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1293
1294                     // Add the URL to the intent.
1295                     genericIntent.setData(Uri.parse(url));
1296
1297                     // List all apps that can handle the URL instead of just opening the first one.
1298                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1299
1300                     // Open the app in a new task instead of as part of Privacy Browser.
1301                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1302
1303                     // Start the app or display a snackbar if no app is available to handle the URL.
1304                     try {
1305                         startActivity(genericIntent);
1306                     } catch (ActivityNotFoundException exception) {
1307                         Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
1308                     }
1309
1310                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1311                     return true;
1312                 }
1313             }
1314
1315             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1316             @SuppressWarnings("deprecation")
1317             @Override
1318             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1319                 // Create an empty web resource response to be used if the resource request is blocked.
1320                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1321
1322                 // Reset `whiteListResultStringArray`.
1323                 whiteListResultStringArray = null;
1324
1325                 // Initialize the third party request tracker.
1326                 boolean isThirdPartyRequest = false;
1327
1328                 // Initialize the current domain string.
1329                 String currentDomain = "";
1330
1331                 // Nobody is happy when comparing null strings.
1332                 if (!(formattedUrlString == null) && !(url == null)) {
1333                     // Get the domain strings to URIs.
1334                     Uri currentDomainUri = Uri.parse(formattedUrlString);
1335                     Uri requestDomainUri = Uri.parse(url);
1336
1337                     // Get the domain host names.
1338                     String currentBaseDomain = currentDomainUri.getHost();
1339                     String requestBaseDomain = requestDomainUri.getHost();
1340
1341                     // Update the current domain variable.
1342                     currentDomain = currentBaseDomain;
1343
1344                     // Only compare the current base domain and the request base domain if neither is null.
1345                     if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1346                         // Determine the current base domain.
1347                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1348                             // Remove the first subdomain.
1349                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1350                         }
1351
1352                         // Determine the request base domain.
1353                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1354                             // Remove the first subdomain.
1355                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1356                         }
1357
1358                         // Update the third party request tracker.
1359                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1360                     }
1361                 }
1362
1363                 // Block third-party requests if enabled.
1364                 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1365                     // Add the request to the log.
1366                     resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1367
1368                     // Return an empty web resource response.
1369                     return emptyWebResourceResponse;
1370                 }
1371
1372                 // Check EasyList if it is enabled.
1373                 if (easyListEnabled) {
1374                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1375                         // The resource request was blocked.  Return an empty web resource response.
1376                         return emptyWebResourceResponse;
1377                     }
1378                 }
1379
1380                 // Check EasyPrivacy if it is enabled.
1381                 if (easyPrivacyEnabled) {
1382                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1383                         // The resource request was blocked.  Return an empty web resource response.
1384                         return emptyWebResourceResponse;
1385                     }
1386                 }
1387
1388                 // Check Fanboy’s Annoyance List if it is enabled.
1389                 if (fanboysAnnoyanceListEnabled) {
1390                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1391                         // The resource request was blocked.  Return an empty web resource response.
1392                         return emptyWebResourceResponse;
1393                     }
1394                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1395                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1396                         // The resource request was blocked.  Return an empty web resource response.
1397                         return emptyWebResourceResponse;
1398                     }
1399                 }
1400
1401                 // Add the request to the log because it hasn't been processed by any of the previous checks.
1402                 if (whiteListResultStringArray != null ) {  // The request was processed by a whitelist.
1403                     resourceRequests.add(whiteListResultStringArray);
1404                 } else {  // The request didn't match any blocklist entry.  Log it as a defult request.
1405                     resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1406                 }
1407
1408                 // The resource request has not been blocked.  `return null` loads the requested resource.
1409                 return null;
1410             }
1411
1412             // Handle HTTP authentication requests.
1413             @Override
1414             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1415                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1416                 httpAuthHandler = handler;
1417
1418                 // Display the HTTP authentication dialog.
1419                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1420                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1421             }
1422
1423             // Update the URL in urlTextBox when the page starts to load.
1424             @Override
1425             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1426                 // Reset the list of resource requests.
1427                 resourceRequests.clear();
1428
1429                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1430                 if (nightMode) {
1431                     mainWebView.setVisibility(View.INVISIBLE);
1432                 }
1433
1434                 // Hide the keyboard.  `0` indicates no additional flags.
1435                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1436
1437                 // Check to see if Privacy Browser is waiting on Orbot.
1438                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1439                     // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
1440                     formattedUrlString = url;
1441
1442                     // Display the formatted URL text.
1443                     urlTextBox.setText(formattedUrlString);
1444
1445                     // Apply text highlighting to `urlTextBox`.
1446                     highlightUrlText();
1447
1448                     // Apply any custom domain settings if the URL was loaded by navigating history.
1449                     if (navigatingHistory) {
1450                         // Reset `navigatingHistory`.
1451                         navigatingHistory = false;
1452
1453                         // Apply the domain settings.
1454                         applyDomainSettings(url, true, false);
1455                     }
1456
1457                     // Set `urlIsLoading` to `true`, so that redirects while loading do not trigger changes in the user agent, which forces another reload of the existing page.
1458                     urlIsLoading = true;
1459                 }
1460             }
1461
1462             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1463             @Override
1464             public void onPageFinished(WebView view, String url) {
1465                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1466                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1467                     cookieManager.flush();
1468                 }
1469
1470                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1471                 urlIsLoading = false;
1472
1473                 // Clear the cache and history if Incognito Mode is enabled.
1474                 if (incognitoModeEnabled) {
1475                     // Clear the cache.  `true` includes disk files.
1476                     mainWebView.clearCache(true);
1477
1478                     // Clear the back/forward history.
1479                     mainWebView.clearHistory();
1480
1481                     // Manually delete cache folders.
1482                     try {
1483                         // Delete the main cache directory.
1484                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1485
1486                         // Delete the secondary `Service Worker` cache directory.
1487                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1488                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1489                     } catch (IOException e) {
1490                         // Do nothing if an error is thrown.
1491                     }
1492                 }
1493
1494                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1495                 if (!waitingForOrbot) {
1496                     // Check to see if `WebView` has set `url` to be `about:blank`.
1497                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1498                         // Set `formattedUrlString` to `""`.
1499                         formattedUrlString = "";
1500
1501                         urlTextBox.setText(formattedUrlString);
1502
1503                         // Request focus for `urlTextBox`.
1504                         urlTextBox.requestFocus();
1505
1506                         // Display the keyboard.
1507                         inputMethodManager.showSoftInput(urlTextBox, 0);
1508
1509                         // Apply the domain settings.  This clears any settings from the previous domain.
1510                         applyDomainSettings(formattedUrlString, true, false);
1511                     } else {  // `WebView` has loaded a webpage.
1512                         // Set `formattedUrlString`.
1513                         formattedUrlString = url;
1514
1515                         // Only update `urlTextBox` if the user is not typing in it.
1516                         if (!urlTextBox.hasFocus()) {
1517                             // Display the formatted URL text.
1518                             urlTextBox.setText(formattedUrlString);
1519
1520                             // Apply text highlighting to `urlTextBox`.
1521                             highlightUrlText();
1522                         }
1523                     }
1524
1525                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1526                     sslCertificate = mainWebView.getCertificate();
1527
1528                     // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
1529                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1530                         // Initialize the current SSL certificate variables.
1531                         String currentWebsiteIssuedToCName = "";
1532                         String currentWebsiteIssuedToOName = "";
1533                         String currentWebsiteIssuedToUName = "";
1534                         String currentWebsiteIssuedByCName = "";
1535                         String currentWebsiteIssuedByOName = "";
1536                         String currentWebsiteIssuedByUName = "";
1537                         Date currentWebsiteSslStartDate = null;
1538                         Date currentWebsiteSslEndDate = null;
1539
1540
1541                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1542                         if (sslCertificate != null) {
1543                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1544                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1545                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1546                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1547                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1548                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1549                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1550                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1551                         }
1552
1553                         // Initialize `String` variables to store the SSL certificate dates.  `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
1554                         String currentWebsiteSslStartDateString = "";
1555                         String currentWebsiteSslEndDateString = "";
1556                         String pinnedDomainSslStartDateString = "";
1557                         String pinnedDomainSslEndDateString = "";
1558
1559                         // Convert the `Dates` to `Strings` if they are not `null`.
1560                         if (currentWebsiteSslStartDate != null) {
1561                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1562                         }
1563
1564                         if (currentWebsiteSslEndDate != null) {
1565                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1566                         }
1567
1568                         if (pinnedDomainSslStartDate != null) {
1569                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1570                         }
1571
1572                         if (pinnedDomainSslEndDate != null) {
1573                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1574                         }
1575
1576                         // Check to see if the pinned SSL certificate matches the current website certificate.
1577                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1578                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1579                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1580                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1581                             // The pinned SSL certificate doesn't match the current domain certificate.
1582                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1583                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1584                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1585                         }
1586                     }
1587                 }
1588             }
1589
1590             // Handle SSL Certificate errors.
1591             @Override
1592             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1593                 // Get the current website SSL certificate.
1594                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1595
1596                 // Extract the individual pieces of information from the current website SSL certificate.
1597                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1598                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1599                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1600                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1601                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1602                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1603                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1604                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1605
1606                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1607                 if (pinnedDomainSslCertificate &&
1608                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1609                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1610                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1611                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1612                     // An SSL certificate is pinned and matches the current domain certificate.
1613                     // Proceed to the website without displaying an error.
1614                     handler.proceed();
1615                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1616                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1617                     sslErrorHandler = handler;
1618
1619                     // Display the SSL error `AlertDialog`.
1620                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1621                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1622                 }
1623             }
1624         });
1625
1626         // Load the website if not waiting for Orbot to connect.
1627         if (!waitingForOrbot) {
1628             loadUrl(formattedUrlString);
1629         }
1630     }
1631
1632     @Override
1633     protected void onNewIntent(Intent intent) {
1634         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1635         setIntent(intent);
1636
1637         // Check to see if the intent contains a new URL.
1638         if (intent.getData() != null) {
1639             // Get the intent data.
1640             final Uri intentUriData = intent.getData();
1641
1642             // Load the website.
1643             loadUrl(intentUriData.toString());
1644
1645             // Close the navigation drawer if it is open.
1646             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1647                 drawerLayout.closeDrawer(GravityCompat.START);
1648             }
1649
1650             // Close the bookmarks drawer if it is open.
1651             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1652                 drawerLayout.closeDrawer(GravityCompat.END);
1653             }
1654
1655             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1656             mainWebView.requestFocus();
1657         }
1658     }
1659
1660     @Override
1661     public void onRestart() {
1662         // Run the default commands.
1663         super.onRestart();
1664
1665         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1666         if (proxyThroughOrbot) {
1667             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1668             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1669
1670             // Send the intent to the Orbot package.
1671             orbotIntent.setPackage("org.torproject.android");
1672
1673             // Make it so.
1674             sendBroadcast(orbotIntent);
1675         }
1676
1677         // Apply the app settings if returning from the Settings activity..
1678         if (reapplyAppSettingsOnRestart) {
1679             // Apply the app settings.
1680             applyAppSettings();
1681
1682             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1683             if (reloadOnRestart) {
1684                 // Reload `mainWebView`.
1685                 mainWebView.reload();
1686
1687                 // Reset `reloadOnRestartBoolean`.
1688                 reloadOnRestart = false;
1689             }
1690
1691             // Reset the return from settings flag.
1692             reapplyAppSettingsOnRestart = false;
1693         }
1694
1695         // Apply the domain settings if returning from the Domains activity.
1696         if (reapplyDomainSettingsOnRestart) {
1697             // Reapply the domain settings.
1698             applyDomainSettings(formattedUrlString, false, true);
1699
1700             // Reset `reapplyDomainSettingsOnRestart`.
1701             reapplyDomainSettingsOnRestart = false;
1702         }
1703
1704         // Load the URL on restart to apply changes to night mode.
1705         if (loadUrlOnRestart) {
1706             // Load the current `formattedUrlString`.
1707             loadUrl(formattedUrlString);
1708
1709             // Reset `loadUrlOnRestart.
1710             loadUrlOnRestart = false;
1711         }
1712
1713         // Update the bookmarks drawer if returning from the Bookmarks activity.
1714         if (restartFromBookmarksActivity) {
1715             // Close the bookmarks drawer.
1716             drawerLayout.closeDrawer(GravityCompat.END);
1717
1718             // Reload the bookmarks drawer.
1719             loadBookmarksFolder();
1720
1721             // Reset `restartFromBookmarksActivity`.
1722             restartFromBookmarksActivity = false;
1723         }
1724
1725         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1726         updatePrivacyIcons(true);
1727     }
1728
1729     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1730     @Override
1731     public void onResume() {
1732         // Run the default commands.
1733         super.onResume();
1734
1735         // Resume JavaScript (if enabled).
1736         mainWebView.resumeTimers();
1737
1738         // Resume `mainWebView`.
1739         mainWebView.onResume();
1740
1741         // Resume the adView for the free flavor.
1742         if (BuildConfig.FLAVOR.contentEquals("free")) {
1743             // Resume the ad.
1744             AdHelper.resumeAd(findViewById(R.id.adview));
1745         }
1746
1747         // Display a message to the user if waiting for Orbot.
1748         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1749             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1750             mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1751         }
1752
1753         if (displayingFullScreenVideo) {
1754             // Remove the translucent overlays.
1755             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1756
1757             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1758             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1759
1760             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1761              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1762              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1763              */
1764             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1765         }
1766     }
1767
1768     @Override
1769     public void onPause() {
1770         super.onPause();
1771
1772         // Pause `mainWebView`.
1773         mainWebView.onPause();
1774
1775         // Stop all JavaScript.
1776         mainWebView.pauseTimers();
1777
1778         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1779         if (BuildConfig.FLAVOR.contentEquals("free")) {
1780             // Pause the ad.
1781             AdHelper.pauseAd(findViewById(R.id.adview));
1782         }
1783     }
1784
1785     @Override
1786     public boolean onCreateOptionsMenu(Menu menu) {
1787         // Inflate the menu; this adds items to the action bar if it is present.
1788         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1789
1790         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1791         mainMenu = menu;
1792
1793         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1794         updatePrivacyIcons(false);
1795
1796         // Get handles for the menu items.
1797         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1798         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1799         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1800         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1801         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1802         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1803         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1804
1805         // Only display third-party cookies if API >= 21
1806         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1807
1808         // Only display the form data menu items if the API < 26.
1809         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1810         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1811
1812         // Only show Ad Consent if this is the free flavor.
1813         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1814
1815         // Get the shared preference values.  `this` references the current context.
1816         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1817
1818         // Set the status of the additional app bar icons.  Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
1819         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1820             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1821             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1822             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1823         } else { //Do not display the additional icons.
1824             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1825             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1826             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1827         }
1828
1829         return true;
1830     }
1831
1832     @Override
1833     public boolean onPrepareOptionsMenu(Menu menu) {
1834         // Get handles for the menu items.
1835         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1836         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1837         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1838         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1839         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1840         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1841         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1842         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1843         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1844         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1845         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1846         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1847         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1848         MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1849         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1850         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1851         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1852
1853         // Set the text for the domain menu item.
1854         if (domainSettingsApplied) {
1855             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1856         } else {
1857             addOrEditDomain.setTitle(R.string.add_domain_settings);
1858         }
1859
1860         // Set the status of the menu item checkboxes.
1861         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1862         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1863         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1864         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
1865         easyListMenuItem.setChecked(easyListEnabled);
1866         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1867         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1868         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1869         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1870         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1871         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1872
1873         // Enable third-party cookies if first-party cookies are enabled.
1874         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1875
1876         // Enable DOM Storage if JavaScript is enabled.
1877         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1878
1879         // Enable Clear Cookies if there are any.
1880         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1881
1882         // Get a count of the number of files in the Local Storage directory.
1883         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1884         int localStorageDirectoryNumberOfFiles = 0;
1885         if (localStorageDirectory.exists()) {
1886             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1887         }
1888
1889         // Get a count of the number of files in the IndexedDB directory.
1890         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1891         int indexedDBDirectoryNumberOfFiles = 0;
1892         if (indexedDBDirectory.exists()) {
1893             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1894         }
1895
1896         // Enable Clear DOM Storage if there is any.
1897         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1898
1899         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1900         if (Build.VERSION.SDK_INT < 26) {
1901             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1902             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1903         }
1904
1905         // Enable Clear Data if any of the submenu items are enabled.
1906         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1907
1908         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1909         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1910
1911         // Initialize font size variables.
1912         int fontSize = mainWebView.getSettings().getTextZoom();
1913         String fontSizeTitle;
1914         MenuItem selectedFontSizeMenuItem;
1915
1916         // Prepare the font size title and current size menu item.
1917         switch (fontSize) {
1918             case 25:
1919                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1920                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1921                 break;
1922
1923             case 50:
1924                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1925                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1926                 break;
1927
1928             case 75:
1929                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1930                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1931                 break;
1932
1933             case 100:
1934                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1935                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1936                 break;
1937
1938             case 125:
1939                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1940                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1941                 break;
1942
1943             case 150:
1944                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1945                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1946                 break;
1947
1948             case 175:
1949                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1950                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1951                 break;
1952
1953             case 200:
1954                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1955                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1956                 break;
1957
1958             default:
1959                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1960                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1961                 break;
1962         }
1963
1964         // Set the font size title and select the current size menu item.
1965         fontSizeMenuItem.setTitle(fontSizeTitle);
1966         selectedFontSizeMenuItem.setChecked(true);
1967
1968         // Run all the other default commands.
1969         super.onPrepareOptionsMenu(menu);
1970
1971         // Display the menu.
1972         return true;
1973     }
1974
1975     @Override
1976     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1977     @SuppressLint("SetJavaScriptEnabled")
1978     // removeAllCookies is deprecated, but it is required for API < 21.
1979     @SuppressWarnings("deprecation")
1980     public boolean onOptionsItemSelected(MenuItem menuItem) {
1981         // Get the selected menu item ID.
1982         int menuItemId = menuItem.getItemId();
1983
1984         // Set the commands that relate to the menu entries.
1985         switch (menuItemId) {
1986             case R.id.toggle_javascript:
1987                 // Switch the status of javaScriptEnabled.
1988                 javaScriptEnabled = !javaScriptEnabled;
1989
1990                 // Apply the new JavaScript status.
1991                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1992
1993                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1994                 updatePrivacyIcons(true);
1995
1996                 // Display a `Snackbar`.
1997                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1998                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1999                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
2000                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2001                 } else {  // Privacy mode.
2002                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2003                 }
2004
2005                 // Reload the WebView.
2006                 mainWebView.reload();
2007                 return true;
2008
2009             case R.id.add_or_edit_domain:
2010                 if (domainSettingsApplied) {  // Edit the current domain settings.
2011                     // Reapply the domain settings on returning to `MainWebViewActivity`.
2012                     reapplyDomainSettingsOnRestart = true;
2013                     currentDomainName = "";
2014
2015                     // Create an intent to launch the domains activity.
2016                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2017
2018                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2019                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2020                     domainsIntent.putExtra("closeOnBack", true);
2021
2022                     // Make it so.
2023                     startActivity(domainsIntent);
2024                 } else {  // Add a new domain.
2025                     // Apply the new domain settings on returning to `MainWebViewActivity`.
2026                     reapplyDomainSettingsOnRestart = true;
2027                     currentDomainName = "";
2028
2029                     // Get the current domain
2030                     Uri currentUri = Uri.parse(formattedUrlString);
2031                     String currentDomain = currentUri.getHost();
2032
2033                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2034                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2035
2036                     // Create the domain and store the database ID.
2037                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2038
2039                     // Create an intent to launch the domains activity.
2040                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2041
2042                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2043                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2044                     domainsIntent.putExtra("closeOnBack", true);
2045
2046                     // Make it so.
2047                     startActivity(domainsIntent);
2048                 }
2049                 return true;
2050
2051             case R.id.toggle_first_party_cookies:
2052                 // Switch the status of firstPartyCookiesEnabled.
2053                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2054
2055                 // Update the menu checkbox.
2056                 menuItem.setChecked(firstPartyCookiesEnabled);
2057
2058                 // Apply the new cookie status.
2059                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2060
2061                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2062                 updatePrivacyIcons(true);
2063
2064                 // Display a `Snackbar`.
2065                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2066                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2067                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
2068                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2069                 } else {  // Privacy mode.
2070                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2071                 }
2072
2073                 // Reload the WebView.
2074                 mainWebView.reload();
2075                 return true;
2076
2077             case R.id.toggle_third_party_cookies:
2078                 if (Build.VERSION.SDK_INT >= 21) {
2079                     // Switch the status of thirdPartyCookiesEnabled.
2080                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2081
2082                     // Update the menu checkbox.
2083                     menuItem.setChecked(thirdPartyCookiesEnabled);
2084
2085                     // Apply the new cookie status.
2086                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2087
2088                     // Display a `Snackbar`.
2089                     if (thirdPartyCookiesEnabled) {
2090                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2091                     } else {
2092                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2093                     }
2094
2095                     // Reload the WebView.
2096                     mainWebView.reload();
2097                 } // Else do nothing because SDK < 21.
2098                 return true;
2099
2100             case R.id.toggle_dom_storage:
2101                 // Switch the status of domStorageEnabled.
2102                 domStorageEnabled = !domStorageEnabled;
2103
2104                 // Update the menu checkbox.
2105                 menuItem.setChecked(domStorageEnabled);
2106
2107                 // Apply the new DOM Storage status.
2108                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2109
2110                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2111                 updatePrivacyIcons(true);
2112
2113                 // Display a `Snackbar`.
2114                 if (domStorageEnabled) {
2115                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2116                 } else {
2117                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2118                 }
2119
2120                 // Reload the WebView.
2121                 mainWebView.reload();
2122                 return true;
2123
2124             // Form data can be removed once the minimum API >= 26.
2125             case R.id.toggle_save_form_data:
2126                 // Switch the status of saveFormDataEnabled.
2127                 saveFormDataEnabled = !saveFormDataEnabled;
2128
2129                 // Update the menu checkbox.
2130                 menuItem.setChecked(saveFormDataEnabled);
2131
2132                 // Apply the new form data status.
2133                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2134
2135                 // Display a `Snackbar`.
2136                 if (saveFormDataEnabled) {
2137                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2138                 } else {
2139                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2140                 }
2141
2142                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2143                 updatePrivacyIcons(true);
2144
2145                 // Reload the WebView.
2146                 mainWebView.reload();
2147                 return true;
2148
2149             case R.id.clear_cookies:
2150                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2151                         .setAction(R.string.undo, v -> {
2152                             // Do nothing because everything will be handled by `onDismissed()` below.
2153                         })
2154                         .addCallback(new Snackbar.Callback() {
2155                             @Override
2156                             public void onDismissed(Snackbar snackbar, int event) {
2157                                 switch (event) {
2158                                     // The user pushed the `Undo` button.
2159                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2160                                         // Do nothing.
2161                                         break;
2162
2163                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2164                                     default:
2165                                         // `cookieManager.removeAllCookie()` varies by SDK.
2166                                         if (Build.VERSION.SDK_INT < 21) {
2167                                             cookieManager.removeAllCookie();
2168                                         } else {
2169                                             // `null` indicates no callback.
2170                                             cookieManager.removeAllCookies(null);
2171                                         }
2172                                 }
2173                             }
2174                         })
2175                         .show();
2176                 return true;
2177
2178             case R.id.clear_dom_storage:
2179                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2180                         .setAction(R.string.undo, v -> {
2181                             // Do nothing because everything will be handled by `onDismissed()` below.
2182                         })
2183                         .addCallback(new Snackbar.Callback() {
2184                             @Override
2185                             public void onDismissed(Snackbar snackbar, int event) {
2186                                 switch (event) {
2187                                     // The user pushed the `Undo` button.
2188                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2189                                         // Do nothing.
2190                                         break;
2191
2192                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2193                                     default:
2194                                         // Delete the DOM Storage.
2195                                         WebStorage webStorage = WebStorage.getInstance();
2196                                         webStorage.deleteAllData();
2197
2198                                         // Manually delete the DOM storage files and directories.
2199                                         try {
2200                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2201                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2202
2203                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2204                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2205                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2206                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2207                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2208                                         } catch (IOException e) {
2209                                             // Do nothing if an error is thrown.
2210                                         }
2211                                 }
2212                             }
2213                         })
2214                         .show();
2215                 return true;
2216
2217             // Form data can be remove once the minimum API >= 26.
2218             case R.id.clear_form_data:
2219                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2220                         .setAction(R.string.undo, v -> {
2221                             // Do nothing because everything will be handled by `onDismissed()` below.
2222                         })
2223                         .addCallback(new Snackbar.Callback() {
2224                             @Override
2225                             public void onDismissed(Snackbar snackbar, int event) {
2226                                 switch (event) {
2227                                     // The user pushed the `Undo` button.
2228                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2229                                         // Do nothing.
2230                                         break;
2231
2232                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2233                                     default:
2234                                         // Delete the form data.
2235                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2236                                         mainWebViewDatabase.clearFormData();
2237                                 }
2238                             }
2239                         })
2240                         .show();
2241                 return true;
2242
2243             case R.id.font_size_twenty_five_percent:
2244                 mainWebView.getSettings().setTextZoom(25);
2245                 return true;
2246
2247             case R.id.font_size_fifty_percent:
2248                 mainWebView.getSettings().setTextZoom(50);
2249                 return true;
2250
2251             case R.id.font_size_seventy_five_percent:
2252                 mainWebView.getSettings().setTextZoom(75);
2253                 return true;
2254
2255             case R.id.font_size_one_hundred_percent:
2256                 mainWebView.getSettings().setTextZoom(100);
2257                 return true;
2258
2259             case R.id.font_size_one_hundred_twenty_five_percent:
2260                 mainWebView.getSettings().setTextZoom(125);
2261                 return true;
2262
2263             case R.id.font_size_one_hundred_fifty_percent:
2264                 mainWebView.getSettings().setTextZoom(150);
2265                 return true;
2266
2267             case R.id.font_size_one_hundred_seventy_five_percent:
2268                 mainWebView.getSettings().setTextZoom(175);
2269                 return true;
2270
2271             case R.id.font_size_two_hundred_percent:
2272                 mainWebView.getSettings().setTextZoom(200);
2273                 return true;
2274
2275             case R.id.swipe_to_refresh:
2276                 // Toggle swipe to refresh.
2277                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2278                 return true;
2279
2280             case R.id.display_images:
2281                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2282                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2283                     mainWebView.reload();
2284                 } else {  // Images are not currently loaded automatically.
2285                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2286                 }
2287
2288                 // Set `onTheFlyDisplayImagesSet`.
2289                 onTheFlyDisplayImagesSet = true;
2290                 return true;
2291
2292             case R.id.view_source:
2293                 // Launch the View Source activity.
2294                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2295                 startActivity(viewSourceIntent);
2296                 return true;
2297
2298             case R.id.easylist:
2299                 // Toggle the EasyList status.
2300                 easyListEnabled = !easyListEnabled;
2301
2302                 // Update the menu checkbox.
2303                 menuItem.setChecked(easyListEnabled);
2304
2305                 // Reload the main WebView.
2306                 mainWebView.reload();
2307                 return true;
2308
2309             case R.id.easyprivacy:
2310                 // Toggle the EasyPrivacy status.
2311                 easyPrivacyEnabled = !easyPrivacyEnabled;
2312
2313                 // Update the menu checkbox.
2314                 menuItem.setChecked(easyPrivacyEnabled);
2315
2316                 // Reload the main WebView.
2317                 mainWebView.reload();
2318                 return true;
2319
2320             case R.id.fanboys_annoyance_list:
2321                 // Toggle Fanboy's Annoyance List status.
2322                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2323
2324                 // Update the menu checkbox.
2325                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2326
2327                 // Update the staus of Fanboy's Social Blocking List.
2328                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2329                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2330
2331                 // Reload the main WebView.
2332                 mainWebView.reload();
2333                 return true;
2334
2335             case R.id.fanboys_social_blocking_list:
2336                 // Toggle Fanboy's Social Blocking List status.
2337                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2338
2339                 // Update the menu checkbox.
2340                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2341
2342                 // Reload the main WebView.
2343                 mainWebView.reload();
2344                 return true;
2345
2346             case R.id.block_all_third_party_requests:
2347                 //Toggle the third-party requests blocker status.
2348                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2349
2350                 // Update the menu checkbox.
2351                 menuItem.setChecked(blockAllThirdPartyRequests);
2352
2353                 // Reload the main WebView.
2354                 mainWebView.reload();
2355                 return true;
2356
2357             case R.id.share:
2358                 // Setup the share string.
2359                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2360
2361                 // Create the share intent.
2362                 Intent shareIntent = new Intent();
2363                 shareIntent.setAction(Intent.ACTION_SEND);
2364                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2365                 shareIntent.setType("text/plain");
2366
2367                 // Make it so.
2368                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2369                 return true;
2370
2371             case R.id.find_on_page:
2372                 // Hide the URL app bar.
2373                 supportAppBar.setVisibility(View.GONE);
2374
2375                 // Show the Find on Page `RelativeLayout`.
2376                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2377
2378                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2379                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2380                 findOnPageEditText.postDelayed(() -> {
2381                     // Set the focus on `findOnPageEditText`.
2382                     findOnPageEditText.requestFocus();
2383
2384                     // Display the keyboard.  `0` sets no input flags.
2385                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2386                 }, 200);
2387                 return true;
2388
2389             case R.id.print:
2390                 // Get a `PrintManager` instance.
2391                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2392
2393                 // Convert `mainWebView` to `printDocumentAdapter`.
2394                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2395
2396                 // Remove the lint error below that `printManager` might be `null`.
2397                 assert printManager != null;
2398
2399                 // Print the document.  The print attributes are `null`.
2400                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2401                 return true;
2402
2403             case R.id.add_to_homescreen:
2404                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2405                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2406                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2407
2408                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2409                 return true;
2410
2411             case R.id.refresh:
2412                 mainWebView.reload();
2413                 return true;
2414
2415             case R.id.ad_consent:
2416                 // Display the ad consent dialog.
2417                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2418                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2419                 return true;
2420
2421             default:
2422                 // Don't consume the event.
2423                 return super.onOptionsItemSelected(menuItem);
2424         }
2425     }
2426
2427     // removeAllCookies is deprecated, but it is required for API < 21.
2428     @SuppressWarnings("deprecation")
2429     @Override
2430     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2431         int menuItemId = menuItem.getItemId();
2432
2433         switch (menuItemId) {
2434             case R.id.home:
2435                 loadUrl(homepage);
2436                 break;
2437
2438             case R.id.back:
2439                 if (mainWebView.canGoBack()) {
2440                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2441                     formattedUrlString = "";
2442
2443                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2444                     navigatingHistory = true;
2445
2446                     // Load the previous website in the history.
2447                     mainWebView.goBack();
2448                 }
2449                 break;
2450
2451             case R.id.forward:
2452                 if (mainWebView.canGoForward()) {
2453                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2454                     formattedUrlString = "";
2455
2456                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2457                     navigatingHistory = true;
2458
2459                     // Load the next website in the history.
2460                     mainWebView.goForward();
2461                 }
2462                 break;
2463
2464             case R.id.history:
2465                 // Get the `WebBackForwardList`.
2466                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2467
2468                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2469                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2470                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2471                 break;
2472
2473             case R.id.requests:
2474                 // Launch the requests activity.
2475                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2476                 startActivity(requestsIntent);
2477                 break;
2478
2479             case R.id.downloads:
2480                 // Launch the system Download Manager.
2481                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2482
2483                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2484                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2485
2486                 startActivity(downloadManagerIntent);
2487                 break;
2488
2489             case R.id.domains:
2490                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2491                 reapplyDomainSettingsOnRestart = true;
2492                 currentDomainName = "";
2493
2494                 // Launch the domains activity.
2495                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2496                 startActivity(domainsIntent);
2497                 break;
2498
2499             case R.id.settings:
2500                 // Set the flag to reapply app settings on restart when returning from Settings.
2501                 reapplyAppSettingsOnRestart = true;
2502
2503                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2504                 reapplyDomainSettingsOnRestart = true;
2505                 currentDomainName = "";
2506
2507                 // Launch the settings activity.
2508                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2509                 startActivity(settingsIntent);
2510                 break;
2511
2512             case R.id.guide:
2513                 // Launch `GuideActivity`.
2514                 Intent guideIntent = new Intent(this, GuideActivity.class);
2515                 startActivity(guideIntent);
2516                 break;
2517
2518             case R.id.about:
2519                 // Launch `AboutActivity`.
2520                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2521                 startActivity(aboutIntent);
2522                 break;
2523
2524             case R.id.clearAndExit:
2525                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2526                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2527
2528                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2529
2530                 // Clear cookies.
2531                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2532                     // The command to remove cookies changed slightly in API 21.
2533                     if (Build.VERSION.SDK_INT >= 21) {
2534                         cookieManager.removeAllCookies(null);
2535                     } else {
2536                         cookieManager.removeAllCookie();
2537                     }
2538
2539                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2540                     try {
2541                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2542                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2543                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2544                     } catch (IOException e) {
2545                         // Do nothing if an error is thrown.
2546                     }
2547                 }
2548
2549                 // Clear DOM storage.
2550                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2551                     // Ask `WebStorage` to clear the DOM storage.
2552                     WebStorage webStorage = WebStorage.getInstance();
2553                     webStorage.deleteAllData();
2554
2555                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2556                     try {
2557                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2558                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2559
2560                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2561                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2562                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2563                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2564                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2565                     } catch (IOException e) {
2566                         // Do nothing if an error is thrown.
2567                     }
2568                 }
2569
2570                 // Clear form data if the API < 26.
2571                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2572                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2573                     webViewDatabase.clearFormData();
2574
2575                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2576                     try {
2577                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2578                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2579                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2580                     } catch (IOException e) {
2581                         // Do nothing if an error is thrown.
2582                     }
2583                 }
2584
2585                 // Clear the cache.
2586                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2587                     // `true` includes disk files.
2588                     mainWebView.clearCache(true);
2589
2590                     // Manually delete the cache directories.
2591                     try {
2592                         // Delete the main cache directory.
2593                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2594
2595                         // Delete the secondary `Service Worker` cache directory.
2596                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2597                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2598                     } catch (IOException e) {
2599                         // Do nothing if an error is thrown.
2600                     }
2601                 }
2602
2603                 // Clear SSL certificate preferences.
2604                 mainWebView.clearSslPreferences();
2605
2606                 // Clear the back/forward history.
2607                 mainWebView.clearHistory();
2608
2609                 // Clear `formattedUrlString`.
2610                 formattedUrlString = null;
2611
2612                 // Clear `customHeaders`.
2613                 customHeaders.clear();
2614
2615                 // Detach all views from `mainWebViewRelativeLayout`.
2616                 mainWebViewRelativeLayout.removeAllViews();
2617
2618                 // Destroy the internal state of `mainWebView`.
2619                 mainWebView.destroy();
2620
2621                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2622                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2623                 if (clearEverything) {
2624                     try {
2625                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2626                     } catch (IOException e) {
2627                         // Do nothing if an error is thrown.
2628                     }
2629                 }
2630
2631                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2632                 if (Build.VERSION.SDK_INT >= 21) {
2633                     finishAndRemoveTask();
2634                 } else {
2635                     finish();
2636                 }
2637
2638                 // Remove the terminated program from RAM.  The status code is `0`.
2639                 System.exit(0);
2640                 break;
2641         }
2642
2643         // Close the navigation drawer.
2644         drawerLayout.closeDrawer(GravityCompat.START);
2645         return true;
2646     }
2647
2648     @Override
2649     public void onPostCreate(Bundle savedInstanceState) {
2650         super.onPostCreate(savedInstanceState);
2651
2652         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2653         drawerToggle.syncState();
2654     }
2655
2656     @Override
2657     public void onConfigurationChanged(Configuration newConfig) {
2658         super.onConfigurationChanged(newConfig);
2659
2660         // Reload the ad for the free flavor if we not in full screen mode.
2661         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2662             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2663             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2664         }
2665
2666         // `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:
2667         // https://code.google.com/p/android/issues/detail?id=20493#c8
2668         // ActivityCompat.invalidateOptionsMenu(this);
2669     }
2670
2671     @Override
2672     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2673         // Store the `HitTestResult`.
2674         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2675
2676         // Create strings.
2677         final String imageUrl;
2678         final String linkUrl;
2679
2680         // Get a handle for the `ClipboardManager`.
2681         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2682
2683         // Remove the lint errors below that `clipboardManager` might be `null`.
2684         assert clipboardManager != null;
2685
2686         switch (hitTestResult.getType()) {
2687             // `SRC_ANCHOR_TYPE` is a link.
2688             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2689                 // Get the target URL.
2690                 linkUrl = hitTestResult.getExtra();
2691
2692                 // Set the target URL as the title of the `ContextMenu`.
2693                 menu.setHeaderTitle(linkUrl);
2694
2695                 // Add a Load URL entry.
2696                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2697                     loadUrl(linkUrl);
2698                     return false;
2699                 });
2700
2701                 // Add a Copy URL entry.
2702                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2703                     // Save the link URL in a `ClipData`.
2704                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2705
2706                     // Set the `ClipData` as the clipboard's primary clip.
2707                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2708                     return false;
2709                 });
2710
2711                 // Add a Download URL entry.
2712                 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2713                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2714                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2715                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2716
2717                         // Store the variables for future use by `onRequestPermissionsResult()`.
2718                         downloadUrl = linkUrl;
2719                         downloadContentDisposition = "none";
2720                         downloadContentLength = -1;
2721
2722                         // Show a dialog if the user has previously denied the permission.
2723                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2724                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2725                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2726
2727                             // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
2728                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2729                         } else {  // Show the permission request directly.
2730                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
2731                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2732                         }
2733                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2734                         // Get a handle for the download file alert dialog.
2735                         AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2736
2737                         // Show the download file alert dialog.
2738                         downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2739                     }
2740                     return false;
2741                 });
2742
2743                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2744                 menu.add(R.string.cancel);
2745                 break;
2746
2747             case WebView.HitTestResult.EMAIL_TYPE:
2748                 // Get the target URL.
2749                 linkUrl = hitTestResult.getExtra();
2750
2751                 // Set the target URL as the title of the `ContextMenu`.
2752                 menu.setHeaderTitle(linkUrl);
2753
2754                 // Add a `Write Email` entry.
2755                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2756                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2757                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2758
2759                     // Parse the url and set it as the data for the `Intent`.
2760                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2761
2762                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2763                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2764
2765                     // Make it so.
2766                     startActivity(emailIntent);
2767                     return false;
2768                 });
2769
2770                 // Add a `Copy Email Address` entry.
2771                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2772                     // Save the email address in a `ClipData`.
2773                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2774
2775                     // Set the `ClipData` as the clipboard's primary clip.
2776                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2777                     return false;
2778                 });
2779
2780                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2781                 menu.add(R.string.cancel);
2782                 break;
2783
2784             // `IMAGE_TYPE` is an image.
2785             case WebView.HitTestResult.IMAGE_TYPE:
2786                 // Get the image URL.
2787                 imageUrl = hitTestResult.getExtra();
2788
2789                 // Set the image URL as the title of the `ContextMenu`.
2790                 menu.setHeaderTitle(imageUrl);
2791
2792                 // Add a `View Image` entry.
2793                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2794                     loadUrl(imageUrl);
2795                     return false;
2796                 });
2797
2798                 // Add a `Download Image` entry.
2799                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2800                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2801                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2802                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2803
2804                         // Store the image URL for use by `onRequestPermissionResult()`.
2805                         downloadImageUrl = imageUrl;
2806
2807                         // Show a dialog if the user has previously denied the permission.
2808                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2809                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2810                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2811
2812                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2813                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2814                         } else {  // Show the permission request directly.
2815                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2816                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2817                         }
2818                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2819                         // Get a handle for the download image alert dialog.
2820                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2821
2822                         // Show the download image alert dialog.
2823                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2824                     }
2825                     return false;
2826                 });
2827
2828                 // Add a `Copy URL` entry.
2829                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2830                     // Save the image URL in a `ClipData`.
2831                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2832
2833                     // Set the `ClipData` as the clipboard's primary clip.
2834                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
2835                     return false;
2836                 });
2837
2838                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2839                 menu.add(R.string.cancel);
2840                 break;
2841
2842
2843             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2844             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2845                 // Get the image URL.
2846                 imageUrl = hitTestResult.getExtra();
2847
2848                 // Set the image URL as the title of the `ContextMenu`.
2849                 menu.setHeaderTitle(imageUrl);
2850
2851                 // Add a `View Image` entry.
2852                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2853                     loadUrl(imageUrl);
2854                     return false;
2855                 });
2856
2857                 // Add a `Download Image` entry.
2858                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2859                     // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2860                     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2861                         // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2862
2863                         // Store the image URL for use by `onRequestPermissionResult()`.
2864                         downloadImageUrl = imageUrl;
2865
2866                         // Show a dialog if the user has previously denied the permission.
2867                         if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
2868                             // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2869                             DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2870
2871                             // Show the download location permission alert dialog.  The permission will be requested when the dialog is closed.
2872                             downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2873                         } else {  // Show the permission request directly.
2874                             // Request the permission.  The download dialog will be launched by `onRequestPermissionResult().
2875                             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2876                         }
2877                     } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2878                         // Get a handle for the download image alert dialog.
2879                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2880
2881                         // Show the download image alert dialog.
2882                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2883                     }
2884                     return false;
2885                 });
2886
2887                 // Add a `Copy URL` entry.
2888                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2889                     // Save the image URL in a `ClipData`.
2890                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2891
2892                     // Set the `ClipData` as the clipboard's primary clip.
2893                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2894                     return false;
2895                 });
2896
2897                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2898                 menu.add(R.string.cancel);
2899                 break;
2900         }
2901     }
2902
2903     @Override
2904     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2905         // Get the `EditTexts` from the `dialogFragment`.
2906         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2907         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2908
2909         // Extract the strings from the `EditTexts`.
2910         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2911         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2912
2913         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2914         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2915         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2916         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2917
2918         // Display the new bookmark below the current items in the (0 indexed) list.
2919         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2920
2921         // Create the bookmark.
2922         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2923
2924         // Update `bookmarksCursor` with the current contents of this folder.
2925         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2926
2927         // Update the `ListView`.
2928         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2929
2930         // Scroll to the new bookmark.
2931         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2932     }
2933
2934     @Override
2935     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2936         // Get handles for the views in `dialogFragment`.
2937         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2938         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2939         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2940
2941         // Get new folder name string.
2942         String folderNameString = createFolderNameEditText.getText().toString();
2943
2944         // Get the new folder icon `Bitmap`.
2945         Bitmap folderIconBitmap;
2946         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2947             // Get the default folder icon and convert it to a `Bitmap`.
2948             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2949             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2950             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2951         } else {  // Use the `WebView` favorite icon.
2952             folderIconBitmap = favoriteIconBitmap;
2953         }
2954
2955         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
2956         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2957         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2958         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2959
2960         // Move all the bookmarks down one in the display order.
2961         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2962             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2963             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2964         }
2965
2966         // Create the folder, which will be placed at the top of the `ListView`.
2967         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2968
2969         // Update `bookmarksCursor` with the current contents of this folder.
2970         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2971
2972         // Update the `ListView`.
2973         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2974
2975         // Scroll to the new folder.
2976         bookmarksListView.setSelection(0);
2977     }
2978
2979     @Override
2980     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2981         // Get the shortcut name.
2982         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2983         String shortcutNameString = shortcutNameEditText.getText().toString();
2984
2985         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
2986         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2987
2988         // Setup the shortcut intent.
2989         Intent shortcutIntent = new Intent();
2990         shortcutIntent.setAction(Intent.ACTION_VIEW);
2991         shortcutIntent.setData(Uri.parse(formattedUrlString));
2992
2993         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
2994         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2995
2996         // Add the required fields to the shortcut info builder.
2997         shortcutInfoBuilder.setIcon(favoriteIcon);
2998         shortcutInfoBuilder.setIntent(shortcutIntent);
2999         shortcutInfoBuilder.setShortLabel(shortcutNameString);
3000
3001         // Request the pin.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3002         ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3003     }
3004
3005     @Override
3006     public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3007         switch (downloadType) {
3008             case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3009                 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3010                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3011                 break;
3012
3013             case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3014                 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3015                 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3016                 break;
3017         }
3018     }
3019
3020     @Override
3021     public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3022         switch (requestCode) {
3023             case DOWNLOAD_FILE_REQUEST_CODE:
3024                 // Show the download file alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
3025                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3026
3027                 // On API 23, displaying the fragment must be delayed or the app will crash.
3028                 if (Build.VERSION.SDK_INT == 23) {
3029                     new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3030                 } else {
3031                     downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3032                 }
3033
3034                 // Reset the download variables.
3035                 downloadUrl = "";
3036                 downloadContentDisposition = "";
3037                 downloadContentLength = 0;
3038                 break;
3039
3040             case DOWNLOAD_IMAGE_REQUEST_CODE:
3041                 // Show the download image alert dialog.  When the dialog closes, the correct command will be used based on the permission status.
3042                 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3043
3044                 // On API 23, displaying the fragment must be delayed or the app will crash.
3045                 if (Build.VERSION.SDK_INT == 23) {
3046                     new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3047                 } else {
3048                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3049                 }
3050
3051                 // Reset the image URL variable.
3052                 downloadImageUrl = "";
3053                 break;
3054         }
3055     }
3056
3057     @Override
3058     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3059         // Download the image if it has an HTTP or HTTPS URI.
3060         if (imageUrl.startsWith("http")) {
3061             // Get a handle for the system `DOWNLOAD_SERVICE`.
3062             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3063
3064             // Parse `imageUrl`.
3065             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3066
3067             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
3068             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3069             if (firstPartyCookiesEnabled) {
3070                 // Get the cookies for `imageUrl`.
3071                 String cookies = cookieManager.getCookie(imageUrl);
3072
3073                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3074                 downloadRequest.addRequestHeader("Cookie", cookies);
3075             }
3076
3077             // Get the file name from the dialog fragment.
3078             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3079             String imageName = downloadImageNameEditText.getText().toString();
3080
3081             // Specify the download location.
3082             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3083                 // Download to the public download directory.
3084                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3085             } else {  // External write permission denied.
3086                 // Download to the app's external download directory.
3087                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3088             }
3089
3090             // Allow `MediaScanner` to index the download if it is a media file.
3091             downloadRequest.allowScanningByMediaScanner();
3092
3093             // Add the URL as the description for the download.
3094             downloadRequest.setDescription(imageUrl);
3095
3096             // Show the download notification after the download is completed.
3097             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3098
3099             // Remove the lint warning below that `downloadManager` might be `null`.
3100             assert downloadManager != null;
3101
3102             // Initiate the download.
3103             downloadManager.enqueue(downloadRequest);
3104         } else {  // The image is not an HTTP or HTTPS URI.
3105             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3106         }
3107     }
3108
3109     @Override
3110     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3111         // Download the file if it has an HTTP or HTTPS URI.
3112         if (downloadUrl.startsWith("http")) {
3113             // Get a handle for the system `DOWNLOAD_SERVICE`.
3114             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3115
3116             // Parse `downloadUrl`.
3117             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3118
3119             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
3120             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3121             if (firstPartyCookiesEnabled) {
3122                 // Get the cookies for `downloadUrl`.
3123                 String cookies = cookieManager.getCookie(downloadUrl);
3124
3125                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3126                 downloadRequest.addRequestHeader("Cookie", cookies);
3127             }
3128
3129             // Get the file name from the dialog fragment.
3130             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3131             String fileName = downloadFileNameEditText.getText().toString();
3132
3133             // Specify the download location.
3134             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // External write permission granted.
3135                 // Download to the public download directory.
3136                 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3137             } else {  // External write permission denied.
3138                 // Download to the app's external download directory.
3139                 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3140             }
3141
3142             // Allow `MediaScanner` to index the download if it is a media file.
3143             downloadRequest.allowScanningByMediaScanner();
3144
3145             // Add the URL as the description for the download.
3146             downloadRequest.setDescription(downloadUrl);
3147
3148             // Show the download notification after the download is completed.
3149             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3150
3151             // Remove the lint warning below that `downloadManager` might be `null`.
3152             assert downloadManager != null;
3153
3154             // Initiate the download.
3155             downloadManager.enqueue(downloadRequest);
3156         } else {  // The download is not an HTTP or HTTPS URI.
3157             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3158         }
3159     }
3160
3161     @Override
3162     public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3163         // Get handles for the views from `dialogFragment`.
3164         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3165         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3166         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3167
3168         // Store the bookmark strings.
3169         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3170         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3171
3172         // Update the bookmark.
3173         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
3174             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3175         } else {  // Update the bookmark using the `WebView` favorite icon.
3176             // Convert the favorite icon to a byte array.  `0` is for lossless compression (the only option for a PNG).
3177             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3178             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3179             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3180
3181             //  Update the bookmark and the favorite icon.
3182             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3183         }
3184
3185         // Update `bookmarksCursor` with the current contents of this folder.
3186         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3187
3188         // Update the `ListView`.
3189         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3190     }
3191
3192     @Override
3193     public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3194         // Get handles for the views from `dialogFragment`.
3195         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3196         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3197         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3198         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3199
3200         // Get the new folder name.
3201         String newFolderNameString = editFolderNameEditText.getText().toString();
3202
3203         // Check if the favorite icon has changed.
3204         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
3205             // Update the name in the database.
3206             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3207         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
3208             // Get the new folder icon `Bitmap`.
3209             Bitmap folderIconBitmap;
3210             if (defaultFolderIconRadioButton.isChecked()) {
3211                 // Get the default folder icon and convert it to a `Bitmap`.
3212                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3213                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3214                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3215             } else {  // Use the `WebView` favorite icon.
3216                 folderIconBitmap = favoriteIconBitmap;
3217             }
3218
3219             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3220             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3221             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3222             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3223
3224             // Update the folder icon in the database.
3225             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3226         } else {  // The folder icon and the name have changed.
3227             // Get the new folder icon `Bitmap`.
3228             Bitmap folderIconBitmap;
3229             if (defaultFolderIconRadioButton.isChecked()) {
3230                 // Get the default folder icon and convert it to a `Bitmap`.
3231                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3232                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3233                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3234             } else {  // Use the `WebView` favorite icon.
3235                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3236             }
3237
3238             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3239             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3240             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3241             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3242
3243             // Update the folder name and icon in the database.
3244             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3245         }
3246
3247         // Update `bookmarksCursor` with the current contents of this folder.
3248         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3249
3250         // Update the `ListView`.
3251         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3252     }
3253
3254     @Override
3255     public void onHttpAuthenticationCancel() {
3256         // Cancel the `HttpAuthHandler`.
3257         httpAuthHandler.cancel();
3258     }
3259
3260     @Override
3261     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3262         // Get handles for the `EditTexts`.
3263         EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3264         EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3265
3266         // Proceed with the HTTP authentication.
3267         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3268     }
3269
3270     public void viewSslCertificate(View view) {
3271         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3272         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3273         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3274     }
3275
3276     @Override
3277     public void onSslErrorCancel() {
3278         sslErrorHandler.cancel();
3279     }
3280
3281     @Override
3282     public void onSslErrorProceed() {
3283         sslErrorHandler.proceed();
3284     }
3285
3286     @Override
3287     public void onSslMismatchBack() {
3288         if (mainWebView.canGoBack()) {  // There is a back page in the history.
3289             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3290             formattedUrlString = "";
3291
3292             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3293             navigatingHistory = true;
3294
3295             // Go back.
3296             mainWebView.goBack();
3297         } else {  // There are no pages to go back to.
3298             // Load a blank page
3299             loadUrl("");
3300         }
3301     }
3302
3303     @Override
3304     public void onSslMismatchProceed() {
3305         // Do not check the pinned SSL certificate for this domain again until the domain changes.
3306         ignorePinnedSslCertificate = true;
3307     }
3308
3309     @Override
3310     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3311         // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3312         formattedUrlString = "";
3313
3314         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3315         navigatingHistory = true;
3316
3317         // Load the history entry.
3318         mainWebView.goBackOrForward(moveBackOrForwardSteps);
3319     }
3320
3321     @Override
3322     public void onClearHistory() {
3323         // Clear the history.
3324         mainWebView.clearHistory();
3325     }
3326
3327     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3328     @Override
3329     public void onBackPressed() {
3330         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
3331             // Close the navigation drawer.
3332             drawerLayout.closeDrawer(GravityCompat.START);
3333         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
3334             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
3335                 // close the bookmarks drawer.
3336                 drawerLayout.closeDrawer(GravityCompat.END);
3337             } else {  // A subfolder is displayed.
3338                 // Place the former parent folder in `currentFolder`.
3339                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3340
3341                 // Load the new folder.
3342                 loadBookmarksFolder();
3343             }
3344
3345         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
3346             // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3347             formattedUrlString = "";
3348
3349             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3350             navigatingHistory = true;
3351
3352             // Go back.
3353             mainWebView.goBack();
3354         } else {  // There isn't anything to do in Privacy Browser.
3355             // Pass `onBackPressed()` to the system.
3356             super.onBackPressed();
3357         }
3358     }
3359
3360     // 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.
3361     @Override
3362     public void onActivityResult(int requestCode, int resultCode, Intent data) {
3363         // File uploads only work on API >= 21.
3364         if (Build.VERSION.SDK_INT >= 21) {
3365             // Pass the file to the WebView.
3366             fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3367         }
3368     }
3369
3370     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3371         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
3372         String unformattedUrlString = urlTextBox.getText().toString().trim();
3373
3374         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
3375         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3376             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
3377             if (!unformattedUrlString.startsWith("http")) {
3378                 unformattedUrlString = "http://" + unformattedUrlString;
3379             }
3380
3381             // Initialize `unformattedUrl`.
3382             URL unformattedUrl = null;
3383
3384             // 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.
3385             try {
3386                 unformattedUrl = new URL(unformattedUrlString);
3387             } catch (MalformedURLException e) {
3388                 e.printStackTrace();
3389             }
3390
3391             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3392             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3393             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3394             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3395             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3396             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3397
3398             // Build the URI.
3399             Uri.Builder formattedUri = new Uri.Builder();
3400             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3401
3402             // Decode `formattedUri` as a `String` in `UTF-8`.
3403             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3404         } else if (unformattedUrlString.isEmpty()){  // Load a blank web site.
3405             // Load a blank string.
3406             formattedUrlString = "";
3407         } else {  // Search for the contents of the URL box.
3408             // Sanitize the search input and convert it to a search.
3409             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3410
3411             // Add the base search URL.
3412             formattedUrlString = searchURL + encodedUrlString;
3413         }
3414
3415         // 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.
3416         urlTextBox.clearFocus();
3417
3418         // Make it so.
3419         loadUrl(formattedUrlString);
3420     }
3421
3422     private void loadUrl(String url) {// Apply any custom domain settings.
3423         // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3424         formattedUrlString = url;
3425
3426         // Apply the domain settings.
3427         applyDomainSettings(url, true, false);
3428
3429         // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3430         urlIsLoading = true;
3431
3432         // Load the URL.
3433         mainWebView.loadUrl(url, customHeaders);
3434     }
3435
3436     public void findPreviousOnPage(View view) {
3437         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
3438         mainWebView.findNext(false);
3439     }
3440
3441     public void findNextOnPage(View view) {
3442         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3443         mainWebView.findNext(true);
3444     }
3445
3446     public void closeFindOnPage(View view) {
3447         // Delete the contents of `find_on_page_edittext`.
3448         findOnPageEditText.setText(null);
3449
3450         // Clear the highlighted phrases.
3451         mainWebView.clearMatches();
3452
3453         // Hide the Find on Page `RelativeLayout`.
3454         findOnPageLinearLayout.setVisibility(View.GONE);
3455
3456         // Show the URL app bar.
3457         supportAppBar.setVisibility(View.VISIBLE);
3458
3459         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
3460         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3461     }
3462
3463     private void applyAppSettings() {
3464         // Get a handle for the shared preferences.
3465         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3466
3467         // Store the values from the shared preferences in variables.
3468         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3469         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3470         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3471         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3472         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3473         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3474         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3475         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3476         proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3477         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3478         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3479         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3480         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3481
3482         // Set the homepage, search, and proxy options.
3483         if (proxyThroughOrbot) {  // Set the Tor options.
3484             // Set `torHomepageString` as `homepage`.
3485             homepage = torHomepageString;
3486
3487             // If formattedUrlString is null assign the homepage to it.
3488             if (formattedUrlString == null) {
3489                 formattedUrlString = homepage;
3490             }
3491
3492             // Set the search URL.
3493             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
3494                 searchURL = torSearchCustomURLString;
3495             } else {  // Use the string from the pre-built list.
3496                 searchURL = torSearchString;
3497             }
3498
3499             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
3500             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3501
3502             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
3503             if (darkTheme) {
3504                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3505             } else {
3506                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3507             }
3508
3509             // Display a message to the user if waiting for Orbot.
3510             if (!orbotStatus.equals("ON")) {
3511                 // Set `waitingForOrbot`.
3512                 waitingForOrbot = true;
3513
3514                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
3515                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3516             }
3517         } else {  // Set the non-Tor options.
3518             // Set `homepageString` as `homepage`.
3519             homepage = homepageString;
3520
3521             // If formattedUrlString is null assign the homepage to it.
3522             if (formattedUrlString == null) {
3523                 formattedUrlString = homepage;
3524             }
3525
3526             // Set the search URL.
3527             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
3528                 searchURL = searchCustomURLString;
3529             } else {  // Use the string from the pre-built list.
3530                 searchURL = searchString;
3531             }
3532
3533             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
3534             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3535
3536             // Set the default `appBar` background.  `this` refers to the context.
3537             if (darkTheme) {
3538                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3539             } else {
3540                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3541             }
3542
3543             // Reset `waitingForOrbot.
3544             waitingForOrbot = false;
3545         }
3546
3547         // Set Do Not Track status.
3548         if (doNotTrackEnabled) {
3549             customHeaders.put("DNT", "1");
3550         } else {
3551             customHeaders.remove("DNT");
3552         }
3553
3554         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3555         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3556             if (hideSystemBarsOnFullscreen) {  // Hide everything.
3557                 // Remove the translucent navigation setting if it is currently flagged.
3558                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3559
3560                 // Remove the translucent status bar overlay.
3561                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3562
3563                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3564                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3565
3566                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3567                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3568                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3569                  */
3570                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3571             } else {  // Hide everything except the status and navigation bars.
3572                 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3573                 rootCoordinatorLayout.setSystemUiVisibility(0);
3574
3575                 // Add the translucent status flag if it is unset.
3576                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3577
3578                 if (translucentNavigationBarOnFullscreen) {
3579                     // Set the navigation bar to be translucent.
3580                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3581                 } else {
3582                     // Set the navigation bar to be black.
3583                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3584                 }
3585             }
3586         } else {  // Privacy Browser is not in full screen browsing mode.
3587             // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3588             inFullScreenBrowsingMode = false;
3589
3590             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3591             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3592                 appBar.show();
3593             }
3594
3595             // Show the `BannerAd` in the free flavor.
3596             if (BuildConfig.FLAVOR.contentEquals("free")) {
3597                 // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3598                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3599             }
3600
3601             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3602             rootCoordinatorLayout.setSystemUiVisibility(0);
3603
3604             // Remove the translucent navigation bar flag if it is set.
3605             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3606
3607             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3608             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3609
3610             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3611             rootCoordinatorLayout.setFitsSystemWindows(true);
3612         }
3613     }
3614
3615     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3616     // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3617     @SuppressWarnings("deprecation")
3618     private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3619         // Parse the URL into a URI.
3620         Uri uri = Uri.parse(url);
3621
3622         // Extract the domain from `uri`.
3623         String hostName = uri.getHost();
3624
3625         // Initialize `loadingNewDomainName`.
3626         boolean loadingNewDomainName;
3627
3628         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3629         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3630         //noinspection SimplifiableIfStatement
3631         if ((hostName == null) || (currentDomainName == null)) {
3632             loadingNewDomainName = true;
3633         } else {  // Determine if `hostName` equals `currentDomainName`.
3634             loadingNewDomainName = !hostName.equals(currentDomainName);
3635         }
3636
3637         // Strings don't like to be null.
3638         if (hostName == null) {
3639             hostName = "";
3640         }
3641
3642         // 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.
3643         if (loadingNewDomainName) {
3644             // Set the new `hostname` as the `currentDomainName`.
3645             currentDomainName = hostName;
3646
3647             // Reset `ignorePinnedSslCertificate`.
3648             ignorePinnedSslCertificate = false;
3649
3650             // Reset the favorite icon if specified.
3651             if (resetFavoriteIcon) {
3652                 favoriteIconBitmap = favoriteIconDefaultBitmap;
3653                 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3654             }
3655
3656             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3657             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3658             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3659
3660             // Get a full cursor from `domainsDatabaseHelper`.
3661             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3662
3663             // Initialize `domainSettingsSet`.
3664             Set<String> domainSettingsSet = new HashSet<>();
3665
3666             // Get the domain name column index.
3667             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3668
3669             // Populate `domainSettingsSet`.
3670             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3671                 // Move `domainsCursor` to the current row.
3672                 domainNameCursor.moveToPosition(i);
3673
3674                 // Store the domain name in `domainSettingsSet`.
3675                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3676             }
3677
3678             // Close `domainNameCursor.
3679             domainNameCursor.close();
3680
3681             // Initialize variables to track if domain settings will be applied and, if so, under which name.
3682             domainSettingsApplied = false;
3683             String domainNameInDatabase = null;
3684
3685             // Check the hostname.
3686             if (domainSettingsSet.contains(hostName)) {
3687                 domainSettingsApplied = true;
3688                 domainNameInDatabase = hostName;
3689             }
3690
3691             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3692             while (!domainSettingsApplied && hostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3693                 if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
3694                     // Apply the domain settings.
3695                     domainSettingsApplied = true;
3696
3697                     // Store the applied domain names as it appears in the database.
3698                     domainNameInDatabase = "*." + hostName;
3699                 }
3700
3701                 // Strip out the lowest subdomain of of the host name.
3702                 hostName = hostName.substring(hostName.indexOf(".") + 1);
3703             }
3704
3705
3706             // Get a handle for the shared preference.
3707             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3708
3709             // Store the general preference information.
3710             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3711             String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3712             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3713             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3714             nightMode = sharedPreferences.getBoolean("night_mode", false);
3715
3716             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
3717                 // Get a cursor for the current host and move it to the first position.
3718                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3719                 currentHostDomainSettingsCursor.moveToFirst();
3720
3721                 // Get the settings from the cursor.
3722                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3723                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3724                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3725                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3726                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3727                 // Form data can be removed once the minimum API >= 26.
3728                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3729                 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3730                 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3731                 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3732                 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3733                 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3734                 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3735                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3736                 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3737                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3738                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3739                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3740                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3741                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3742                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3743                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3744                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3745                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3746
3747                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3748                 switch (nightModeInt) {
3749                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3750                         nightMode = true;
3751                         break;
3752
3753                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3754                         nightMode = false;
3755                         break;
3756                 }
3757
3758                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3759                 if (nightMode) {
3760                     javaScriptEnabled = true;
3761                 }
3762
3763                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3764                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3765                     pinnedDomainSslStartDate = null;
3766                 } else {
3767                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3768                 }
3769
3770                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3771                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3772                     pinnedDomainSslEndDate = null;
3773                 } else {
3774                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3775                 }
3776
3777                 // Close `currentHostDomainSettingsCursor`.
3778                 currentHostDomainSettingsCursor.close();
3779
3780                 // Apply the domain settings.
3781                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3782                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3783                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3784
3785                 // Apply the form data setting if the API < 26.
3786                 if (Build.VERSION.SDK_INT < 26) {
3787                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3788                 }
3789
3790                 // Apply the font size.
3791                 if (fontSize == 0) {  // Apply the default font size.
3792                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3793                 } else {  // Apply the specified font size.
3794                     mainWebView.getSettings().setTextZoom(fontSize);
3795                 }
3796
3797                 // Set third-party cookies status if API >= 21.
3798                 if (Build.VERSION.SDK_INT >= 21) {
3799                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3800                 }
3801
3802                 // 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.
3803                 // <https://redmine.stoutner.com/issues/160>
3804                 if (!urlIsLoading) {
3805                     // Set the user agent.
3806                     if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3807                         // Get the array position of the default user agent name.
3808                         int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3809
3810                         // Set the user agent according to the system default.
3811                         switch (defaultUserAgentArrayPosition) {
3812                             case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3813                                 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3814                                 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3815                                 break;
3816
3817                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3818                                 // Set the user agent to `""`, which uses the default value.
3819                                 mainWebView.getSettings().setUserAgentString("");
3820                                 break;
3821
3822                             case SETTINGS_CUSTOM_USER_AGENT:
3823                                 // Set the custom user agent.
3824                                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3825                                 break;
3826
3827                             default:
3828                                 // Get the user agent string from the user agent data array
3829                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3830                         }
3831                     } else {  // Set the user agent according to the stored name.
3832                         // Get the array position of the user agent name.
3833                         int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3834
3835                         switch (userAgentArrayPosition) {
3836                             case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3837                                 mainWebView.getSettings().setUserAgentString(userAgentName);
3838                                 break;
3839
3840                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3841                                 // Set the user agent to `""`, which uses the default value.
3842                                 mainWebView.getSettings().setUserAgentString("");
3843                                 break;
3844
3845                             default:
3846                                 // Get the user agent string from the user agent data array.
3847                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3848                         }
3849                     }
3850
3851                     // Set swipe to refresh.
3852                     switch (swipeToRefreshInt) {
3853                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3854                             // Set swipe to refresh according to the default.
3855                             swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3856                             break;
3857
3858                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3859                             // Enable swipe to refresh.
3860                             swipeRefreshLayout.setEnabled(true);
3861                             break;
3862
3863                         case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3864                             // Disable swipe to refresh.
3865                             swipeRefreshLayout.setEnabled(false);
3866                     }
3867
3868                     // Store the applied user agent string, which is used in the View Source activity.
3869                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3870                 }
3871
3872                 // 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.
3873                 if (darkTheme) {
3874                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3875                 } else {
3876                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3877                 }
3878             } else {  // The new URL does not have custom domain settings.  Load the defaults.
3879                 // Store the values from `sharedPreferences` in variables.
3880                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3881                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3882                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3883                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3884                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);  // Form data can be removed once the minimum API >= 26.
3885                 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3886                 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3887                 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3888                 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3889                 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3890
3891                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3892                 if (nightMode) {
3893                     javaScriptEnabled = true;
3894                 }
3895
3896                 // Apply the default settings.
3897                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3898                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3899                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3900                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3901                 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3902
3903                 // Apply the form data setting if the API < 26.
3904                 if (Build.VERSION.SDK_INT < 26) {
3905                     mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3906                 }
3907
3908                 // Reset the pinned SSL certificate information.
3909                 domainSettingsDatabaseId = -1;
3910                 pinnedDomainSslCertificate = false;
3911                 pinnedDomainSslIssuedToCNameString = "";
3912                 pinnedDomainSslIssuedToONameString = "";
3913                 pinnedDomainSslIssuedToUNameString = "";
3914                 pinnedDomainSslIssuedByCNameString = "";
3915                 pinnedDomainSslIssuedByONameString = "";
3916                 pinnedDomainSslIssuedByUNameString = "";
3917                 pinnedDomainSslStartDate = null;
3918                 pinnedDomainSslEndDate = null;
3919
3920                 // Set third-party cookies status if API >= 21.
3921                 if (Build.VERSION.SDK_INT >= 21) {
3922                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3923                 }
3924
3925                 // 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.
3926                 // <https://redmine.stoutner.com/issues/160>
3927                 if (!urlIsLoading) {
3928                     // Get the array position of the user agent name.
3929                     int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3930
3931                     // Set the user agent.
3932                     switch (userAgentArrayPosition) {
3933                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3934                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3935                             mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3936                             break;
3937
3938                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3939                             // Set the user agent to `""`, which uses the default value.
3940                             mainWebView.getSettings().setUserAgentString("");
3941                             break;
3942
3943                         case SETTINGS_CUSTOM_USER_AGENT:
3944                             // Set the custom user agent.
3945                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3946                             break;
3947
3948                         default:
3949                             // Get the user agent string from the user agent data array
3950                             mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3951                     }
3952
3953                     // Store the applied user agent string, which is used in the View Source activity.
3954                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3955                 }
3956
3957                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3958                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3959             }
3960
3961             // Close `domainsDatabaseHelper`.
3962             domainsDatabaseHelper.close();
3963
3964             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
3965             onTheFlyDisplayImagesSet = false;
3966             setDisplayWebpageImages();
3967
3968             // Update the privacy icons, but only if `mainMenu` has already been populated.
3969             if (mainMenu != null) {
3970                 updatePrivacyIcons(true);
3971             }
3972         }
3973
3974         // Reload the website if returning from the Domains activity.
3975         if (reloadWebsite) {
3976             mainWebView.reload();
3977         }
3978     }
3979
3980     private void setDisplayWebpageImages() {
3981         if (!onTheFlyDisplayImagesSet) {
3982             if (domainSettingsApplied) {  // Custom domain settings are applied.
3983                 switch (displayWebpageImagesInt) {
3984                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3985                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3986                         break;
3987
3988                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3989                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
3990                         break;
3991
3992                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3993                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
3994                         break;
3995                 }
3996             } else {  // Default settings are applied.
3997                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3998             }
3999         }
4000     }
4001
4002     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4003         // Get handles for the menu items.
4004         MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4005         MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4006         MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4007         MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4008
4009         // Update the privacy icon.
4010         if (javaScriptEnabled) {  // JavaScript is enabled.
4011             privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4012         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
4013             privacyMenuItem.setIcon(R.drawable.warning);
4014         } else {  // All the dangerous features are disabled.
4015             privacyMenuItem.setIcon(R.drawable.privacy_mode);
4016         }
4017
4018         // Update the first-party cookies icon.
4019         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
4020             firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4021         } else {  // First-party cookies are disabled.
4022             if (darkTheme) {
4023                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4024             } else {
4025                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4026             }
4027         }
4028
4029         // Update the DOM storage icon.
4030         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
4031             domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4032         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
4033             if (darkTheme) {
4034                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4035             } else {
4036                 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4037             }
4038         } else {  // JavaScript is disabled, so DOM storage is ghosted.
4039             if (darkTheme) {
4040                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4041             } else {
4042                 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4043             }
4044         }
4045
4046         // Update the refresh icon.
4047         if (darkTheme) {
4048             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4049         } else {
4050             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4051         }
4052
4053         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4054         if (runInvalidateOptionsMenu) {
4055             invalidateOptionsMenu();
4056         }
4057     }
4058
4059     private void highlightUrlText() {
4060         String urlString = urlTextBox.getText().toString();
4061
4062         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4063             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4064         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4065             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4066         }
4067
4068         // Get the index of the `/` immediately after the domain name.
4069         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4070
4071         // De-emphasize the text after the domain name.
4072         if (endOfDomainName > 0) {
4073             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4074         }
4075     }
4076
4077     private void loadBookmarksFolder() {
4078         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4079         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4080
4081         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
4082         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4083             @Override
4084             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4085                 // Inflate the individual item layout.  `false` does not attach it to the root.
4086                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4087             }
4088
4089             @Override
4090             public void bindView(View view, Context context, Cursor cursor) {
4091                 // Get handles for the views.
4092                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4093                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4094
4095                 // Get the favorite icon byte array from the cursor.
4096                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4097
4098                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4099                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4100
4101                 // Display the bitmap in `bookmarkFavoriteIcon`.
4102                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4103
4104                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4105                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4106                 bookmarkNameTextView.setText(bookmarkNameString);
4107
4108                 // Make the font bold for folders.
4109                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4110                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4111                 } else {  // Reset the font to default for normal bookmarks.
4112                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4113                 }
4114             }
4115         };
4116
4117         // Populate the `ListView` with the adapter.
4118         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4119
4120         // Set the bookmarks drawer title.
4121         if (currentBookmarksFolder.isEmpty()) {
4122             bookmarksTitleTextView.setText(R.string.bookmarks);
4123         } else {
4124             bookmarksTitleTextView.setText(currentBookmarksFolder);
4125         }
4126     }
4127 }