]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Get consent for ads to comply with the GDPR. https://redmine.stoutner.com/issues/278
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.ActivityNotFoundException;
29 import android.content.BroadcastReceiver;
30 import android.content.ClipData;
31 import android.content.ClipboardManager;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageManager;
37 import android.content.res.Configuration;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Typeface;
42 import android.graphics.drawable.BitmapDrawable;
43 import android.graphics.drawable.Drawable;
44 import android.net.Uri;
45 import android.net.http.SslCertificate;
46 import android.net.http.SslError;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.Environment;
50 import android.os.Handler;
51 import android.preference.PreferenceManager;
52 import android.print.PrintDocumentAdapter;
53 import android.print.PrintManager;
54 import android.support.annotation.NonNull;
55 import android.support.design.widget.CoordinatorLayout;
56 import android.support.design.widget.FloatingActionButton;
57 import android.support.design.widget.NavigationView;
58 import android.support.design.widget.Snackbar;
59 import android.support.v4.app.ActivityCompat;
60 import android.support.v4.content.ContextCompat;
61 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
62 import android.support.v4.content.pm.ShortcutInfoCompat;
63 import android.support.v4.content.pm.ShortcutManagerCompat;
64 import android.support.v4.graphics.drawable.IconCompat;
65 import android.support.v4.view.GravityCompat;
66 import android.support.v4.widget.DrawerLayout;
67 import android.support.v4.widget.SwipeRefreshLayout;
68 import android.support.v7.app.ActionBar;
69 import android.support.v7.app.ActionBarDrawerToggle;
70 import android.support.v7.app.AppCompatActivity;
71 import android.support.v7.app.AppCompatDialogFragment;
72 import android.support.v7.widget.Toolbar;
73 import android.text.Editable;
74 import android.text.Spanned;
75 import android.text.TextWatcher;
76 import android.text.style.ForegroundColorSpan;
77 import android.util.Patterns;
78 import android.view.ContextMenu;
79 import android.view.GestureDetector;
80 import android.view.KeyEvent;
81 import android.view.Menu;
82 import android.view.MenuItem;
83 import android.view.MotionEvent;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.WindowManager;
87 import android.view.inputmethod.InputMethodManager;
88 import android.webkit.CookieManager;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.SslErrorHandler;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebBackForwardList;
93 import android.webkit.WebChromeClient;
94 import android.webkit.WebResourceResponse;
95 import android.webkit.WebStorage;
96 import android.webkit.WebView;
97 import android.webkit.WebViewClient;
98 import android.webkit.WebViewDatabase;
99 import android.widget.ArrayAdapter;
100 import android.widget.CursorAdapter;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.ImageView;
104 import android.widget.LinearLayout;
105 import android.widget.ListView;
106 import android.widget.ProgressBar;
107 import android.widget.RadioButton;
108 import android.widget.RelativeLayout;
109 import android.widget.TextView;
110
111 import com.stoutner.privacybrowser.BuildConfig;
112 import com.stoutner.privacybrowser.R;
113 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
122 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
123 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
124 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
125 import com.stoutner.privacybrowser.helpers.AdHelper;
126 import com.stoutner.privacybrowser.helpers.BlockListHelper;
127 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
128 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
130 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
131 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
132
133 import java.io.ByteArrayInputStream;
134 import java.io.ByteArrayOutputStream;
135 import java.io.File;
136 import java.io.IOException;
137 import java.io.UnsupportedEncodingException;
138 import java.net.MalformedURLException;
139 import java.net.URL;
140 import java.net.URLDecoder;
141 import java.net.URLEncoder;
142 import java.util.ArrayList;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map;
148 import java.util.Set;
149
150 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
151 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
152         CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
153         DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
154         HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
155         SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
156
157     // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
158     // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
159     // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
160     //  and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
161     public static boolean darkTheme;
162
163     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
164     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
165     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
166     public static Bitmap favoriteIconBitmap;
167
168     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
169     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
170     public static String formattedUrlString;
171
172     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
173     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
174     public static SslCertificate sslCertificate;
175
176     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`.
177     public static String orbotStatus;
178
179     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
180     public static String webViewTitle;
181
182     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
183     public static String appliedUserAgentString;
184
185     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
186     public static boolean reloadOnRestart;
187
188     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`.  It is also used in `onRestart()`.
189     public static boolean loadUrlOnRestart;
190
191     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
192     public static boolean restartFromBookmarksActivity;
193
194     // The block list versions are public static so they can be accessed from `AboutTabFragment`.  They are also used in `onCreate()`.
195     public static String easyListVersion;
196     public static String easyPrivacyVersion;
197     public static String fanboyAnnoyanceVersion;
198     public static String fanboySocialVersion;
199
200     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
201     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
202     public static String currentBookmarksFolder;
203
204     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
205     public static int domainSettingsDatabaseId;
206
207     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
208     public static String pinnedDomainSslIssuedToCNameString;
209     public static String pinnedDomainSslIssuedToONameString;
210     public static String pinnedDomainSslIssuedToUNameString;
211     public static String pinnedDomainSslIssuedByCNameString;
212     public static String pinnedDomainSslIssuedByONameString;
213     public static String pinnedDomainSslIssuedByUNameString;
214     public static Date pinnedDomainSslStartDate;
215     public static Date pinnedDomainSslEndDate;
216
217     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
218     public final static int UNRECOGNIZED_USER_AGENT = -1;
219     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
220     public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
221     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
222     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
223     public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
224
225
226     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
227     private ActionBar appBar;
228
229     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
230     private boolean navigatingHistory;
231
232     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
233     private Bitmap favoriteIconDefaultBitmap;
234
235     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
236     private DrawerLayout drawerLayout;
237
238     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
239     private CoordinatorLayout rootCoordinatorLayout;
240
241     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
242     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
243     private WebView mainWebView;
244
245     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
246     private FrameLayout fullScreenVideoFrameLayout;
247
248     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
249     private SwipeRefreshLayout swipeRefreshLayout;
250
251     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
252     private RelativeLayout urlAppBarRelativeLayout;
253
254     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
255     private ImageView favoriteIconImageView;
256
257     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
258     private CookieManager cookieManager;
259
260     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
261     private final Map<String, String> customHeaders = new HashMap<>();
262
263     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
264     private boolean javaScriptEnabled;
265
266     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
267     private boolean firstPartyCookiesEnabled;
268
269     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
270     private boolean thirdPartyCookiesEnabled;
271
272     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
273     private boolean domStorageEnabled;
274
275     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
276     private boolean saveFormDataEnabled;
277
278     // `nightMode` is used in `onCreate()` and  `applyDomainSettings()`.
279     private boolean nightMode;
280
281     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
282     private boolean swipeToRefreshEnabled;
283
284     // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
285     private boolean displayWebpageImagesBoolean;
286
287     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
288     private String homepage;
289
290     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
291     private String searchURL;
292
293     // The block list variables are used in `onCreate()` and `applyAppSettings()`.
294     private boolean easyListEnabled;
295     private boolean easyPrivacyEnabled;
296     private boolean fanboysAnnoyanceListEnabled;
297     private boolean fanboysSocialBlockingListEnabled;
298
299     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
300     private Runtime privacyBrowserRuntime;
301
302     // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
303     private boolean proxyThroughOrbot;
304
305     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
306     private boolean incognitoModeEnabled;
307
308     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
309     private boolean fullScreenBrowsingModeEnabled;
310
311     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
312     private boolean inFullScreenBrowsingMode;
313
314     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
315     private boolean hideSystemBarsOnFullscreen;
316
317     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
318     private boolean translucentNavigationBarOnFullscreen;
319
320     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
321     private boolean reapplyDomainSettingsOnRestart;
322
323     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
324     private boolean reapplyAppSettingsOnRestart;
325
326     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
327     private String currentDomainName;
328
329     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
330     private boolean ignorePinnedSslCertificate;
331
332     // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
333     private boolean waitingForOrbot;
334
335     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
336     private boolean domainSettingsApplied;
337
338     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
339     private int displayWebpageImagesInt;
340
341     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
342     private boolean onTheFlyDisplayImagesSet;
343
344     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
345     private String waitingForOrbotHTMLString;
346
347     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
348     private String privateDataDirectoryString;
349
350     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
351     private LinearLayout findOnPageLinearLayout;
352
353     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
354     private EditText findOnPageEditText;
355
356     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
357     private Menu mainMenu;
358
359     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
360     private ActionBarDrawerToggle drawerToggle;
361
362     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
363     private Toolbar supportAppBar;
364
365     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
366     private EditText urlTextBox;
367
368     // The color spans are used in `onCreate()` and `highlightUrlText()`.
369     private ForegroundColorSpan redColorSpan;
370     private ForegroundColorSpan initialGrayColorSpan;
371     private ForegroundColorSpan finalGrayColorSpan;
372
373     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
374     private SslErrorHandler sslErrorHandler;
375
376     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
377     private static HttpAuthHandler httpAuthHandler;
378
379     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
380     private InputMethodManager inputMethodManager;
381
382     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
383     private RelativeLayout mainWebViewRelativeLayout;
384
385     // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
386     private boolean urlIsLoading;
387
388     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
389     private boolean pinnedDomainSslCertificate;
390
391     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
392     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
393
394     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
395     private ListView bookmarksListView;
396
397     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
398     private TextView bookmarksTitleTextView;
399
400     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
401     private Cursor bookmarksCursor;
402
403     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
404     private CursorAdapter bookmarksCursorAdapter;
405
406     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
407     private String oldFolderNameString;
408
409     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
410     private ValueCallback<Uri[]> fileChooserCallback;
411
412     // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
413     private String downloadUrl;
414     private String downloadContentDisposition;
415     private long downloadContentLength;
416
417     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
418     private String downloadImageUrl;
419
420     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
421     private ArrayAdapter<CharSequence> userAgentNamesArray;
422     private String[] userAgentDataArray;
423
424     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
425     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
426     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
427
428     @Override
429     // 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.
430     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
431     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
432     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
433     @SuppressWarnings("deprecation")
434     protected void onCreate(Bundle savedInstanceState) {
435         // Get a handle for `sharedPreferences`.  `this` references the current context.
436         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
437
438         // Get the theme preference.
439         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
440
441         // Set the activity theme.
442         if (darkTheme) {
443             setTheme(R.style.PrivacyBrowserDark);
444         } else {
445             setTheme(R.style.PrivacyBrowserLight);
446         }
447
448         // Run the default commands.
449         super.onCreate(savedInstanceState);
450
451         // Set the content view.
452         setContentView(R.layout.main_drawerlayout);
453
454         // Get a handle for `inputMethodManager`.
455         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
456
457         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
458         supportAppBar = findViewById(R.id.app_bar);
459         setSupportActionBar(supportAppBar);
460         appBar = getSupportActionBar();
461
462         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
463         assert appBar != null;
464
465         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
466         appBar.setCustomView(R.layout.url_app_bar);
467         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
468
469         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
470         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
471         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
472         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
473
474         // Get a handle for `urlTextBox`.
475         urlTextBox = findViewById(R.id.url_edittext);
476
477         // Remove the formatting from `urlTextBar` when the user is editing the text.
478         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
479             if (hasFocus) {  // The user is editing `urlTextBox`.
480                 // Remove the highlighting.
481                 urlTextBox.getText().removeSpan(redColorSpan);
482                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
483                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
484             } else {  // The user has stopped editing `urlTextBox`.
485                 // Reapply the highlighting.
486                 highlightUrlText();
487             }
488         });
489
490         // Set the go button on the keyboard to load the URL in `urlTextBox`.
491         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
492             // If the event is a key-down event on the `enter` button, load the URL.
493             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
494                 // Load the URL into the mainWebView and consume the event.
495                 try {
496                     loadUrlFromTextBox();
497                 } catch (UnsupportedEncodingException e) {
498                     e.printStackTrace();
499                 }
500                 // If the enter key was pressed, consume the event.
501                 return true;
502             } else {
503                 // If any other key was pressed, do not consume the event.
504                 return false;
505             }
506         });
507
508         // Set `waitingForOrbotHTMLString`.
509         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
510
511         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
512         currentDomainName = "";
513         orbotStatus = "unknown";
514         waitingForOrbot = false;
515
516         // Create an Orbot status `BroadcastReceiver`.
517         BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
518             @Override
519             public void onReceive(Context context, Intent intent) {
520                 // Store the content of the status message in `orbotStatus`.
521                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
522
523                 // If we are waiting on Orbot, load the website now that Orbot is connected.
524                 if (orbotStatus.equals("ON") && waitingForOrbot) {
525                     // Reset `waitingForOrbot`.
526                     waitingForOrbot = false;
527
528                     // Load `formattedUrlString
529                     loadUrl(formattedUrlString);
530                 }
531             }
532         };
533
534         // Register `orbotStatusBroadcastReceiver` on `this` context.
535         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
536
537         // Get handles for views that need to be accessed.
538         drawerLayout = findViewById(R.id.drawerlayout);
539         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
540         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
541         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
542         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
543         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
544         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
545         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
546         mainWebView = findViewById(R.id.main_webview);
547         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
548         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
549         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
550         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
551         favoriteIconImageView = findViewById(R.id.favorite_icon);
552
553         // 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.
554         if (darkTheme) {
555             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
556             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
557             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
558             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
559         } else {
560             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
561             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
562             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
563             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
564         }
565
566         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
567         launchBookmarksActivityFab.setOnClickListener(v -> {
568             // Create an intent to launch the bookmarks activity.
569             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
570
571             // Include the current folder with the `Intent`.
572             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
573
574             // Make it so.
575             startActivity(bookmarksIntent);
576         });
577
578         // Set the create new bookmark folder FAB to display an alert dialog.
579         createBookmarkFolderFab.setOnClickListener(v -> {
580             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
581             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
582             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
583         });
584
585         // Set the create new bookmark FAB to display an alert dialog.
586         createBookmarkFab.setOnClickListener(view -> {
587             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
588             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
589             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
590         });
591
592         // Create a double-tap listener to toggle full-screen mode.
593         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
594             // Override `onDoubleTap()`.  All other events are handled using the default settings.
595             @Override
596             public boolean onDoubleTap(MotionEvent event) {
597                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
598                     // Toggle `inFullScreenBrowsingMode`.
599                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
600
601                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
602                         // Hide the `appBar`.
603                         appBar.hide();
604
605                         // Hide the banner ad in the free flavor.
606                         if (BuildConfig.FLAVOR.contentEquals("free")) {
607                             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
608                             AdHelper.hideAd(findViewById(R.id.adview));
609                         }
610
611                         // Modify the system bars.
612                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
613                             // Remove the translucent overlays.
614                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
615
616                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
617                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
618
619                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
620                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
621                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
622                              */
623                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
624
625                             // Set `rootCoordinatorLayout` to fill the whole screen.
626                             rootCoordinatorLayout.setFitsSystemWindows(false);
627                         } else {  // Hide everything except the status and navigation bars.
628                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
629                             rootCoordinatorLayout.setFitsSystemWindows(false);
630
631                             // 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.
632                             if (translucentNavigationBarOnFullscreen) {
633                                 // Set the navigation bar to be translucent.
634                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
635                             }
636                         }
637                     } else {  // Switch to normal viewing mode.
638                         // Show the `appBar`.
639                         appBar.show();
640
641                         // Show the `BannerAd` in the free flavor.
642                         if (BuildConfig.FLAVOR.contentEquals("free")) {
643                             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
644                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
645                         }
646
647                         // Remove the translucent navigation bar flag if it is set.
648                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
649
650                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
651                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
652
653                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
654                         rootCoordinatorLayout.setSystemUiVisibility(0);
655
656                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
657                         rootCoordinatorLayout.setFitsSystemWindows(true);
658                     }
659
660                     // Consume the double-tap.
661                     return true;
662                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
663                     return false;
664                 }
665             }
666         });
667
668         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
669         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
670             // Call `performClick()` on the view, which is required for accessibility.
671             v.performClick();
672
673             // Send the `event` to `gestureDetector`.
674             return gestureDetector.onTouchEvent(event);
675         });
676
677         // Update `findOnPageCountTextView`.
678         mainWebView.setFindListener(new WebView.FindListener() {
679             // Get a handle for `findOnPageCountTextView`.
680             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
681
682             @Override
683             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
684                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
685                     // Set `findOnPageCountTextView` to `0/0`.
686                     findOnPageCountTextView.setText(R.string.zero_of_zero);
687                 } else if (isDoneCounting) {  // There are matches.
688                     // `activeMatchOrdinal` is zero-based.
689                     int activeMatch = activeMatchOrdinal + 1;
690
691                     // Build the match string.
692                     String matchString = activeMatch + "/" + numberOfMatches;
693
694                     // Set `findOnPageCountTextView`.
695                     findOnPageCountTextView.setText(matchString);
696                 }
697             }
698         });
699
700         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
701         findOnPageEditText.addTextChangedListener(new TextWatcher() {
702             @Override
703             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
704                 // Do nothing.
705             }
706
707             @Override
708             public void onTextChanged(CharSequence s, int start, int before, int count) {
709                 // Do nothing.
710             }
711
712             @Override
713             public void afterTextChanged(Editable s) {
714                 // Search for the text in `mainWebView`.
715                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
716             }
717         });
718
719         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
720         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
721             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
722                 // Hide the soft keyboard.  `0` indicates no additional flags.
723                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
724
725                 // Consume the event.
726                 return true;
727             } else {  // A different key was pressed.
728                 // Do not consume the event.
729                 return false;
730             }
731         });
732
733         // Implement swipe to refresh
734         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
735         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
736         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
737
738         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
739         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
740         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
741
742         // Listen for touches on the navigation menu.
743         final NavigationView navigationView = findViewById(R.id.navigationview);
744         navigationView.setNavigationItemSelectedListener(this);
745
746         // 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.
747         final Menu navigationMenu = navigationView.getMenu();
748         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
749         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
750         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
751
752         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
753         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
754         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
755
756         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
757         currentBookmarksFolder = "";
758
759         // Load the home folder, which is `""` in the database.
760         loadBookmarksFolder();
761
762         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
763             // Convert the id from long to int to match the format of the bookmarks database.
764             int databaseID = (int) id;
765
766             // Get the bookmark cursor for this ID and move it to the first row.
767             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
768             bookmarkCursor.moveToFirst();
769
770             // Act upon the bookmark according to the type.
771             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
772                 // Store the new folder name in `currentBookmarksFolder`.
773                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
774
775                 // Load the new folder.
776                 loadBookmarksFolder();
777             } else {  // The selected bookmark is not a folder.
778                 // Load the bookmark URL.
779                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
780
781                 // Close the bookmarks drawer.
782                 drawerLayout.closeDrawer(GravityCompat.END);
783             }
784
785             // Close the `Cursor`.
786             bookmarkCursor.close();
787         });
788
789         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
790             // Convert the database ID from `long` to `int`.
791             int databaseId = (int) id;
792
793             // Find out if the selected bookmark is a folder.
794             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
795
796             if (isFolder) {
797                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
798                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
799
800                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
801                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
802                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
803             } else {
804                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
805                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
806                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
807             }
808
809             // Consume the event.
810             return true;
811         });
812
813         // The `DrawerListener` allows us to update the Navigation Menu.
814         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
815             @Override
816             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
817             }
818
819             @Override
820             public void onDrawerOpened(@NonNull View drawerView) {
821             }
822
823             @Override
824             public void onDrawerClosed(@NonNull View drawerView) {
825             }
826
827             @Override
828             public void onDrawerStateChanged(int newState) {
829                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // The drawer is opening or closing.
830                     // Update the `Back`, `Forward`, and `History` menu items.
831                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
832                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
833                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
834
835                     // Hide the keyboard (if displayed) so we can see the navigation menu.  `0` indicates no additional flags.
836                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
837
838                     // Clear the focus from `urlTextBox` if it has it.
839                     urlTextBox.clearFocus();
840                 }
841             }
842         });
843
844         // drawerToggle creates the hamburger icon at the start of the AppBar.
845         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
846
847         // Get a handle for the progress bar.
848         final ProgressBar progressBar = findViewById(R.id.progress_bar);
849
850         mainWebView.setWebChromeClient(new WebChromeClient() {
851             // Update the progress bar when a page is loading.
852             @Override
853             public void onProgressChanged(WebView view, int progress) {
854                 // Inject the night mode CSS if night mode is enabled.
855                 if (nightMode) {
856                     // `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
857                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
858                     // `border: none` removes all borders, which can also be used to underline text.
859                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
860                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
861                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
862                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
863                                 // Initialize a `Handler` to display `mainWebView`.
864                                 Handler displayWebViewHandler = new Handler();
865
866                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
867                                 Runnable displayWebViewRunnable = () -> {
868                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
869                                     if (progressBar.getVisibility() == View.GONE) {
870                                         mainWebView.setVisibility(View.VISIBLE);
871                                     }
872                                 };
873
874                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
875                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
876                             });
877                 }
878
879                 // Update the progress bar.
880                 progressBar.setProgress(progress);
881
882                 // Set the visibility of the progress bar.
883                 if (progress < 100) {
884                     // Show the progress bar.
885                     progressBar.setVisibility(View.VISIBLE);
886                 } else {
887                     // Hide the progress bar.
888                     progressBar.setVisibility(View.GONE);
889
890                     // Display `mainWebView` if night mode is disabled.
891                     // 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
892                     // currently enabled.
893                     if (!nightMode) {
894                         mainWebView.setVisibility(View.VISIBLE);
895                     }
896
897                     //Stop the `SwipeToRefresh` indicator if it is running
898                     swipeRefreshLayout.setRefreshing(false);
899                 }
900             }
901
902             // Set the favorite icon when it changes.
903             @Override
904             public void onReceivedIcon(WebView view, Bitmap icon) {
905                 // Only update the favorite icon if the website has finished loading.
906                 if (progressBar.getVisibility() == View.GONE) {
907                     // Save a copy of the favorite icon.
908                     favoriteIconBitmap = icon;
909
910                     // Place the favorite icon in the appBar.
911                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
912                 }
913             }
914
915             // Save a copy of the title when it changes.
916             @Override
917             public void onReceivedTitle(WebView view, String title) {
918                 // Save a copy of the title.
919                 webViewTitle = title;
920             }
921
922             // Enter full screen video.
923             @Override
924             public void onShowCustomView(View view, CustomViewCallback callback) {
925                 // Pause the ad if this is the free flavor.
926                 if (BuildConfig.FLAVOR.contentEquals("free")) {
927                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
928                     AdHelper.pauseAd(findViewById(R.id.adview));
929                 }
930
931                 // Remove the translucent overlays.
932                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
933
934                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
935                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
936
937                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
938                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
939                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
940                  */
941                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
942
943                 // Set `rootCoordinatorLayout` to fill the entire screen.
944                 rootCoordinatorLayout.setFitsSystemWindows(false);
945
946                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
947                 fullScreenVideoFrameLayout.addView(view);
948                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
949             }
950
951             // Exit full screen video.
952             @Override
953             public void onHideCustomView() {
954                 // Hide `fullScreenVideoFrameLayout`.
955                 fullScreenVideoFrameLayout.removeAllViews();
956                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
957
958                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
959                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
960
961                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
962                 rootCoordinatorLayout.setFitsSystemWindows(true);
963
964                 // Show the ad if this is the free flavor.
965                 if (BuildConfig.FLAVOR.contentEquals("free")) {
966                     // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
967                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
968                 }
969             }
970
971             // Upload files.
972             @Override
973             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
974                 // Show the file chooser if the device is running API >= 21.
975                 if (Build.VERSION.SDK_INT >= 21) {
976                     // Store the file path callback.
977                     fileChooserCallback = filePathCallback;
978
979                     // Create an intent to open a chooser based ont the file chooser parameters.
980                     Intent fileChooserIntent = fileChooserParams.createIntent();
981
982                     // Open the file chooser.  Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
983                     startActivityForResult(fileChooserIntent, 0);
984                 }
985                 return true;
986             }
987         });
988
989         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
990         registerForContextMenu(mainWebView);
991
992         // Allow the downloading of files.
993         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
994             // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
995             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
996                 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
997
998                 // Store the variables for future use by `onRequestPermissionsResult()`.
999                 downloadUrl = url;
1000                 downloadContentDisposition = contentDisposition;
1001                 downloadContentLength = contentLength;
1002
1003                 // Show a dialog if the user has previously denied the permission.
1004                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
1005                     // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1006                     DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1007
1008                     // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
1009                     downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1010                 } else {  // Show the permission request directly.
1011                     // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
1012                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1013                 }
1014             } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1015                 // Get a handle for the download file alert dialog.
1016                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1017
1018                 // Show the download file alert dialog.
1019                 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1020             }
1021         });
1022
1023         // Allow pinch to zoom.
1024         mainWebView.getSettings().setBuiltInZoomControls(true);
1025
1026         // Hide zoom controls.
1027         mainWebView.getSettings().setDisplayZoomControls(false);
1028
1029         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
1030         mainWebView.getSettings().setUseWideViewPort(true);
1031
1032         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1033         mainWebView.getSettings().setLoadWithOverviewMode(true);
1034
1035         // Explicitly disable geolocation.
1036         mainWebView.getSettings().setGeolocationEnabled(false);
1037
1038         // Initialize cookieManager.
1039         cookieManager = CookieManager.getInstance();
1040
1041         // 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).
1042         customHeaders.put("X-Requested-With", "");
1043
1044         // 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.
1045         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1046
1047         // Get the intent that started the app.
1048         final Intent launchingIntent = getIntent();
1049
1050         // Extract the launching intent data as `launchingIntentUriData`.
1051         final Uri launchingIntentUriData = launchingIntent.getData();
1052
1053         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1054         if (launchingIntentUriData != null) {
1055             formattedUrlString = launchingIntentUriData.toString();
1056         }
1057
1058         // Get a handle for the `Runtime`.
1059         privacyBrowserRuntime = Runtime.getRuntime();
1060
1061         // Store the application's private data directory.
1062         privateDataDirectoryString = getApplicationInfo().dataDir;
1063         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1064
1065         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1066         inFullScreenBrowsingMode = false;
1067
1068         // Initialize the privacy settings variables.
1069         javaScriptEnabled = false;
1070         firstPartyCookiesEnabled = false;
1071         thirdPartyCookiesEnabled = false;
1072         domStorageEnabled = false;
1073         saveFormDataEnabled = false;
1074         nightMode = false;
1075
1076         // Initialize the WebView title.
1077         webViewTitle = getString(R.string.no_title);
1078
1079         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1080         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1081         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1082         assert favoriteIconBitmapDrawable != null;
1083         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1084
1085         // If the favorite icon is null, load the default.
1086         if (favoriteIconBitmap == null) {
1087             favoriteIconBitmap = favoriteIconDefaultBitmap;
1088         }
1089
1090         // Initialize the user agent array adapter and string array.
1091         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1092         userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1093
1094         // Apply the app settings from the shared preferences.
1095         applyAppSettings();
1096
1097         // Instantiate the block list helper.
1098         BlockListHelper blockListHelper = new BlockListHelper();
1099
1100         // Parse the block lists.
1101         final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1102         final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1103         final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1104         final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1105
1106         // Store the list versions.
1107         easyListVersion = easyList.get(0).get(0)[0];
1108         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1109         fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1110         fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1111
1112         mainWebView.setWebViewClient(new WebViewClient() {
1113             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1114             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1115             @SuppressWarnings("deprecation")
1116             @Override
1117             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1118                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
1119                     // Apply the domain settings for the new URL.
1120                     applyDomainSettings(url, true, false);
1121
1122                     // Returning false causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1123                     return false;
1124                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1125                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1126                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1127
1128                     // Parse the url and set it as the data for the intent.
1129                     emailIntent.setData(Uri.parse(url));
1130
1131                     // Open the email program in a new task instead of as part of Privacy Browser.
1132                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1133
1134                     // Make it so.
1135                     startActivity(emailIntent);
1136
1137                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1138                     return true;
1139                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1140                     // Open the dialer and load the phone number, but wait for the user to place the call.
1141                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1142
1143                     // Add the phone number to the intent.
1144                     dialIntent.setData(Uri.parse(url));
1145
1146                     // Open the dialer in a new task instead of as part of Privacy Browser.
1147                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1148
1149                     // Make it so.
1150                     startActivity(dialIntent);
1151
1152                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1153                     return true;
1154                 } else {  // Load a system chooser to select an app that can handle the URL.
1155                     // Open an app that can handle the URL.
1156                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1157
1158                     // Add the URL to the intent.
1159                     genericIntent.setData(Uri.parse(url));
1160
1161                     // List all apps that can handle the URL instead of just opening the first one.
1162                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1163
1164                     // Open the app in a new task instead of as part of Privacy Browser.
1165                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1166
1167                     // Start the app or display a snackbar if no app is available to handle the URL.
1168                     try {
1169                         startActivity(genericIntent);
1170                     } catch (ActivityNotFoundException exception) {
1171                         Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
1172                     }
1173
1174                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1175                     return true;
1176                 }
1177             }
1178
1179             // Check requests against the block lists.  The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1180             @SuppressWarnings("deprecation")
1181             @Override
1182             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1183                 // Create an empty web resource response to be used if the resource request is blocked.
1184                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1185
1186                 // Check EasyList if it is enabled.
1187                 if (easyListEnabled) {
1188                     if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1189                         // The resource request was blocked.  Return an empty web resource response.
1190                         return emptyWebResourceResponse;
1191                     }
1192                 }
1193
1194                 // Check EasyPrivacy if it is enabled.
1195                 if (easyPrivacyEnabled) {
1196                     if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1197                         // The resource request was blocked.  Return an empty web resource response.
1198                         return emptyWebResourceResponse;
1199                     }
1200                 }
1201
1202                 // Check Fanboy’s Annoyance List if it is enabled.
1203                 if (fanboysAnnoyanceListEnabled) {
1204                     if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1205                         // The resource request was blocked.  Return an empty web resource response.
1206                         return emptyWebResourceResponse;
1207                     }
1208                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1209                     if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1210                         // The resource request was blocked.  Return an empty web resource response.
1211                         return emptyWebResourceResponse;
1212                     }
1213                 }
1214
1215                 // The resource request has not been blocked.  `return null` loads the requested resource.
1216                 return null;
1217             }
1218
1219             // Handle HTTP authentication requests.
1220             @Override
1221             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1222                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1223                 httpAuthHandler = handler;
1224
1225                 // Display the HTTP authentication dialog.
1226                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1227                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1228             }
1229
1230             // Update the URL in urlTextBox when the page starts to load.
1231             @Override
1232             public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1233                 if (nightMode) {
1234                     mainWebView.setVisibility(View.INVISIBLE);
1235                 }
1236
1237                 // Hide the keyboard.  `0` indicates no additional flags.
1238                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1239
1240                 // Check to see if we are waiting on Orbot.
1241                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1242                     // 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.
1243                     formattedUrlString = url;
1244
1245                     // Display the formatted URL text.
1246                     urlTextBox.setText(formattedUrlString);
1247
1248                     // Apply text highlighting to `urlTextBox`.
1249                     highlightUrlText();
1250
1251                     // Apply any custom domain settings if the URL was loaded by navigating history.
1252                     if (navigatingHistory) {
1253                         applyDomainSettings(url, true, false);
1254                     }
1255
1256                     // 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.
1257                     urlIsLoading = true;
1258                 }
1259             }
1260
1261             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1262             @Override
1263             public void onPageFinished(WebView view, String url) {
1264                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1265                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1266                     cookieManager.flush();
1267                 }
1268
1269                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1270                 urlIsLoading = false;
1271
1272                 // Clear the cache and history if Incognito Mode is enabled.
1273                 if (incognitoModeEnabled) {
1274                     // Clear the cache.  `true` includes disk files.
1275                     mainWebView.clearCache(true);
1276
1277                     // Clear the back/forward history.
1278                     mainWebView.clearHistory();
1279
1280                     // Manually delete cache folders.
1281                     try {
1282                         // Delete the main cache directory.
1283                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1284
1285                         // Delete the secondary `Service Worker` cache directory.
1286                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1287                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1288                     } catch (IOException e) {
1289                         // Do nothing if an error is thrown.
1290                     }
1291                 }
1292
1293                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1294                 if (!waitingForOrbot) {
1295                     // Check to see if `WebView` has set `url` to be `about:blank`.
1296                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1297                         // Set `formattedUrlString` to `""`.
1298                         formattedUrlString = "";
1299
1300                         urlTextBox.setText(formattedUrlString);
1301
1302                         // Request focus for `urlTextBox`.
1303                         urlTextBox.requestFocus();
1304
1305                         // Display the keyboard.
1306                         inputMethodManager.showSoftInput(urlTextBox, 0);
1307
1308                         // Apply the domain settings.  This clears any settings from the previous domain.
1309                         applyDomainSettings(formattedUrlString, true, false);
1310                     } else {  // `WebView` has loaded a webpage.
1311                         // Set `formattedUrlString`.
1312                         formattedUrlString = url;
1313
1314                         // Only update `urlTextBox` if the user is not typing in it.
1315                         if (!urlTextBox.hasFocus()) {
1316                             // Display the formatted URL text.
1317                             urlTextBox.setText(formattedUrlString);
1318
1319                             // Apply text highlighting to `urlTextBox`.
1320                             highlightUrlText();
1321                         }
1322                     }
1323
1324                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1325                     sslCertificate = mainWebView.getCertificate();
1326
1327                     // 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.
1328                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1329                         // Initialize the current SSL certificate variables.
1330                         String currentWebsiteIssuedToCName = "";
1331                         String currentWebsiteIssuedToOName = "";
1332                         String currentWebsiteIssuedToUName = "";
1333                         String currentWebsiteIssuedByCName = "";
1334                         String currentWebsiteIssuedByOName = "";
1335                         String currentWebsiteIssuedByUName = "";
1336                         Date currentWebsiteSslStartDate = null;
1337                         Date currentWebsiteSslEndDate = null;
1338
1339
1340                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1341                         if (sslCertificate != null) {
1342                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1343                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1344                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1345                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1346                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1347                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1348                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1349                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1350                         }
1351
1352                         // 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`.
1353                         String currentWebsiteSslStartDateString = "";
1354                         String currentWebsiteSslEndDateString = "";
1355                         String pinnedDomainSslStartDateString = "";
1356                         String pinnedDomainSslEndDateString = "";
1357
1358                         // Convert the `Dates` to `Strings` if they are not `null`.
1359                         if (currentWebsiteSslStartDate != null) {
1360                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1361                         }
1362
1363                         if (currentWebsiteSslEndDate != null) {
1364                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1365                         }
1366
1367                         if (pinnedDomainSslStartDate != null) {
1368                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1369                         }
1370
1371                         if (pinnedDomainSslEndDate != null) {
1372                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1373                         }
1374
1375                         // Check to see if the pinned SSL certificate matches the current website certificate.
1376                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1377                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1378                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1379                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1380                             // The pinned SSL certificate doesn't match the current domain certificate.
1381                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1382                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1383                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1384                         }
1385                     }
1386                 }
1387             }
1388
1389             // Handle SSL Certificate errors.
1390             @Override
1391             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1392                 // Get the current website SSL certificate.
1393                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1394
1395                 // Extract the individual pieces of information from the current website SSL certificate.
1396                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1397                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1398                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1399                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1400                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1401                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1402                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1403                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1404
1405                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1406                 if (pinnedDomainSslCertificate &&
1407                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1408                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1409                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1410                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1411                     // An SSL certificate is pinned and matches the current domain certificate.
1412                     // Proceed to the website without displaying an error.
1413                     handler.proceed();
1414                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1415                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1416                     sslErrorHandler = handler;
1417
1418                     // Display the SSL error `AlertDialog`.
1419                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1420                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1421                 }
1422             }
1423         });
1424
1425         // Load the website if not waiting for Orbot to connect.
1426         if (!waitingForOrbot) {
1427             loadUrl(formattedUrlString);
1428         }
1429     }
1430
1431     @Override
1432     protected void onNewIntent(Intent intent) {
1433         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1434         setIntent(intent);
1435
1436         // Check to see if the intent contains a new URL.
1437         if (intent.getData() != null) {
1438             // Get the intent data and convert it to a string.
1439             final Uri intentUriData = intent.getData();
1440             formattedUrlString = intentUriData.toString();
1441
1442             // Load the website.
1443             loadUrl(formattedUrlString);
1444
1445             // Close the navigation drawer if it is open.
1446             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1447                 drawerLayout.closeDrawer(GravityCompat.START);
1448             }
1449
1450             // Close the bookmarks drawer if it is open.
1451             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1452                 drawerLayout.closeDrawer(GravityCompat.END);
1453             }
1454
1455             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1456             mainWebView.requestFocus();
1457         }
1458     }
1459
1460     @Override
1461     public void onRestart() {
1462         // Run the default commands.
1463         super.onRestart();
1464
1465         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1466         if (proxyThroughOrbot) {
1467             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1468             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1469
1470             // Send the intent to the Orbot package.
1471             orbotIntent.setPackage("org.torproject.android");
1472
1473             // Make it so.
1474             sendBroadcast(orbotIntent);
1475         }
1476
1477         // Apply the app settings if returning from the Settings activity..
1478         if (reapplyAppSettingsOnRestart) {
1479             // Apply the app settings.
1480             applyAppSettings();
1481
1482             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1483             if (reloadOnRestart) {
1484                 // Reload `mainWebView`.
1485                 mainWebView.reload();
1486
1487                 // Reset `reloadOnRestartBoolean`.
1488                 reloadOnRestart = false;
1489             }
1490
1491             // Reset the return from settings flag.
1492             reapplyAppSettingsOnRestart = false;
1493         }
1494
1495         // Apply the domain settings if returning from the Domains activity.
1496         if (reapplyDomainSettingsOnRestart) {
1497             // Reapply the domain settings.
1498             applyDomainSettings(formattedUrlString, false, true);
1499
1500             // Reset `reapplyDomainSettingsOnRestart`.
1501             reapplyDomainSettingsOnRestart = false;
1502         }
1503
1504         // Load the URL on restart to apply changes to night mode.
1505         if (loadUrlOnRestart) {
1506             // Load the current `formattedUrlString`.
1507             loadUrl(formattedUrlString);
1508
1509             // Reset `loadUrlOnRestart.
1510             loadUrlOnRestart = false;
1511         }
1512
1513         // Update the bookmarks drawer if returning from the Bookmarks activity.
1514         if (restartFromBookmarksActivity) {
1515             // Close the bookmarks drawer.
1516             drawerLayout.closeDrawer(GravityCompat.END);
1517
1518             // Reload the bookmarks drawer.
1519             loadBookmarksFolder();
1520
1521             // Reset `restartFromBookmarksActivity`.
1522             restartFromBookmarksActivity = false;
1523         }
1524
1525         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1526         updatePrivacyIcons(true);
1527     }
1528
1529     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1530     @Override
1531     public void onResume() {
1532         // Run the default commands.
1533         super.onResume();
1534
1535         // Resume JavaScript (if enabled).
1536         mainWebView.resumeTimers();
1537
1538         // Resume `mainWebView`.
1539         mainWebView.onResume();
1540
1541         // Resume the adView for the free flavor.
1542         if (BuildConfig.FLAVOR.contentEquals("free")) {
1543             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1544             AdHelper.resumeAd(findViewById(R.id.adview));
1545         }
1546     }
1547
1548     @Override
1549     public void onPause() {
1550         // Pause `mainWebView`.
1551         mainWebView.onPause();
1552
1553         // Stop all JavaScript.
1554         mainWebView.pauseTimers();
1555
1556         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1557         if (BuildConfig.FLAVOR.contentEquals("free")) {
1558             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1559             AdHelper.pauseAd(findViewById(R.id.adview));
1560         }
1561
1562         super.onPause();
1563     }
1564
1565     @Override
1566     public boolean onCreateOptionsMenu(Menu menu) {
1567         // Inflate the menu; this adds items to the action bar if it is present.
1568         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1569
1570         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1571         mainMenu = menu;
1572
1573         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1574         updatePrivacyIcons(false);
1575
1576         // Get handles for the menu items.
1577         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1578         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1579         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1580         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1581
1582         // Only display third-party cookies if SDK >= 21
1583         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1584
1585         // Get the shared preference values.  `this` references the current context.
1586         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1587
1588         // Set the status of the additional app bar icons.  The default is `false`.
1589         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1590             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1591             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1592             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1593         } else { //Do not display the additional icons.
1594             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1595             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1596             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1597         }
1598
1599         return true;
1600     }
1601
1602     @Override
1603     public boolean onPrepareOptionsMenu(Menu menu) {
1604         // Get handles for the menu items.
1605         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1606         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1607         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1608         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1609         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1610         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1611         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1612         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1613         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1614         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1615         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1616         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1617         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1618
1619         // Set the text for the domain menu item.
1620         if (domainSettingsApplied) {
1621             addOrEditDomain.setTitle(R.string.edit_domain_settings);
1622         } else {
1623             addOrEditDomain.setTitle(R.string.add_domain_settings);
1624         }
1625
1626         // Set the status of the menu item checkboxes.
1627         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1628         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1629         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1630         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1631         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1632
1633         // Enable third-party cookies if first-party cookies are enabled.
1634         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1635
1636         // Enable `DOM Storage` if JavaScript is enabled.
1637         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1638
1639         // Enable `Clear Cookies` if there are any.
1640         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1641
1642         // Get a count of the number of files in the `Local Storage` directory.
1643         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1644         int localStorageDirectoryNumberOfFiles = 0;
1645         if (localStorageDirectory.exists()) {
1646             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1647         }
1648
1649         // Get a count of the number of files in the `IndexedDB` directory.
1650         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1651         int indexedDBDirectoryNumberOfFiles = 0;
1652         if (indexedDBDirectory.exists()) {
1653             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1654         }
1655
1656         // Enable `Clear DOM Storage` if there is any.
1657         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1658
1659         // Enable `Clear Form Data` is there is any.
1660         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1661         clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1662
1663         // Enable `Clear Data` if any of the submenu items are enabled.
1664         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1665
1666         // Initialize font size variables.
1667         int fontSize = mainWebView.getSettings().getTextZoom();
1668         String fontSizeTitle;
1669         MenuItem selectedFontSizeMenuItem;
1670
1671         // Prepare the font size title and current size menu item.
1672         switch (fontSize) {
1673             case 25:
1674                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1675                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1676                 break;
1677
1678             case 50:
1679                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1680                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1681                 break;
1682
1683             case 75:
1684                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1685                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1686                 break;
1687
1688             case 100:
1689                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1690                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1691                 break;
1692
1693             case 125:
1694                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1695                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1696                 break;
1697
1698             case 150:
1699                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1700                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1701                 break;
1702
1703             case 175:
1704                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1705                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1706                 break;
1707
1708             case 200:
1709                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1710                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1711                 break;
1712
1713             default:
1714                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1715                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1716                 break;
1717         }
1718
1719         // Set the font size title and select the current size menu item.
1720         fontSizeMenuItem.setTitle(fontSizeTitle);
1721         selectedFontSizeMenuItem.setChecked(true);
1722
1723         // Only show Refresh if `swipeToRefresh` is disabled.
1724         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1725
1726         // Only show Ad Consent if this is the free flavor.
1727         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1728
1729         // Run all the other default commands.
1730         super.onPrepareOptionsMenu(menu);
1731
1732         // Display the menu.
1733         return true;
1734     }
1735
1736     @Override
1737     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1738     @SuppressLint("SetJavaScriptEnabled")
1739     // removeAllCookies is deprecated, but it is required for API < 21.
1740     @SuppressWarnings("deprecation")
1741     public boolean onOptionsItemSelected(MenuItem menuItem) {
1742         // Get the selected menu item ID.
1743         int menuItemId = menuItem.getItemId();
1744
1745         // Set the commands that relate to the menu entries.
1746         switch (menuItemId) {
1747             case R.id.add_or_edit_domain:
1748                 if (domainSettingsApplied) {  // Edit the current domain settings.
1749                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1750                     reapplyDomainSettingsOnRestart = true;
1751                     currentDomainName = "";
1752
1753                     // Create an intent to launch the domains activity.
1754                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1755
1756                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1757                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1758                     domainsIntent.putExtra("closeOnBack", true);
1759
1760                     // Make it so.
1761                     startActivity(domainsIntent);
1762                 } else {  // Add a new domain.
1763                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1764                     reapplyDomainSettingsOnRestart = true;
1765                     currentDomainName = "";
1766
1767                     // Get the current domain
1768                     Uri currentUri = Uri.parse(formattedUrlString);
1769                     String currentDomain = currentUri.getHost();
1770
1771                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1772                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1773
1774                     // Create the domain and store the database ID.
1775                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1776
1777                     // Create an intent to launch the domains activity.
1778                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1779
1780                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1781                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1782                     domainsIntent.putExtra("closeOnBack", true);
1783
1784                     // Make it so.
1785                     startActivity(domainsIntent);
1786                 }
1787                 return true;
1788
1789             case R.id.toggle_javascript:
1790                 // Switch the status of javaScriptEnabled.
1791                 javaScriptEnabled = !javaScriptEnabled;
1792
1793                 // Apply the new JavaScript status.
1794                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1795
1796                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1797                 updatePrivacyIcons(true);
1798
1799                 // Display a `Snackbar`.
1800                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1801                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1802                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1803                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1804                 } else {  // Privacy mode.
1805                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1806                 }
1807
1808                 // Reload the WebView.
1809                 mainWebView.reload();
1810                 return true;
1811
1812             case R.id.toggle_first_party_cookies:
1813                 // Switch the status of firstPartyCookiesEnabled.
1814                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1815
1816                 // Update the menu checkbox.
1817                 menuItem.setChecked(firstPartyCookiesEnabled);
1818
1819                 // Apply the new cookie status.
1820                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1821
1822                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1823                 updatePrivacyIcons(true);
1824
1825                 // Display a `Snackbar`.
1826                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1827                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1828                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
1829                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1830                 } else {  // Privacy mode.
1831                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1832                 }
1833
1834                 // Reload the WebView.
1835                 mainWebView.reload();
1836                 return true;
1837
1838             case R.id.toggle_third_party_cookies:
1839                 if (Build.VERSION.SDK_INT >= 21) {
1840                     // Switch the status of thirdPartyCookiesEnabled.
1841                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1842
1843                     // Update the menu checkbox.
1844                     menuItem.setChecked(thirdPartyCookiesEnabled);
1845
1846                     // Apply the new cookie status.
1847                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1848
1849                     // Display a `Snackbar`.
1850                     if (thirdPartyCookiesEnabled) {
1851                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1852                     } else {
1853                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1854                     }
1855
1856                     // Reload the WebView.
1857                     mainWebView.reload();
1858                 } // Else do nothing because SDK < 21.
1859                 return true;
1860
1861             case R.id.toggle_dom_storage:
1862                 // Switch the status of domStorageEnabled.
1863                 domStorageEnabled = !domStorageEnabled;
1864
1865                 // Update the menu checkbox.
1866                 menuItem.setChecked(domStorageEnabled);
1867
1868                 // Apply the new DOM Storage status.
1869                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1870
1871                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1872                 updatePrivacyIcons(true);
1873
1874                 // Display a `Snackbar`.
1875                 if (domStorageEnabled) {
1876                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1877                 } else {
1878                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1879                 }
1880
1881                 // Reload the WebView.
1882                 mainWebView.reload();
1883                 return true;
1884
1885             case R.id.toggle_save_form_data:
1886                 // Switch the status of saveFormDataEnabled.
1887                 saveFormDataEnabled = !saveFormDataEnabled;
1888
1889                 // Update the menu checkbox.
1890                 menuItem.setChecked(saveFormDataEnabled);
1891
1892                 // Apply the new form data status.
1893                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1894
1895                 // Display a `Snackbar`.
1896                 if (saveFormDataEnabled) {
1897                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1898                 } else {
1899                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1900                 }
1901
1902                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1903                 updatePrivacyIcons(true);
1904
1905                 // Reload the WebView.
1906                 mainWebView.reload();
1907                 return true;
1908
1909             case R.id.clear_cookies:
1910                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1911                         .setAction(R.string.undo, v -> {
1912                             // Do nothing because everything will be handled by `onDismissed()` below.
1913                         })
1914                         .addCallback(new Snackbar.Callback() {
1915                             @Override
1916                             public void onDismissed(Snackbar snackbar, int event) {
1917                                 switch (event) {
1918                                     // The user pushed the `Undo` button.
1919                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1920                                         // Do nothing.
1921                                         break;
1922
1923                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1924                                     default:
1925                                         // `cookieManager.removeAllCookie()` varies by SDK.
1926                                         if (Build.VERSION.SDK_INT < 21) {
1927                                             cookieManager.removeAllCookie();
1928                                         } else {
1929                                             // `null` indicates no callback.
1930                                             cookieManager.removeAllCookies(null);
1931                                         }
1932                                 }
1933                             }
1934                         })
1935                         .show();
1936                 return true;
1937
1938             case R.id.clear_dom_storage:
1939                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1940                         .setAction(R.string.undo, v -> {
1941                             // Do nothing because everything will be handled by `onDismissed()` below.
1942                         })
1943                         .addCallback(new Snackbar.Callback() {
1944                             @Override
1945                             public void onDismissed(Snackbar snackbar, int event) {
1946                                 switch (event) {
1947                                     // The user pushed the `Undo` button.
1948                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1949                                         // Do nothing.
1950                                         break;
1951
1952                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1953                                     default:
1954                                         // Delete the DOM Storage.
1955                                         WebStorage webStorage = WebStorage.getInstance();
1956                                         webStorage.deleteAllData();
1957
1958                                         // Manually delete the DOM storage files and directories.
1959                                         try {
1960                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1961                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1962
1963                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1964                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1965                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1966                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1967                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1968                                         } catch (IOException e) {
1969                                             // Do nothing if an error is thrown.
1970                                         }
1971                                 }
1972                             }
1973                         })
1974                         .show();
1975                 return true;
1976
1977             case R.id.clear_form_data:
1978                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1979                         .setAction(R.string.undo, v -> {
1980                             // Do nothing because everything will be handled by `onDismissed()` below.
1981                         })
1982                         .addCallback(new Snackbar.Callback() {
1983                             @Override
1984                             public void onDismissed(Snackbar snackbar, int event) {
1985                                 switch (event) {
1986                                     // The user pushed the `Undo` button.
1987                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1988                                         // Do nothing.
1989                                         break;
1990
1991                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1992                                     default:
1993                                         // Delete the form data.
1994                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1995                                         mainWebViewDatabase.clearFormData();
1996                                 }
1997                             }
1998                         })
1999                         .show();
2000                 return true;
2001
2002             case R.id.font_size_twenty_five_percent:
2003                 mainWebView.getSettings().setTextZoom(25);
2004                 return true;
2005
2006             case R.id.font_size_fifty_percent:
2007                 mainWebView.getSettings().setTextZoom(50);
2008                 return true;
2009
2010             case R.id.font_size_seventy_five_percent:
2011                 mainWebView.getSettings().setTextZoom(75);
2012                 return true;
2013
2014             case R.id.font_size_one_hundred_percent:
2015                 mainWebView.getSettings().setTextZoom(100);
2016                 return true;
2017
2018             case R.id.font_size_one_hundred_twenty_five_percent:
2019                 mainWebView.getSettings().setTextZoom(125);
2020                 return true;
2021
2022             case R.id.font_size_one_hundred_fifty_percent:
2023                 mainWebView.getSettings().setTextZoom(150);
2024                 return true;
2025
2026             case R.id.font_size_one_hundred_seventy_five_percent:
2027                 mainWebView.getSettings().setTextZoom(175);
2028                 return true;
2029
2030             case R.id.font_size_two_hundred_percent:
2031                 mainWebView.getSettings().setTextZoom(200);
2032                 return true;
2033
2034             case R.id.display_images:
2035                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2036                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2037                     mainWebView.reload();
2038                 } else {  // Images are not currently loaded automatically.
2039                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2040                 }
2041
2042                 // Set `onTheFlyDisplayImagesSet`.
2043                 onTheFlyDisplayImagesSet = true;
2044                 return true;
2045
2046             case R.id.share:
2047                 // Setup the share string.
2048                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2049
2050                 // Create the share intent.
2051                 Intent shareIntent = new Intent();
2052                 shareIntent.setAction(Intent.ACTION_SEND);
2053                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2054                 shareIntent.setType("text/plain");
2055
2056                 // Make it so.
2057                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2058                 return true;
2059
2060             case R.id.find_on_page:
2061                 // Hide the URL app bar.
2062                 supportAppBar.setVisibility(View.GONE);
2063
2064                 // Show the Find on Page `RelativeLayout`.
2065                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2066
2067                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2068                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2069                 findOnPageEditText.postDelayed(() -> {
2070                     // Set the focus on `findOnPageEditText`.
2071                     findOnPageEditText.requestFocus();
2072
2073                     // Display the keyboard.  `0` sets no input flags.
2074                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2075                 }, 200);
2076                 return true;
2077
2078             case R.id.print:
2079                 // Get a `PrintManager` instance.
2080                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2081
2082                 // Convert `mainWebView` to `printDocumentAdapter`.
2083                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2084
2085                 // Remove the lint error below that `printManager` might be `null`.
2086                 assert printManager != null;
2087
2088                 // Print the document.  The print attributes are `null`.
2089                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2090                 return true;
2091
2092             case R.id.view_source:
2093                 // Launch the Vew Source activity.
2094                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2095                 startActivity(viewSourceIntent);
2096                 return true;
2097
2098             case R.id.add_to_homescreen:
2099                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2100                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2101                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2102
2103                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2104                 return true;
2105
2106             case R.id.refresh:
2107                 mainWebView.reload();
2108                 return true;
2109
2110             case R.id.ad_consent:
2111                 // Display the ad consent dialog.
2112                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2113                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2114                 return true;
2115
2116             default:
2117                 // Don't consume the event.
2118                 return super.onOptionsItemSelected(menuItem);
2119         }
2120     }
2121
2122     // removeAllCookies is deprecated, but it is required for API < 21.
2123     @SuppressWarnings("deprecation")
2124     @Override
2125     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2126         int menuItemId = menuItem.getItemId();
2127
2128         switch (menuItemId) {
2129             case R.id.home:
2130                 loadUrl(homepage);
2131                 break;
2132
2133             case R.id.back:
2134                 if (mainWebView.canGoBack()) {
2135                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2136                     navigatingHistory = true;
2137
2138                     // Load the previous website in the history.
2139                     mainWebView.goBack();
2140                 }
2141                 break;
2142
2143             case R.id.forward:
2144                 if (mainWebView.canGoForward()) {
2145                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2146                     navigatingHistory = true;
2147
2148                     // Load the next website in the history.
2149                     mainWebView.goForward();
2150                 }
2151                 break;
2152
2153             case R.id.history:
2154                 // Get the `WebBackForwardList`.
2155                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2156
2157                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2158                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2159                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2160                 break;
2161
2162             case R.id.downloads:
2163                 // Launch the system Download Manager.
2164                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2165
2166                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2167                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2168
2169                 startActivity(downloadManagerIntent);
2170                 break;
2171
2172             case R.id.domains:
2173                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2174                 reapplyDomainSettingsOnRestart = true;
2175                 currentDomainName = "";
2176
2177                 // Launch `DomainsActivity`.
2178                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2179                 startActivity(domainsIntent);
2180                 break;
2181
2182             case R.id.settings:
2183                 // Set the flag to reapply app settings on restart when returning from Settings.
2184                 reapplyAppSettingsOnRestart = true;
2185
2186                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2187                 reapplyDomainSettingsOnRestart = true;
2188                 currentDomainName = "";
2189
2190                 // Launch `SettingsActivity`.
2191                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2192                 startActivity(settingsIntent);
2193                 break;
2194
2195             case R.id.guide:
2196                 // Launch `GuideActivity`.
2197                 Intent guideIntent = new Intent(this, GuideActivity.class);
2198                 startActivity(guideIntent);
2199                 break;
2200
2201             case R.id.about:
2202                 // Launch `AboutActivity`.
2203                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2204                 startActivity(aboutIntent);
2205                 break;
2206
2207             case R.id.clearAndExit:
2208                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2209                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2210
2211                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2212
2213                 // Clear cookies.
2214                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2215                     // The command to remove cookies changed slightly in API 21.
2216                     if (Build.VERSION.SDK_INT >= 21) {
2217                         cookieManager.removeAllCookies(null);
2218                     } else {
2219                         cookieManager.removeAllCookie();
2220                     }
2221
2222                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2223                     try {
2224                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2225                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2226                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2227                     } catch (IOException e) {
2228                         // Do nothing if an error is thrown.
2229                     }
2230                 }
2231
2232                 // Clear DOM storage.
2233                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2234                     // Ask `WebStorage` to clear the DOM storage.
2235                     WebStorage webStorage = WebStorage.getInstance();
2236                     webStorage.deleteAllData();
2237
2238                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2239                     try {
2240                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2241                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2242
2243                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2244                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2245                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2246                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2247                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2248                     } catch (IOException e) {
2249                         // Do nothing if an error is thrown.
2250                     }
2251                 }
2252
2253                 // Clear form data.
2254                 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2255                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2256                     webViewDatabase.clearFormData();
2257
2258                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2259                     try {
2260                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2261                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2262                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2263                     } catch (IOException e) {
2264                         // Do nothing if an error is thrown.
2265                     }
2266                 }
2267
2268                 // Clear the cache.
2269                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2270                     // `true` includes disk files.
2271                     mainWebView.clearCache(true);
2272
2273                     // Manually delete the cache directories.
2274                     try {
2275                         // Delete the main cache directory.
2276                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2277
2278                         // Delete the secondary `Service Worker` cache directory.
2279                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2280                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2281                     } catch (IOException e) {
2282                         // Do nothing if an error is thrown.
2283                     }
2284                 }
2285
2286                 // Clear SSL certificate preferences.
2287                 mainWebView.clearSslPreferences();
2288
2289                 // Clear the back/forward history.
2290                 mainWebView.clearHistory();
2291
2292                 // Clear `formattedUrlString`.
2293                 formattedUrlString = null;
2294
2295                 // Clear `customHeaders`.
2296                 customHeaders.clear();
2297
2298                 // Detach all views from `mainWebViewRelativeLayout`.
2299                 mainWebViewRelativeLayout.removeAllViews();
2300
2301                 // Destroy the internal state of `mainWebView`.
2302                 mainWebView.destroy();
2303
2304                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2305                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2306                 if (clearEverything) {
2307                     try {
2308                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2309                     } catch (IOException e) {
2310                         // Do nothing if an error is thrown.
2311                     }
2312                 }
2313
2314                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2315                 if (Build.VERSION.SDK_INT >= 21) {
2316                     finishAndRemoveTask();
2317                 } else {
2318                     finish();
2319                 }
2320
2321                 // Remove the terminated program from RAM.  The status code is `0`.
2322                 System.exit(0);
2323                 break;
2324         }
2325
2326         // Close the navigation drawer.
2327         drawerLayout.closeDrawer(GravityCompat.START);
2328         return true;
2329     }
2330
2331     @Override
2332     public void onPostCreate(Bundle savedInstanceState) {
2333         super.onPostCreate(savedInstanceState);
2334
2335         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2336         drawerToggle.syncState();
2337     }
2338
2339     @Override
2340     public void onConfigurationChanged(Configuration newConfig) {
2341         super.onConfigurationChanged(newConfig);
2342
2343         // Reload the ad for the free flavor if we are not in full screen mode.
2344         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2345             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2346             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
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                 // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3267                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3268             }
3269
3270             // Remove the translucent navigation bar flag if it is set.
3271             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3272
3273             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3274             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3275
3276             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3277             rootCoordinatorLayout.setSystemUiVisibility(0);
3278
3279             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3280             rootCoordinatorLayout.setFitsSystemWindows(true);
3281         }
3282     }
3283
3284     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3285     // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3286     @SuppressWarnings("deprecation")
3287     private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3288         // Reset `navigatingHistory`.
3289         navigatingHistory = false;
3290
3291         // Parse the URL into a URI.
3292         Uri uri = Uri.parse(url);
3293
3294         // Extract the domain from `uri`.
3295         String hostName = uri.getHost();
3296
3297         // Initialize `loadingNewDomainName`.
3298         boolean loadingNewDomainName;
3299
3300         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3301         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3302         //noinspection SimplifiableIfStatement
3303         if ((hostName == null) || (currentDomainName == null)) {
3304             loadingNewDomainName = true;
3305         } else {  // Determine if `hostName` equals `currentDomainName`.
3306             loadingNewDomainName = !hostName.equals(currentDomainName);
3307         }
3308
3309         // 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.
3310         if (loadingNewDomainName) {
3311             // Set the new `hostname` as the `currentDomainName`.
3312             currentDomainName = hostName;
3313
3314             // Reset `ignorePinnedSslCertificate`.
3315             ignorePinnedSslCertificate = false;
3316
3317             // Reset the favorite icon if specified.
3318             if (resetFavoriteIcon) {
3319                 favoriteIconBitmap = favoriteIconDefaultBitmap;
3320                 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3321             }
3322
3323             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3324             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3325             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3326
3327             // Get a full cursor from `domainsDatabaseHelper`.
3328             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3329
3330             // Initialize `domainSettingsSet`.
3331             Set<String> domainSettingsSet = new HashSet<>();
3332
3333             // Get the domain name column index.
3334             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3335
3336             // Populate `domainSettingsSet`.
3337             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3338                 // Move `domainsCursor` to the current row.
3339                 domainNameCursor.moveToPosition(i);
3340
3341                 // Store the domain name in `domainSettingsSet`.
3342                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3343             }
3344
3345             // Close `domainNameCursor.
3346             domainNameCursor.close();
3347
3348             // Initialize variables to track if domain settings will be applied and, if so, under which name.
3349             domainSettingsApplied = false;
3350             String domainNameInDatabase = null;
3351
3352             // Check the hostname.
3353             if (domainSettingsSet.contains(hostName)) {
3354                 domainSettingsApplied = true;
3355                 domainNameInDatabase = hostName;
3356             }
3357
3358             // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3359             if (hostName != null) {
3360                 while (hostName.contains(".") && !domainSettingsApplied) {  // Stop checking if we run out of  `.` or if we already know that `domainSettingsApplied` is `true`.
3361                     if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
3362                         domainSettingsApplied = true;
3363                         domainNameInDatabase = "*." + hostName;
3364                     }
3365
3366                     // Strip out the lowest subdomain of `host`.
3367                     hostName = hostName.substring(hostName.indexOf(".") + 1);
3368                 }
3369             }
3370
3371             // Get a handle for the shared preference.  `this` references the current context.
3372             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3373
3374             // Store the general preference information.
3375             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3376             String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3377             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3378             nightMode = sharedPreferences.getBoolean("night_mode", false);
3379
3380             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
3381                 // Get a cursor for the current host and move it to the first position.
3382                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3383                 currentHostDomainSettingsCursor.moveToFirst();
3384
3385                 // Get the settings from the cursor.
3386                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3387                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3388                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3389                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3390                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3391                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3392                 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3393                 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3394                 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3395                 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3396                 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3397                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3398                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3399                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3400                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3401                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3402                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3403                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3404                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3405                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3406                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3407
3408                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3409                 switch (nightModeInt) {
3410                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3411                         nightMode = true;
3412                         break;
3413
3414                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3415                         nightMode = false;
3416                         break;
3417                 }
3418
3419                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3420                 if (nightMode) {
3421                     javaScriptEnabled = true;
3422                 }
3423
3424                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3425                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3426                     pinnedDomainSslStartDate = null;
3427                 } else {
3428                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3429                 }
3430
3431                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3432                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3433                     pinnedDomainSslEndDate = null;
3434                 } else {
3435                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3436                 }
3437
3438                 // Close `currentHostDomainSettingsCursor`.
3439                 currentHostDomainSettingsCursor.close();
3440
3441                 // Apply the domain settings.
3442                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3443                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3444                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3445                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3446
3447                 // Apply the font size.
3448                 if (fontSize == 0) {  // Apply the default font size.
3449                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3450                 } else {  // Apply the specified font size.
3451                     mainWebView.getSettings().setTextZoom(fontSize);
3452                 }
3453
3454                 // Set third-party cookies status if API >= 21.
3455                 if (Build.VERSION.SDK_INT >= 21) {
3456                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3457                 }
3458
3459                 // 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.
3460                 // <https://redmine.stoutner.com/issues/160>
3461                 if (!urlIsLoading) {
3462                     // Set the user agent.
3463                     if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3464                         // Get the array position of the default user agent name.
3465                         int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3466
3467                         // Set the user agent according to the system default.
3468                         switch (defaultUserAgentArrayPosition) {
3469                             case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3470                                 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3471                                 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3472                                 break;
3473
3474                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3475                                 // Set the user agent to `""`, which uses the default value.
3476                                 mainWebView.getSettings().setUserAgentString("");
3477                                 break;
3478
3479                             case SETTINGS_CUSTOM_USER_AGENT:
3480                                 // Set the custom user agent.
3481                                 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3482                                 break;
3483
3484                             default:
3485                                 // Get the user agent string from the user agent data array
3486                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3487                         }
3488                     } else {  // Set the user agent according to the stored name.
3489                         // Get the array position of the user agent name.
3490                         int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3491
3492                         switch (userAgentArrayPosition) {
3493                             case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3494                                 mainWebView.getSettings().setUserAgentString(userAgentName);
3495                                 break;
3496
3497                             case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3498                                 // Set the user agent to `""`, which uses the default value.
3499                                 mainWebView.getSettings().setUserAgentString("");
3500                                 break;
3501
3502                             default:
3503                                 // Get the user agent string from the user agent data array.
3504                                 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3505                         }
3506                     }
3507
3508                     // Store the applied user agent string, which is used in the View Source activity.
3509                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3510                 }
3511
3512                 // 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.
3513                 if (darkTheme) {
3514                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3515                 } else {
3516                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3517                 }
3518             } else {  // The URL we are loading does not have custom domain settings.  Load the defaults.
3519                 // Store the values from `sharedPreferences` in variables.
3520                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3521                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3522                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3523                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3524                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3525                 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3526                 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3527                 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3528                 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3529
3530                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3531                 if (nightMode) {
3532                     javaScriptEnabled = true;
3533                 }
3534
3535                 // Apply the default settings.
3536                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3537                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3538                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3539                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3540                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3541
3542                 // Reset the pinned SSL certificate information.
3543                 domainSettingsDatabaseId = -1;
3544                 pinnedDomainSslCertificate = false;
3545                 pinnedDomainSslIssuedToCNameString = "";
3546                 pinnedDomainSslIssuedToONameString = "";
3547                 pinnedDomainSslIssuedToUNameString = "";
3548                 pinnedDomainSslIssuedByCNameString = "";
3549                 pinnedDomainSslIssuedByONameString = "";
3550                 pinnedDomainSslIssuedByUNameString = "";
3551                 pinnedDomainSslStartDate = null;
3552                 pinnedDomainSslEndDate = null;
3553
3554                 // Set third-party cookies status if API >= 21.
3555                 if (Build.VERSION.SDK_INT >= 21) {
3556                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3557                 }
3558
3559                 // 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.
3560                 // <https://redmine.stoutner.com/issues/160>
3561                 if (!urlIsLoading) {
3562                     // Get the array position of the user agent name.
3563                     int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3564
3565                     // Set the user agent.
3566                     switch (userAgentArrayPosition) {
3567                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3568                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3569                             mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3570                             break;
3571
3572                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3573                             // Set the user agent to `""`, which uses the default value.
3574                             mainWebView.getSettings().setUserAgentString("");
3575                             break;
3576
3577                         case SETTINGS_CUSTOM_USER_AGENT:
3578                             // Set the custom user agent.
3579                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3580                             break;
3581
3582                         default:
3583                             // Get the user agent string from the user agent data array
3584                             mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3585                     }
3586
3587                     // Store the applied user agent string, which is used in the View Source activity.
3588                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3589                 }
3590
3591                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3592                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3593             }
3594
3595             // Close `domainsDatabaseHelper`.
3596             domainsDatabaseHelper.close();
3597
3598             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
3599             onTheFlyDisplayImagesSet = false;
3600             setDisplayWebpageImages();
3601
3602             // Update the privacy icons, but only if `mainMenu` has already been populated.
3603             if (mainMenu != null) {
3604                 updatePrivacyIcons(true);
3605             }
3606
3607             // Reload the website if returning from the Domains activity.
3608             if (reloadWebsite) {
3609                 mainWebView.reload();
3610             }
3611         }
3612     }
3613
3614     private void setDisplayWebpageImages() {
3615         if (!onTheFlyDisplayImagesSet) {
3616             if (domainSettingsApplied) {  // Custom domain settings are applied.
3617                 switch (displayWebpageImagesInt) {
3618                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3619                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3620                         break;
3621
3622                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3623                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
3624                         break;
3625
3626                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3627                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
3628                         break;
3629                 }
3630             } else {  // Default settings are applied.
3631                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3632             }
3633         }
3634     }
3635
3636     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3637         // Get handles for the icons.
3638         MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3639         MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3640         MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3641         MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3642
3643         // Update `privacyIcon`.
3644         if (javaScriptEnabled) {  // JavaScript is enabled.
3645             privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3646         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
3647             privacyIconMenuItem.setIcon(R.drawable.warning);
3648         } else {  // All the dangerous features are disabled.
3649             privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3650         }
3651
3652         // Update `firstPartyCookiesIcon`.
3653         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
3654             firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3655         } else {  // First-party cookies are disabled.
3656             if (darkTheme) {
3657                 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3658             } else {
3659                 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3660             }
3661         }
3662
3663         // Update `domStorageIcon`.
3664         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
3665             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3666         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
3667             if (darkTheme) {
3668                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3669             } else {
3670                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3671             }
3672         } else {  // JavaScript is disabled, so DOM storage is ghosted.
3673             if (darkTheme) {
3674                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3675             } else {
3676                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3677             }
3678         }
3679
3680         // Update `formDataIcon`.
3681         if (saveFormDataEnabled) {  // Form data is enabled.
3682             formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3683         } else {  // Form data is disabled.
3684             if (darkTheme) {
3685                 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3686             } else {
3687                 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3688             }
3689         }
3690
3691         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3692         if (runInvalidateOptionsMenu) {
3693             invalidateOptionsMenu();
3694         }
3695     }
3696
3697     private void highlightUrlText() {
3698         String urlString = urlTextBox.getText().toString();
3699
3700         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
3701             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3702         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
3703             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3704         }
3705
3706         // Get the index of the `/` immediately after the domain name.
3707         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3708
3709         // De-emphasize the text after the domain name.
3710         if (endOfDomainName > 0) {
3711             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3712         }
3713     }
3714
3715     private void loadBookmarksFolder() {
3716         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3717         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3718
3719         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
3720         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3721             @Override
3722             public View newView(Context context, Cursor cursor, ViewGroup parent) {
3723                 // Inflate the individual item layout.  `false` does not attach it to the root.
3724                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3725             }
3726
3727             @Override
3728             public void bindView(View view, Context context, Cursor cursor) {
3729                 // Get handles for the views.
3730                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3731                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3732
3733                 // Get the favorite icon byte array from the cursor.
3734                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3735
3736                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3737                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3738
3739                 // Display the bitmap in `bookmarkFavoriteIcon`.
3740                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3741
3742                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3743                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3744                 bookmarkNameTextView.setText(bookmarkNameString);
3745
3746                 // Make the font bold for folders.
3747                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3748                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3749                 } else {  // Reset the font to default for normal bookmarks.
3750                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3751                 }
3752             }
3753         };
3754
3755         // Populate the `ListView` with the adapter.
3756         bookmarksListView.setAdapter(bookmarksCursorAdapter);
3757
3758         // Set the bookmarks drawer title.
3759         if (currentBookmarksFolder.isEmpty()) {
3760             bookmarksTitleTextView.setText(R.string.bookmarks);
3761         } else {
3762             bookmarksTitleTextView.setText(currentBookmarksFolder);
3763         }
3764     }
3765 }