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