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