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