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