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