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