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