Live update the blocked requests counts. https://redmine.stoutner.com/issues/323
[PrivacyBrowser.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     int blockedRequests;
206     int easyListBlockedRequests;
207     int easyPrivacyBlockedRequests;
208     int fanboysAnnoyanceListBlockedRequests;
209     int fanboysSocialBlockingListBlockedRequests;
210     int ultraPrivacyBlockedRequests;
211     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()` 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     // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
344     private boolean easyListEnabled;
345     private boolean easyPrivacyEnabled;
346     private boolean fanboysAnnoyanceListEnabled;
347     private boolean fanboysSocialBlockingListEnabled;
348     private boolean ultraPrivacyEnabled;
349
350     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
351     private Runtime privacyBrowserRuntime;
352
353     // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
354     private boolean proxyThroughOrbot;
355
356     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
357     private boolean incognitoModeEnabled;
358
359     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
360     private boolean fullScreenBrowsingModeEnabled;
361
362     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
363     private boolean inFullScreenBrowsingMode;
364
365     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
366     private boolean hideSystemBarsOnFullscreen;
367
368     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
369     private boolean translucentNavigationBarOnFullscreen;
370
371     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
372     private boolean reapplyDomainSettingsOnRestart;
373
374     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
375     private boolean reapplyAppSettingsOnRestart;
376
377     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
378     private boolean displayingFullScreenVideo;
379
380     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
381     private String currentDomainName;
382
383     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
384     private boolean ignorePinnedSslCertificate;
385
386     // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
387     private BroadcastReceiver orbotStatusBroadcastReceiver;
388
389     // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
390     private boolean waitingForOrbot;
391
392     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
393     private boolean domainSettingsApplied;
394
395     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
396     private int displayWebpageImagesInt;
397
398     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
399     private boolean onTheFlyDisplayImagesSet;
400
401     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
402     private String waitingForOrbotHTMLString;
403
404     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
405     private String privateDataDirectoryString;
406
407     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
408     private LinearLayout findOnPageLinearLayout;
409
410     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
411     private EditText findOnPageEditText;
412
413     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
414     private Menu mainMenu;
415
416     // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
417     private MenuItem refreshMenuItem;
418
419     // The blocklist menu items are used in `onCreate()` and `onCreateOptionsMenu()`.
420     MenuItem easyListMenuItem;
421     MenuItem easyPrivacyMenuItem;
422     MenuItem fanboysAnnoyanceListMenuItem;
423     MenuItem fanboysSocialBlockingListMenuItem;
424     MenuItem ultraPrivacyMenuItem;
425     MenuItem blockAllThirdParyRequestsMenuItem;
426
427     // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
428     private boolean displayAdditionalAppBarIcons;
429
430     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
431     private ActionBarDrawerToggle drawerToggle;
432
433     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
434     private Toolbar supportAppBar;
435
436     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
437     private EditText urlTextBox;
438
439     // The color spans are used in `onCreate()` and `highlightUrlText()`.
440     private ForegroundColorSpan redColorSpan;
441     private ForegroundColorSpan initialGrayColorSpan;
442     private ForegroundColorSpan finalGrayColorSpan;
443
444     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
445     private SslErrorHandler sslErrorHandler;
446
447     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
448     private static HttpAuthHandler httpAuthHandler;
449
450     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
451     private InputMethodManager inputMethodManager;
452
453     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
454     private RelativeLayout mainWebViewRelativeLayout;
455
456     // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
457     private boolean urlIsLoading;
458
459     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
460     private boolean pinnedDomainSslCertificate;
461
462     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
463     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
464
465     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
466     private ListView bookmarksListView;
467
468     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
469     private TextView bookmarksTitleTextView;
470
471     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
472     private Cursor bookmarksCursor;
473
474     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
475     private CursorAdapter bookmarksCursorAdapter;
476
477     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
478     private String oldFolderNameString;
479
480     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
481     private ValueCallback<Uri[]> fileChooserCallback;
482
483     // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
484     private String downloadUrl;
485     private String downloadContentDisposition;
486     private long downloadContentLength;
487
488     // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
489     private String downloadImageUrl;
490
491     // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
492     private ArrayAdapter<CharSequence> userAgentNamesArray;
493     private String[] userAgentDataArray;
494
495     // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
496     private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
497     private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
498
499     @Override
500     // 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.
501     // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
502     @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
503     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
504     @SuppressWarnings("deprecation")
505     protected void onCreate(Bundle savedInstanceState) {
506         // Get a handle for the shared preferences.
507         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
508
509         // Get the theme and screenshot preferences.
510         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
511         allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
512
513         // Disable screenshots if not allowed.
514         if (!allowScreenshots) {
515             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
516         }
517
518         // Set the activity theme.
519         if (darkTheme) {
520             setTheme(R.style.PrivacyBrowserDark);
521         } else {
522             setTheme(R.style.PrivacyBrowserLight);
523         }
524
525         // Run the default commands.
526         super.onCreate(savedInstanceState);
527
528         // Set the content view.
529         setContentView(R.layout.main_drawerlayout);
530
531         // Get a handle for `inputMethodManager`.
532         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
533
534         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
535         supportAppBar = findViewById(R.id.app_bar);
536         setSupportActionBar(supportAppBar);
537         appBar = getSupportActionBar();
538
539         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
540         assert appBar != null;
541
542         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
543         appBar.setCustomView(R.layout.url_app_bar);
544         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
545
546         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
547         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
548         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
549         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
550
551         // Get a handle for `urlTextBox`.
552         urlTextBox = findViewById(R.id.url_edittext);
553
554         // Remove the formatting from `urlTextBar` when the user is editing the text.
555         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
556             if (hasFocus) {  // The user is editing `urlTextBox`.
557                 // Remove the highlighting.
558                 urlTextBox.getText().removeSpan(redColorSpan);
559                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
560                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
561             } else {  // The user has stopped editing `urlTextBox`.
562                 // Reapply the highlighting.
563                 highlightUrlText();
564             }
565         });
566
567         // Set the go button on the keyboard to load the URL in `urlTextBox`.
568         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
569             // If the event is a key-down event on the `enter` button, load the URL.
570             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
571                 // Load the URL into the mainWebView and consume the event.
572                 try {
573                     loadUrlFromTextBox();
574                 } catch (UnsupportedEncodingException e) {
575                     e.printStackTrace();
576                 }
577                 // If the enter key was pressed, consume the event.
578                 return true;
579             } else {
580                 // If any other key was pressed, do not consume the event.
581                 return false;
582             }
583         });
584
585         // Set `waitingForOrbotHTMLString`.
586         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
587
588         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
589         currentDomainName = "";
590         orbotStatus = "unknown";
591         waitingForOrbot = false;
592
593         // Create an Orbot status `BroadcastReceiver`.
594         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
595             @Override
596             public void onReceive(Context context, Intent intent) {
597                 // Store the content of the status message in `orbotStatus`.
598                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
599
600                 // If we are waiting on Orbot, load the website now that Orbot is connected.
601                 if (orbotStatus.equals("ON") && waitingForOrbot) {
602                     // Reset `waitingForOrbot`.
603                     waitingForOrbot = false;
604
605                     // Load `formattedUrlString
606                     loadUrl(formattedUrlString);
607                 }
608             }
609         };
610
611         // Register `orbotStatusBroadcastReceiver` on `this` context.
612         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
613
614         // Get handles for views that need to be accessed.
615         drawerLayout = findViewById(R.id.drawerlayout);
616         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
617         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
618         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
619         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
620         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
621         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
622         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
623         mainWebView = findViewById(R.id.main_webview);
624         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
625         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
626         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
627         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
628         favoriteIconImageView = findViewById(R.id.favorite_icon);
629
630         // 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.
631         if (darkTheme) {
632             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
633             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
634             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
635             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
636         } else {
637             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
638             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
639             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
640             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
641         }
642
643         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
644         launchBookmarksActivityFab.setOnClickListener(v -> {
645             // Create an intent to launch the bookmarks activity.
646             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
647
648             // Include the current folder with the `Intent`.
649             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
650
651             // Make it so.
652             startActivity(bookmarksIntent);
653         });
654
655         // Set the create new bookmark folder FAB to display an alert dialog.
656         createBookmarkFolderFab.setOnClickListener(v -> {
657             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
658             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
659             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
660         });
661
662         // Set the create new bookmark FAB to display an alert dialog.
663         createBookmarkFab.setOnClickListener(view -> {
664             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
665             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
666             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
667         });
668
669         // Create a double-tap listener to toggle full-screen mode.
670         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
671             // Override `onDoubleTap()`.  All other events are handled using the default settings.
672             @Override
673             public boolean onDoubleTap(MotionEvent event) {
674                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
675                     // Toggle `inFullScreenBrowsingMode`.
676                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
677
678                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
679                         // Hide the `appBar`.
680                         appBar.hide();
681
682                         // Hide the banner ad in the free flavor.
683                         if (BuildConfig.FLAVOR.contentEquals("free")) {
684                             // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
685                             AdHelper.hideAd(findViewById(R.id.adview));
686                         }
687
688                         // Modify the system bars.
689                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
690                             // Remove the translucent overlays.
691                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
692
693                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
694                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
695
696                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
697                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
698                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
699                              */
700                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
701
702                             // Set `rootCoordinatorLayout` to fill the whole screen.
703                             rootCoordinatorLayout.setFitsSystemWindows(false);
704                         } else {  // Hide everything except the status and navigation bars.
705                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
706                             rootCoordinatorLayout.setFitsSystemWindows(false);
707
708                             // 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.
709                             if (translucentNavigationBarOnFullscreen) {
710                                 // Set the navigation bar to be translucent.
711                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
712                             }
713                         }
714                     } else {  // Switch to normal viewing mode.
715                         // Show the `appBar`.
716                         appBar.show();
717
718                         // Show the `BannerAd` in the free flavor.
719                         if (BuildConfig.FLAVOR.contentEquals("free")) {
720                             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
721                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
722                         }
723
724                         // Remove the translucent navigation bar flag if it is set.
725                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
726
727                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
728                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
729
730                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
731                         rootCoordinatorLayout.setSystemUiVisibility(0);
732
733                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
734                         rootCoordinatorLayout.setFitsSystemWindows(true);
735                     }
736
737                     // Consume the double-tap.
738                     return true;
739                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
740                     return false;
741                 }
742             }
743         });
744
745         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
746         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
747             // Call `performClick()` on the view, which is required for accessibility.
748             v.performClick();
749
750             // Send the `event` to `gestureDetector`.
751             return gestureDetector.onTouchEvent(event);
752         });
753
754         // Update `findOnPageCountTextView`.
755         mainWebView.setFindListener(new WebView.FindListener() {
756             // Get a handle for `findOnPageCountTextView`.
757             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
758
759             @Override
760             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
761                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
762                     // Set `findOnPageCountTextView` to `0/0`.
763                     findOnPageCountTextView.setText(R.string.zero_of_zero);
764                 } else if (isDoneCounting) {  // There are matches.
765                     // `activeMatchOrdinal` is zero-based.
766                     int activeMatch = activeMatchOrdinal + 1;
767
768                     // Build the match string.
769                     String matchString = activeMatch + "/" + numberOfMatches;
770
771                     // Set `findOnPageCountTextView`.
772                     findOnPageCountTextView.setText(matchString);
773                 }
774             }
775         });
776
777         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
778         findOnPageEditText.addTextChangedListener(new TextWatcher() {
779             @Override
780             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
781                 // Do nothing.
782             }
783
784             @Override
785             public void onTextChanged(CharSequence s, int start, int before, int count) {
786                 // Do nothing.
787             }
788
789             @Override
790             public void afterTextChanged(Editable s) {
791                 // Search for the text in `mainWebView`.
792                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
793             }
794         });
795
796         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
797         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
798             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
799                 // Hide the soft keyboard.  `0` indicates no additional flags.
800                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
801
802                 // Consume the event.
803                 return true;
804             } else {  // A different key was pressed.
805                 // Do not consume the event.
806                 return false;
807             }
808         });
809
810         // Implement swipe to refresh
811         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
812         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
813         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
814
815         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
816         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
817         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
818
819         // Listen for touches on the navigation menu.
820         final NavigationView navigationView = findViewById(R.id.navigationview);
821         navigationView.setNavigationItemSelectedListener(this);
822
823         // 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.
824         final Menu navigationMenu = navigationView.getMenu();
825         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
826         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
827         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
828         final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
829
830         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
831         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
832         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
833
834         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
835         currentBookmarksFolder = "";
836
837         // Load the home folder, which is `""` in the database.
838         loadBookmarksFolder();
839
840         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
841             // Convert the id from long to int to match the format of the bookmarks database.
842             int databaseID = (int) id;
843
844             // Get the bookmark cursor for this ID and move it to the first row.
845             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
846             bookmarkCursor.moveToFirst();
847
848             // Act upon the bookmark according to the type.
849             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
850                 // Store the new folder name in `currentBookmarksFolder`.
851                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
852
853                 // Load the new folder.
854                 loadBookmarksFolder();
855             } else {  // The selected bookmark is not a folder.
856                 // Load the bookmark URL.
857                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
858
859                 // Close the bookmarks drawer.
860                 drawerLayout.closeDrawer(GravityCompat.END);
861             }
862
863             // Close the `Cursor`.
864             bookmarkCursor.close();
865         });
866
867         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
868             // Convert the database ID from `long` to `int`.
869             int databaseId = (int) id;
870
871             // Find out if the selected bookmark is a folder.
872             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
873
874             if (isFolder) {
875                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
876                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
877
878                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
879                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
880                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
881             } else {
882                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
883                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
884                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
885             }
886
887             // Consume the event.
888             return true;
889         });
890
891         // The drawer listener is used to update the navigation menu.
892         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
893             @Override
894             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
895             }
896
897             @Override
898             public void onDrawerOpened(@NonNull View drawerView) {
899             }
900
901             @Override
902             public void onDrawerClosed(@NonNull View drawerView) {
903             }
904
905             @Override
906             public void onDrawerStateChanged(int newState) {
907                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
908                     // Update the back, forward, history, and requests menu items.
909                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
910                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
911                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
912                     navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
913
914                     // Hide the keyboard (if displayed).
915                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
916
917                     // Clear the focus from from the URL text box.
918                     urlTextBox.clearFocus();
919                 }
920             }
921         });
922
923         // drawerToggle creates the hamburger icon at the start of the AppBar.
924         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
925
926         // Get a handle for the progress bar.
927         final ProgressBar progressBar = findViewById(R.id.progress_bar);
928
929         mainWebView.setWebChromeClient(new WebChromeClient() {
930             // Update the progress bar when a page is loading.
931             @Override
932             public void onProgressChanged(WebView view, int progress) {
933                 // Inject the night mode CSS if night mode is enabled.
934                 if (nightMode) {
935                     // `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
936                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
937                     // `border: none` removes all borders, which can also be used to underline text.
938                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
939                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
940                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
941                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
942                                 // Initialize a `Handler` to display `mainWebView`.
943                                 Handler displayWebViewHandler = new Handler();
944
945                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
946                                 Runnable displayWebViewRunnable = () -> {
947                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
948                                     if (progressBar.getVisibility() == View.GONE) {
949                                         mainWebView.setVisibility(View.VISIBLE);
950                                     }
951                                 };
952
953                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
954                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
955                             });
956                 }
957
958                 // Update the progress bar.
959                 progressBar.setProgress(progress);
960
961                 // Set the visibility of the progress bar.
962                 if (progress < 100) {
963                     // Show the progress bar.
964                     progressBar.setVisibility(View.VISIBLE);
965                 } else {
966                     // Hide the progress bar.
967                     progressBar.setVisibility(View.GONE);
968
969                     // Display `mainWebView` if night mode is disabled.
970                     // 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
971                     // currently enabled.
972                     if (!nightMode) {
973                         mainWebView.setVisibility(View.VISIBLE);
974                     }
975
976                     //Stop the swipe to refresh indicator if it is running
977                     swipeRefreshLayout.setRefreshing(false);
978                 }
979             }
980
981             // Set the favorite icon when it changes.
982             @Override
983             public void onReceivedIcon(WebView view, Bitmap icon) {
984                 // Only update the favorite icon if the website has finished loading.
985                 if (progressBar.getVisibility() == View.GONE) {
986                     // Save a copy of the favorite icon.
987                     favoriteIconBitmap = icon;
988
989                     // Place the favorite icon in the appBar.
990                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
991                 }
992             }
993
994             // Save a copy of the title when it changes.
995             @Override
996             public void onReceivedTitle(WebView view, String title) {
997                 // Save a copy of the title.
998                 webViewTitle = title;
999             }
1000
1001             // Enter full screen video.
1002             @Override
1003             public void onShowCustomView(View view, CustomViewCallback callback) {
1004                 // Set the full screen video flag.
1005                 displayingFullScreenVideo = true;
1006
1007                 // Pause the ad if this is the free flavor.
1008                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1009                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1010                     AdHelper.pauseAd(findViewById(R.id.adview));
1011                 }
1012
1013                 // Remove the translucent overlays.
1014                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1015
1016                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1017                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1018
1019                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1020                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1021                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1022                  */
1023                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1024
1025                 // Set `rootCoordinatorLayout` to fill the entire screen.
1026                 rootCoordinatorLayout.setFitsSystemWindows(false);
1027
1028                 // Disable the sliding drawers.
1029                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1030
1031                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1032                 fullScreenVideoFrameLayout.addView(view);
1033                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1034             }
1035
1036             // Exit full screen video.
1037             @Override
1038             public void onHideCustomView() {
1039                 // Unset the full screen video flag.
1040                 displayingFullScreenVideo = true;
1041
1042                 // Hide `fullScreenVideoFrameLayout`.
1043                 fullScreenVideoFrameLayout.removeAllViews();
1044                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1045
1046                 // Enable the sliding drawers.
1047                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1048
1049                 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1050                 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
1051                     if (hideSystemBarsOnFullscreen) {  // Hide everything.
1052                         // Remove the translucent navigation setting if it is currently flagged.
1053                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1054
1055                         // Remove the translucent status bar overlay.
1056                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1057
1058                         // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1059                         drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1060
1061                         /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1062                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1063                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1064                          */
1065                         rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1066                     } else {  // Hide everything except the status and navigation bars.
1067                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1068                         rootCoordinatorLayout.setSystemUiVisibility(0);
1069
1070                         // Add the translucent status flag if it is unset.
1071                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1072
1073                         if (translucentNavigationBarOnFullscreen) {
1074                             // Set the navigation bar to be translucent.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1075                             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1076                         } else {
1077                             // Set the navigation bar to be black.
1078                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1079                         }
1080                     }
1081                 } else {  // Switch to normal viewing mode.
1082                     // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1083                     if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1084                         appBar.show();
1085                     }
1086
1087                     // Show the `BannerAd` in the free flavor.
1088                     if (BuildConfig.FLAVOR.contentEquals("free")) {
1089                         // Initialize the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1090                         AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1091                     }
1092
1093                     // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1094                     rootCoordinatorLayout.setSystemUiVisibility(0);
1095
1096                     // Remove the translucent navigation bar flag if it is set.
1097                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1098
1099                     // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1100                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1101
1102                     // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1103                     rootCoordinatorLayout.setFitsSystemWindows(true);
1104                 }
1105
1106                 // Show the ad if this is the free flavor.
1107                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1108                     // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1109                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1110                 }
1111             }
1112
1113             // Upload files.
1114             @Override
1115             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1116                 // Show the file chooser if the device is running API >= 21.
1117                 if (Build.VERSION.SDK_INT >= 21) {
1118                     // Store the file path callback.
1119                     fileChooserCallback = filePathCallback;
1120
1121                     // Create an intent to open a chooser based ont the file chooser parameters.
1122                     Intent fileChooserIntent = fileChooserParams.createIntent();
1123
1124                     // Open the file chooser.  Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1125                     startActivityForResult(fileChooserIntent, 0);
1126                 }
1127                 return true;
1128             }
1129         });
1130
1131         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
1132         registerForContextMenu(mainWebView);
1133
1134         // Allow the downloading of files.
1135         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1136             // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1137             if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1138                 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1139
1140                 // Store the variables for future use by `onRequestPermissionsResult()`.
1141                 downloadUrl = url;
1142                 downloadContentDisposition = contentDisposition;
1143                 downloadContentLength = contentLength;
1144
1145                 // Show a dialog if the user has previously denied the permission.
1146                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
1147                     // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1148                     DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1149
1150                     // Show the download location permission alert dialog.  The permission will be requested when the the dialog is closed.
1151                     downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1152                 } else {  // Show the permission request directly.
1153                     // Request the permission.  The download dialog will be launched by `onRequestPermissionResult()`.
1154                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1155                 }
1156             } else {  // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1157                 // Get a handle for the download file alert dialog.
1158                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1159
1160                 // Show the download file alert dialog.
1161                 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1162             }
1163         });
1164
1165         // Allow pinch to zoom.
1166         mainWebView.getSettings().setBuiltInZoomControls(true);
1167
1168         // Hide zoom controls.
1169         mainWebView.getSettings().setDisplayZoomControls(false);
1170
1171         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
1172         mainWebView.getSettings().setUseWideViewPort(true);
1173
1174         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1175         mainWebView.getSettings().setLoadWithOverviewMode(true);
1176
1177         // Explicitly disable geolocation.
1178         mainWebView.getSettings().setGeolocationEnabled(false);
1179
1180         // Initialize cookieManager.
1181         cookieManager = CookieManager.getInstance();
1182
1183         // 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).
1184         customHeaders.put("X-Requested-With", "");
1185
1186         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
1187         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1188
1189         // Get the intent that started the app.
1190         final Intent launchingIntent = getIntent();
1191
1192         // Extract the launching intent data as `launchingIntentUriData`.
1193         final Uri launchingIntentUriData = launchingIntent.getData();
1194
1195         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1196         if (launchingIntentUriData != null) {
1197             formattedUrlString = launchingIntentUriData.toString();
1198         }
1199
1200         // Get a handle for the `Runtime`.
1201         privacyBrowserRuntime = Runtime.getRuntime();
1202
1203         // Store the application's private data directory.
1204         privateDataDirectoryString = getApplicationInfo().dataDir;
1205         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1206
1207         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1208         inFullScreenBrowsingMode = false;
1209
1210         // Initialize the privacy settings variables.
1211         javaScriptEnabled = false;
1212         firstPartyCookiesEnabled = false;
1213         thirdPartyCookiesEnabled = false;
1214         domStorageEnabled = false;
1215         saveFormDataEnabled = false;  // Form data can be removed once the minimum API >= 26.
1216         nightMode = false;
1217
1218         // Initialize the WebView title.
1219         webViewTitle = getString(R.string.no_title);
1220
1221         // Initialize the favorite icon bitmap.  `ContextCompat` must be used until API >= 21.
1222         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1223         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1224         assert favoriteIconBitmapDrawable != null;
1225         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1226
1227         // If the favorite icon is null, load the default.
1228         if (favoriteIconBitmap == null) {
1229             favoriteIconBitmap = favoriteIconDefaultBitmap;
1230         }
1231
1232         // Initialize the user agent array adapter and string array.
1233         userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1234         userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1235
1236         // Apply the app settings from the shared preferences.
1237         applyAppSettings();
1238
1239         // Instantiate the block list helper.
1240         BlockListHelper blockListHelper = new BlockListHelper();
1241
1242         // Initialize the list of resource requests.
1243         resourceRequests = new ArrayList<>();
1244
1245         // Parse the block lists.
1246         final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1247         final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1248         final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1249         final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1250         final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1251
1252         // Store the list versions.
1253         easyListVersion = easyList.get(0).get(0)[0];
1254         easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1255         fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1256         fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1257         ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1258
1259         // Get a handle for the activity.  This is used to update the requests counter while the navigation menu is open.
1260         Activity activity = this;
1261
1262         mainWebView.setWebViewClient(new WebViewClient() {
1263             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1264             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1265             @SuppressWarnings("deprecation")
1266             @Override
1267             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1268                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
1269                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1270                     formattedUrlString = "";
1271
1272                     // Apply the domain settings for the new URL.  `applyDomainSettings` doesn't do anything if the domain has not changed.
1273                     applyDomainSettings(url, true, false);
1274
1275                     // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1276                     return false;
1277                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1278                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1279                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1280
1281                     // Parse the url and set it as the data for the intent.
1282                     emailIntent.setData(Uri.parse(url));
1283
1284                     // Open the email program in a new task instead of as part of Privacy Browser.
1285                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1286
1287                     // Make it so.
1288                     startActivity(emailIntent);
1289
1290                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1291                     return true;
1292                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1293                     // Open the dialer and load the phone number, but wait for the user to place the call.
1294                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1295
1296                     // Add the phone number to the intent.
1297                     dialIntent.setData(Uri.parse(url));
1298
1299                     // Open the dialer in a new task instead of as part of Privacy Browser.
1300                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1301
1302                     // Make it so.
1303                     startActivity(dialIntent);
1304
1305                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1306                     return true;
1307                 } else {  // Load a system chooser to select an app that can handle the URL.
1308                     // Open an app that can handle the URL.
1309                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1310
1311                     // Add the URL to the intent.
1312                     genericIntent.setData(Uri.parse(url));
1313
1314                     // List all apps that can handle the URL instead of just opening the first one.
1315                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1316
1317                     // Open the app in a new task instead of as part of Privacy Browser.
1318                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1319
1320                     // Start the app or display a snackbar if no app is available to handle the URL.
1321                     try {
1322                         startActivity(genericIntent);
1323                     } catch (ActivityNotFoundException exception) {
1324                         Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
1325                     }
1326
1327                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1328                     return true;
1329                 }
1330             }
1331
1332             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1333             @SuppressWarnings("deprecation")
1334             @Override
1335             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1336                 // Create an empty web resource response to be used if the resource request is blocked.
1337                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1338
1339                 // Reset the whitelist results tracker.
1340                 whiteListResultStringArray = null;
1341
1342                 // Initialize the third party request tracker.
1343                 boolean isThirdPartyRequest = false;
1344
1345                 // Initialize the current domain string.
1346                 String currentDomain = "";
1347
1348                 // Nobody is happy when comparing null strings.
1349                 if (!(formattedUrlString == null) && !(url == null)) {
1350                     // Get the domain strings to URIs.
1351                     Uri currentDomainUri = Uri.parse(formattedUrlString);
1352                     Uri requestDomainUri = Uri.parse(url);
1353
1354                     // Get the domain host names.
1355                     String currentBaseDomain = currentDomainUri.getHost();
1356                     String requestBaseDomain = requestDomainUri.getHost();
1357
1358                     // Update the current domain variable.
1359                     currentDomain = currentBaseDomain;
1360
1361                     // Only compare the current base domain and the request base domain if neither is null.
1362                     if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1363                         // Determine the current base domain.
1364                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1365                             // Remove the first subdomain.
1366                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1367                         }
1368
1369                         // Determine the request base domain.
1370                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
1371                             // Remove the first subdomain.
1372                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1373                         }
1374
1375                         // Update the third party request tracker.
1376                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1377                     }
1378                 }
1379
1380                 // Block third-party requests if enabled.
1381                 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1382                     // Increment the blocked requests counters.
1383                     blockedRequests++;
1384                     thirdPartyBlockedRequests++;
1385
1386                     // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1387                     activity.runOnUiThread(() -> {
1388                         navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1389                         blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1390                     });
1391
1392                     // Add the request to the log.
1393                     resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1394
1395                     // Return an empty web resource response.
1396                     return emptyWebResourceResponse;
1397                 }
1398
1399                 // Check UltraPrivacy if it is enabled.
1400                 if (ultraPrivacyEnabled) {
1401                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1402                         // Increment the blocked requests counters.
1403                         blockedRequests++;
1404                         ultraPrivacyBlockedRequests++;
1405
1406                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1407                         activity.runOnUiThread(() -> {
1408                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1409                             ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1410                         });
1411
1412                         // The resource request was blocked.  Return an empty web resource response.
1413                         return emptyWebResourceResponse;
1414                     }
1415
1416                     // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1417                     if (whiteListResultStringArray != null) {
1418                         // Add a whitelist entry to the resource requests array.
1419                         resourceRequests.add(whiteListResultStringArray);
1420
1421                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
1422                         return null;
1423                     }
1424                 }
1425
1426                 // Check EasyList if it is enabled.
1427                 if (easyListEnabled) {
1428                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1429                         // Increment the blocked requests counters.
1430                         blockedRequests++;
1431                         easyListBlockedRequests++;
1432
1433                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1434                         activity.runOnUiThread(() -> {
1435                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1436                             easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1437                         });
1438
1439                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1440                         whiteListResultStringArray = null;
1441
1442                         // The resource request was blocked.  Return an empty web resource response.
1443                         return emptyWebResourceResponse;
1444                     }
1445                 }
1446
1447                 // Check EasyPrivacy if it is enabled.
1448                 if (easyPrivacyEnabled) {
1449                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1450                         // Increment the blocked requests counters.
1451                         blockedRequests++;
1452                         easyPrivacyBlockedRequests++;
1453
1454                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1455                         activity.runOnUiThread(() -> {
1456                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1457                             easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1458                         });
1459
1460                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1461                         whiteListResultStringArray = null;
1462
1463                         // The resource request was blocked.  Return an empty web resource response.
1464                         return emptyWebResourceResponse;
1465                     }
1466                 }
1467
1468                 // Check Fanboy’s Annoyance List if it is enabled.
1469                 if (fanboysAnnoyanceListEnabled) {
1470                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1471                         // Increment the blocked requests counters.
1472                         blockedRequests++;
1473                         fanboysAnnoyanceListBlockedRequests++;
1474
1475                         // Update the titles of the blocklist menu items.  This must be run from the UI thread.
1476                         activity.runOnUiThread(() -> {
1477                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1478                             fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1479                         });
1480
1481                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1482                         whiteListResultStringArray = null;
1483
1484                         // The resource request was blocked.  Return an empty web resource response.
1485                         return emptyWebResourceResponse;
1486                     }
1487                 } else if (fanboysSocialBlockingListEnabled){  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1488                     if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1489                         // Increment the blocked requests counters.
1490                         blockedRequests++;
1491                         fanboysSocialBlockingListBlockedRequests++;
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                             fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1497                         });
1498
1499                         // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1500                         whiteListResultStringArray = null;
1501
1502                         // The resource request was blocked.  Return an empty web resource response.
1503                         return emptyWebResourceResponse;
1504                     }
1505                 }
1506
1507                 // Add the request to the log because it hasn't been processed by any of the previous checks.
1508                 if (whiteListResultStringArray != null ) {  // The request was processed by a whitelist.
1509                     resourceRequests.add(whiteListResultStringArray);
1510                 } else {  // The request didn't match any blocklist entry.  Log it as a defult request.
1511                     resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1512                 }
1513
1514                 // The resource request has not been blocked.  `return null` loads the requested resource.
1515                 return null;
1516             }
1517
1518             // Handle HTTP authentication requests.
1519             @Override
1520             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1521                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1522                 httpAuthHandler = handler;
1523
1524                 // Display the HTTP authentication dialog.
1525                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1526                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1527             }
1528
1529             // Update the URL in urlTextBox when the page starts to load.
1530             @Override
1531             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1532                 // Reset the list of resource requests.
1533                 resourceRequests.clear();
1534
1535                 // Initialize the counters for requests blocked by each blocklist.
1536                 blockedRequests = 0;
1537                 easyListBlockedRequests = 0;
1538                 easyPrivacyBlockedRequests = 0;
1539                 fanboysAnnoyanceListBlockedRequests = 0;
1540                 fanboysSocialBlockingListBlockedRequests = 0;
1541                 ultraPrivacyBlockedRequests = 0;
1542                 thirdPartyBlockedRequests = 0;
1543
1544                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1545                 if (nightMode) {
1546                     mainWebView.setVisibility(View.INVISIBLE);
1547                 }
1548
1549                 // Hide the keyboard.  `0` indicates no additional flags.
1550                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1551
1552                 // Check to see if Privacy Browser is waiting on Orbot.
1553                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1554                     // 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.
1555                     formattedUrlString = url;
1556
1557                     // Display the formatted URL text.
1558                     urlTextBox.setText(formattedUrlString);
1559
1560                     // Apply text highlighting to `urlTextBox`.
1561                     highlightUrlText();
1562
1563                     // Apply any custom domain settings if the URL was loaded by navigating history.
1564                     if (navigatingHistory) {
1565                         // Reset `navigatingHistory`.
1566                         navigatingHistory = false;
1567
1568                         // Apply the domain settings.
1569                         applyDomainSettings(url, true, false);
1570                     }
1571
1572                     // 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.
1573                     urlIsLoading = true;
1574
1575                     // Replace Refresh with Stop if the menu item has been created.  (The WebView typically begins loading before the menu items are instantiated.)
1576                     if (refreshMenuItem != null) {
1577                         // Set the title.
1578                         refreshMenuItem.setTitle(R.string.stop);
1579
1580                         // If the icon is displayed in the AppBar, set it according to the theme.
1581                         if (displayAdditionalAppBarIcons) {
1582                             if (darkTheme) {
1583                                 refreshMenuItem.setIcon(R.drawable.close_dark);
1584                             } else {
1585                                 refreshMenuItem.setIcon(R.drawable.close_light);
1586                             }
1587                         }
1588                     }
1589                 }
1590             }
1591
1592             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1593             @Override
1594             public void onPageFinished(WebView view, String url) {
1595                 // Flush any cookies to persistent storage.  `CookieManager` has become very lazy about flushing cookies in recent versions.
1596                 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1597                     cookieManager.flush();
1598                 }
1599
1600                 // Update the Refresh menu item if it has been created.
1601                 if (refreshMenuItem != null) {
1602                     // Reset the Refresh title.
1603                     refreshMenuItem.setTitle(R.string.refresh);
1604
1605                     // If the icon is displayed in the AppBar, reset it according to the theme.
1606                     if (displayAdditionalAppBarIcons) {
1607                         if (darkTheme) {
1608                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1609                         } else {
1610                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1611                         }
1612                     }
1613                 }
1614
1615                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1616                 urlIsLoading = false;
1617
1618                 // Clear the cache and history if Incognito Mode is enabled.
1619                 if (incognitoModeEnabled) {
1620                     // Clear the cache.  `true` includes disk files.
1621                     mainWebView.clearCache(true);
1622
1623                     // Clear the back/forward history.
1624                     mainWebView.clearHistory();
1625
1626                     // Manually delete cache folders.
1627                     try {
1628                         // Delete the main cache directory.
1629                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1630
1631                         // Delete the secondary `Service Worker` cache directory.
1632                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1633                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1634                     } catch (IOException e) {
1635                         // Do nothing if an error is thrown.
1636                     }
1637                 }
1638
1639                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1640                 if (!waitingForOrbot) {
1641                     // Check to see if `WebView` has set `url` to be `about:blank`.
1642                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1643                         // Set `formattedUrlString` to `""`.
1644                         formattedUrlString = "";
1645
1646                         urlTextBox.setText(formattedUrlString);
1647
1648                         // Request focus for `urlTextBox`.
1649                         urlTextBox.requestFocus();
1650
1651                         // Display the keyboard.
1652                         inputMethodManager.showSoftInput(urlTextBox, 0);
1653
1654                         // Apply the domain settings.  This clears any settings from the previous domain.
1655                         applyDomainSettings(formattedUrlString, true, false);
1656                     } else {  // `WebView` has loaded a webpage.
1657                         // Set `formattedUrlString`.
1658                         formattedUrlString = url;
1659
1660                         // Only update `urlTextBox` if the user is not typing in it.
1661                         if (!urlTextBox.hasFocus()) {
1662                             // Display the formatted URL text.
1663                             urlTextBox.setText(formattedUrlString);
1664
1665                             // Apply text highlighting to `urlTextBox`.
1666                             highlightUrlText();
1667                         }
1668                     }
1669
1670                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1671                     sslCertificate = mainWebView.getCertificate();
1672
1673                     // 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.
1674                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1675                         // Initialize the current SSL certificate variables.
1676                         String currentWebsiteIssuedToCName = "";
1677                         String currentWebsiteIssuedToOName = "";
1678                         String currentWebsiteIssuedToUName = "";
1679                         String currentWebsiteIssuedByCName = "";
1680                         String currentWebsiteIssuedByOName = "";
1681                         String currentWebsiteIssuedByUName = "";
1682                         Date currentWebsiteSslStartDate = null;
1683                         Date currentWebsiteSslEndDate = null;
1684
1685
1686                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1687                         if (sslCertificate != null) {
1688                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1689                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1690                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1691                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1692                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1693                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1694                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1695                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1696                         }
1697
1698                         // 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`.
1699                         String currentWebsiteSslStartDateString = "";
1700                         String currentWebsiteSslEndDateString = "";
1701                         String pinnedDomainSslStartDateString = "";
1702                         String pinnedDomainSslEndDateString = "";
1703
1704                         // Convert the `Dates` to `Strings` if they are not `null`.
1705                         if (currentWebsiteSslStartDate != null) {
1706                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1707                         }
1708
1709                         if (currentWebsiteSslEndDate != null) {
1710                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1711                         }
1712
1713                         if (pinnedDomainSslStartDate != null) {
1714                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1715                         }
1716
1717                         if (pinnedDomainSslEndDate != null) {
1718                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1719                         }
1720
1721                         // Check to see if the pinned SSL certificate matches the current website certificate.
1722                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1723                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1724                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1725                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1726                             // The pinned SSL certificate doesn't match the current domain certificate.
1727                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1728                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1729                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1730                         }
1731                     }
1732                 }
1733             }
1734
1735             // Handle SSL Certificate errors.
1736             @Override
1737             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1738                 // Get the current website SSL certificate.
1739                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1740
1741                 // Extract the individual pieces of information from the current website SSL certificate.
1742                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1743                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1744                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1745                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1746                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1747                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1748                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1749                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1750
1751                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1752                 if (pinnedDomainSslCertificate &&
1753                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1754                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1755                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1756                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1757                     // An SSL certificate is pinned and matches the current domain certificate.
1758                     // Proceed to the website without displaying an error.
1759                     handler.proceed();
1760                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1761                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1762                     sslErrorHandler = handler;
1763
1764                     // Display the SSL error `AlertDialog`.
1765                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1766                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1767                 }
1768             }
1769         });
1770
1771         // Load the website if not waiting for Orbot to connect.
1772         if (!waitingForOrbot) {
1773             loadUrl(formattedUrlString);
1774         }
1775     }
1776
1777     @Override
1778     protected void onNewIntent(Intent intent) {
1779         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1780         setIntent(intent);
1781
1782         // Check to see if the intent contains a new URL.
1783         if (intent.getData() != null) {
1784             // Get the intent data.
1785             final Uri intentUriData = intent.getData();
1786
1787             // Load the website.
1788             loadUrl(intentUriData.toString());
1789
1790             // Close the navigation drawer if it is open.
1791             if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1792                 drawerLayout.closeDrawer(GravityCompat.START);
1793             }
1794
1795             // Close the bookmarks drawer if it is open.
1796             if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1797                 drawerLayout.closeDrawer(GravityCompat.END);
1798             }
1799
1800             // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1801             mainWebView.requestFocus();
1802         }
1803     }
1804
1805     @Override
1806     public void onRestart() {
1807         // Run the default commands.
1808         super.onRestart();
1809
1810         // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1811         if (proxyThroughOrbot) {
1812             // Request Orbot to start.  If Orbot is already running no hard will be caused by this request.
1813             Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1814
1815             // Send the intent to the Orbot package.
1816             orbotIntent.setPackage("org.torproject.android");
1817
1818             // Make it so.
1819             sendBroadcast(orbotIntent);
1820         }
1821
1822         // Apply the app settings if returning from the Settings activity..
1823         if (reapplyAppSettingsOnRestart) {
1824             // Apply the app settings.
1825             applyAppSettings();
1826
1827             // Reload the webpage if displaying of images has been disabled in the Settings activity.
1828             if (reloadOnRestart) {
1829                 // Reload `mainWebView`.
1830                 mainWebView.reload();
1831
1832                 // Reset `reloadOnRestartBoolean`.
1833                 reloadOnRestart = false;
1834             }
1835
1836             // Reset the return from settings flag.
1837             reapplyAppSettingsOnRestart = false;
1838         }
1839
1840         // Apply the domain settings if returning from the Domains activity.
1841         if (reapplyDomainSettingsOnRestart) {
1842             // Reapply the domain settings.
1843             applyDomainSettings(formattedUrlString, false, true);
1844
1845             // Reset `reapplyDomainSettingsOnRestart`.
1846             reapplyDomainSettingsOnRestart = false;
1847         }
1848
1849         // Load the URL on restart to apply changes to night mode.
1850         if (loadUrlOnRestart) {
1851             // Load the current `formattedUrlString`.
1852             loadUrl(formattedUrlString);
1853
1854             // Reset `loadUrlOnRestart.
1855             loadUrlOnRestart = false;
1856         }
1857
1858         // Update the bookmarks drawer if returning from the Bookmarks activity.
1859         if (restartFromBookmarksActivity) {
1860             // Close the bookmarks drawer.
1861             drawerLayout.closeDrawer(GravityCompat.END);
1862
1863             // Reload the bookmarks drawer.
1864             loadBookmarksFolder();
1865
1866             // Reset `restartFromBookmarksActivity`.
1867             restartFromBookmarksActivity = false;
1868         }
1869
1870         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
1871         updatePrivacyIcons(true);
1872     }
1873
1874     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1875     @Override
1876     public void onResume() {
1877         // Run the default commands.
1878         super.onResume();
1879
1880         // Resume JavaScript (if enabled).
1881         mainWebView.resumeTimers();
1882
1883         // Resume `mainWebView`.
1884         mainWebView.onResume();
1885
1886         // Resume the adView for the free flavor.
1887         if (BuildConfig.FLAVOR.contentEquals("free")) {
1888             // Resume the ad.
1889             AdHelper.resumeAd(findViewById(R.id.adview));
1890         }
1891
1892         // Display a message to the user if waiting for Orbot.
1893         if (waitingForOrbot && !orbotStatus.equals("ON")) {
1894             // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
1895             mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1896         }
1897
1898         if (displayingFullScreenVideo) {
1899             // Remove the translucent overlays.
1900             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1901
1902             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1903             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1904
1905             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1906              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1907              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1908              */
1909             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1910         }
1911     }
1912
1913     @Override
1914     public void onPause() {
1915         // Run the default commands.
1916         super.onPause();
1917
1918         // Pause `mainWebView`.
1919         mainWebView.onPause();
1920
1921         // Stop all JavaScript.
1922         mainWebView.pauseTimers();
1923
1924         // Pause the ad or it will continue to consume resources in the background on the free flavor.
1925         if (BuildConfig.FLAVOR.contentEquals("free")) {
1926             // Pause the ad.
1927             AdHelper.pauseAd(findViewById(R.id.adview));
1928         }
1929     }
1930
1931     @Override
1932     public void onDestroy() {
1933         // Unregister the Orbot status broadcast receiver.
1934         this.unregisterReceiver(orbotStatusBroadcastReceiver);
1935
1936         // Run the default commands.
1937         super.onDestroy();
1938     }
1939
1940     @Override
1941     public boolean onCreateOptionsMenu(Menu menu) {
1942         // Inflate the menu; this adds items to the action bar if it is present.
1943         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1944
1945         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1946         mainMenu = menu;
1947
1948         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1949         updatePrivacyIcons(false);
1950
1951         // Get handles for the menu items.
1952         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1953         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1954         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1955         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
1956         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
1957         refreshMenuItem = menu.findItem(R.id.refresh);
1958         easyListMenuItem = menu.findItem(R.id.easylist);
1959         easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1960         fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1961         fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1962         ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1963         blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1964         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1965
1966         // Only display third-party cookies if API >= 21
1967         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1968
1969         // Only display the form data menu items if the API < 26.
1970         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1971         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1972
1973         // Only show Ad Consent if this is the free flavor.
1974         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1975
1976         // Get the shared preference values.
1977         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1978
1979         // Get the status of the additional AppBar icons.
1980         displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1981
1982         // 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.
1983         if (displayAdditionalAppBarIcons) {
1984             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1985             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1986             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1987         } else { //Do not display the additional icons.
1988             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1989             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1990             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1991         }
1992
1993         // Update the display names for the blocklists with the number of blocked requests.
1994         easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1995         easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1996         fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1997         fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1998         ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1999         blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2000
2001         // Replace Refresh with Stop if a URL is already loading.
2002         if (urlIsLoading) {
2003             // Set the title.
2004             refreshMenuItem.setTitle(R.string.stop);
2005
2006             // If the icon is displayed in the AppBar, set it according to the theme.
2007             if (displayAdditionalAppBarIcons) {
2008                 if (darkTheme) {
2009                     refreshMenuItem.setIcon(R.drawable.close_dark);
2010                 } else {
2011                     refreshMenuItem.setIcon(R.drawable.close_light);
2012                 }
2013             }
2014         }
2015
2016         return true;
2017     }
2018
2019     @Override
2020     public boolean onPrepareOptionsMenu(Menu menu) {
2021         // Get handles for the menu items.
2022         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2023         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2024         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2025         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2026         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
2027         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2028         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2029         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2030         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
2031         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2032         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2033         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2034
2035         // Set the text for the domain menu item.
2036         if (domainSettingsApplied) {
2037             addOrEditDomain.setTitle(R.string.edit_domain_settings);
2038         } else {
2039             addOrEditDomain.setTitle(R.string.add_domain_settings);
2040         }
2041
2042         // Set the status of the menu item checkboxes.
2043         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2044         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2045         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2046         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);  // Form data can be removed once the minimum API >= 26.
2047         easyListMenuItem.setChecked(easyListEnabled);
2048         easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2049         fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2050         fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2051         ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2052         blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2053         swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2054         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2055
2056         // Enable third-party cookies if first-party cookies are enabled.
2057         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2058
2059         // Enable DOM Storage if JavaScript is enabled.
2060         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2061
2062         // Enable Clear Cookies if there are any.
2063         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2064
2065         // Get a count of the number of files in the Local Storage directory.
2066         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2067         int localStorageDirectoryNumberOfFiles = 0;
2068         if (localStorageDirectory.exists()) {
2069             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2070         }
2071
2072         // Get a count of the number of files in the IndexedDB directory.
2073         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2074         int indexedDBDirectoryNumberOfFiles = 0;
2075         if (indexedDBDirectory.exists()) {
2076             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2077         }
2078
2079         // Enable Clear DOM Storage if there is any.
2080         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2081
2082         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
2083         if (Build.VERSION.SDK_INT < 26) {
2084             WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2085             clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2086         } else {
2087             // Disable clear form data because it is not supported on current version of Android.
2088             clearFormDataMenuItem.setEnabled(false);
2089         }
2090
2091         // Enable Clear Data if any of the submenu items are enabled.
2092         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2093
2094         // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2095         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2096
2097         // Initialize font size variables.
2098         int fontSize = mainWebView.getSettings().getTextZoom();
2099         String fontSizeTitle;
2100         MenuItem selectedFontSizeMenuItem;
2101
2102         // Prepare the font size title and current size menu item.
2103         switch (fontSize) {
2104             case 25:
2105                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2106                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2107                 break;
2108
2109             case 50:
2110                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2111                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2112                 break;
2113
2114             case 75:
2115                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2116                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2117                 break;
2118
2119             case 100:
2120                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2121                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2122                 break;
2123
2124             case 125:
2125                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2126                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2127                 break;
2128
2129             case 150:
2130                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2131                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2132                 break;
2133
2134             case 175:
2135                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2136                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2137                 break;
2138
2139             case 200:
2140                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2141                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2142                 break;
2143
2144             default:
2145                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2146                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2147                 break;
2148         }
2149
2150         // Set the font size title and select the current size menu item.
2151         fontSizeMenuItem.setTitle(fontSizeTitle);
2152         selectedFontSizeMenuItem.setChecked(true);
2153
2154         // Run all the other default commands.
2155         super.onPrepareOptionsMenu(menu);
2156
2157         // Display the menu.
2158         return true;
2159     }
2160
2161     @Override
2162     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2163     @SuppressLint("SetJavaScriptEnabled")
2164     // removeAllCookies is deprecated, but it is required for API < 21.
2165     @SuppressWarnings("deprecation")
2166     public boolean onOptionsItemSelected(MenuItem menuItem) {
2167         // Get the selected menu item ID.
2168         int menuItemId = menuItem.getItemId();
2169
2170         // Set the commands that relate to the menu entries.
2171         switch (menuItemId) {
2172             case R.id.toggle_javascript:
2173                 // Switch the status of javaScriptEnabled.
2174                 javaScriptEnabled = !javaScriptEnabled;
2175
2176                 // Apply the new JavaScript status.
2177                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2178
2179                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2180                 updatePrivacyIcons(true);
2181
2182                 // Display a `Snackbar`.
2183                 if (javaScriptEnabled) {  // JavaScrip is enabled.
2184                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2185                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
2186                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2187                 } else {  // Privacy mode.
2188                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2189                 }
2190
2191                 // Reload the WebView.
2192                 mainWebView.reload();
2193                 return true;
2194
2195             case R.id.add_or_edit_domain:
2196                 if (domainSettingsApplied) {  // Edit the current domain settings.
2197                     // Reapply the domain settings on returning to `MainWebViewActivity`.
2198                     reapplyDomainSettingsOnRestart = true;
2199                     currentDomainName = "";
2200
2201                     // Create an intent to launch the domains activity.
2202                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2203
2204                     // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2205                     domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2206                     domainsIntent.putExtra("closeOnBack", true);
2207
2208                     // Make it so.
2209                     startActivity(domainsIntent);
2210                 } else {  // Add a new domain.
2211                     // Apply the new domain settings on returning to `MainWebViewActivity`.
2212                     reapplyDomainSettingsOnRestart = true;
2213                     currentDomainName = "";
2214
2215                     // Get the current domain
2216                     Uri currentUri = Uri.parse(formattedUrlString);
2217                     String currentDomain = currentUri.getHost();
2218
2219                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2220                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2221
2222                     // Create the domain and store the database ID.
2223                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2224
2225                     // Create an intent to launch the domains activity.
2226                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2227
2228                     // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2229                     domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2230                     domainsIntent.putExtra("closeOnBack", true);
2231
2232                     // Make it so.
2233                     startActivity(domainsIntent);
2234                 }
2235                 return true;
2236
2237             case R.id.toggle_first_party_cookies:
2238                 // Switch the status of firstPartyCookiesEnabled.
2239                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2240
2241                 // Update the menu checkbox.
2242                 menuItem.setChecked(firstPartyCookiesEnabled);
2243
2244                 // Apply the new cookie status.
2245                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2246
2247                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2248                 updatePrivacyIcons(true);
2249
2250                 // Display a `Snackbar`.
2251                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2252                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2253                 } else if (javaScriptEnabled) {  // JavaScript is still enabled.
2254                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_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.toggle_third_party_cookies:
2264                 if (Build.VERSION.SDK_INT >= 21) {
2265                     // Switch the status of thirdPartyCookiesEnabled.
2266                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2267
2268                     // Update the menu checkbox.
2269                     menuItem.setChecked(thirdPartyCookiesEnabled);
2270
2271                     // Apply the new cookie status.
2272                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2273
2274                     // Display a `Snackbar`.
2275                     if (thirdPartyCookiesEnabled) {
2276                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2277                     } else {
2278                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2279                     }
2280
2281                     // Reload the WebView.
2282                     mainWebView.reload();
2283                 } // Else do nothing because SDK < 21.
2284                 return true;
2285
2286             case R.id.toggle_dom_storage:
2287                 // Switch the status of domStorageEnabled.
2288                 domStorageEnabled = !domStorageEnabled;
2289
2290                 // Update the menu checkbox.
2291                 menuItem.setChecked(domStorageEnabled);
2292
2293                 // Apply the new DOM Storage status.
2294                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2295
2296                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2297                 updatePrivacyIcons(true);
2298
2299                 // Display a `Snackbar`.
2300                 if (domStorageEnabled) {
2301                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2302                 } else {
2303                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2304                 }
2305
2306                 // Reload the WebView.
2307                 mainWebView.reload();
2308                 return true;
2309
2310             // Form data can be removed once the minimum API >= 26.
2311             case R.id.toggle_save_form_data:
2312                 // Switch the status of saveFormDataEnabled.
2313                 saveFormDataEnabled = !saveFormDataEnabled;
2314
2315                 // Update the menu checkbox.
2316                 menuItem.setChecked(saveFormDataEnabled);
2317
2318                 // Apply the new form data status.
2319                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2320
2321                 // Display a `Snackbar`.
2322                 if (saveFormDataEnabled) {
2323                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2324                 } else {
2325                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2326                 }
2327
2328                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2329                 updatePrivacyIcons(true);
2330
2331                 // Reload the WebView.
2332                 mainWebView.reload();
2333                 return true;
2334
2335             case R.id.clear_cookies:
2336                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2337                         .setAction(R.string.undo, v -> {
2338                             // Do nothing because everything will be handled by `onDismissed()` below.
2339                         })
2340                         .addCallback(new Snackbar.Callback() {
2341                             @Override
2342                             public void onDismissed(Snackbar snackbar, int event) {
2343                                 switch (event) {
2344                                     // The user pushed the `Undo` button.
2345                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2346                                         // Do nothing.
2347                                         break;
2348
2349                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2350                                     default:
2351                                         // `cookieManager.removeAllCookie()` varies by SDK.
2352                                         if (Build.VERSION.SDK_INT < 21) {
2353                                             cookieManager.removeAllCookie();
2354                                         } else {
2355                                             // `null` indicates no callback.
2356                                             cookieManager.removeAllCookies(null);
2357                                         }
2358                                 }
2359                             }
2360                         })
2361                         .show();
2362                 return true;
2363
2364             case R.id.clear_dom_storage:
2365                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2366                         .setAction(R.string.undo, v -> {
2367                             // Do nothing because everything will be handled by `onDismissed()` below.
2368                         })
2369                         .addCallback(new Snackbar.Callback() {
2370                             @Override
2371                             public void onDismissed(Snackbar snackbar, int event) {
2372                                 switch (event) {
2373                                     // The user pushed the `Undo` button.
2374                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2375                                         // Do nothing.
2376                                         break;
2377
2378                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2379                                     default:
2380                                         // Delete the DOM Storage.
2381                                         WebStorage webStorage = WebStorage.getInstance();
2382                                         webStorage.deleteAllData();
2383
2384                                         // Manually delete the DOM storage files and directories.
2385                                         try {
2386                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2387                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2388
2389                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2390                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2391                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2392                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2393                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2394                                         } catch (IOException e) {
2395                                             // Do nothing if an error is thrown.
2396                                         }
2397                                 }
2398                             }
2399                         })
2400                         .show();
2401                 return true;
2402
2403             // Form data can be remove once the minimum API >= 26.
2404             case R.id.clear_form_data:
2405                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2406                         .setAction(R.string.undo, v -> {
2407                             // Do nothing because everything will be handled by `onDismissed()` below.
2408                         })
2409                         .addCallback(new Snackbar.Callback() {
2410                             @Override
2411                             public void onDismissed(Snackbar snackbar, int event) {
2412                                 switch (event) {
2413                                     // The user pushed the `Undo` button.
2414                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2415                                         // Do nothing.
2416                                         break;
2417
2418                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2419                                     default:
2420                                         // Delete the form data.
2421                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2422                                         mainWebViewDatabase.clearFormData();
2423                                 }
2424                             }
2425                         })
2426                         .show();
2427                 return true;
2428
2429             case R.id.font_size_twenty_five_percent:
2430                 mainWebView.getSettings().setTextZoom(25);
2431                 return true;
2432
2433             case R.id.font_size_fifty_percent:
2434                 mainWebView.getSettings().setTextZoom(50);
2435                 return true;
2436
2437             case R.id.font_size_seventy_five_percent:
2438                 mainWebView.getSettings().setTextZoom(75);
2439                 return true;
2440
2441             case R.id.font_size_one_hundred_percent:
2442                 mainWebView.getSettings().setTextZoom(100);
2443                 return true;
2444
2445             case R.id.font_size_one_hundred_twenty_five_percent:
2446                 mainWebView.getSettings().setTextZoom(125);
2447                 return true;
2448
2449             case R.id.font_size_one_hundred_fifty_percent:
2450                 mainWebView.getSettings().setTextZoom(150);
2451                 return true;
2452
2453             case R.id.font_size_one_hundred_seventy_five_percent:
2454                 mainWebView.getSettings().setTextZoom(175);
2455                 return true;
2456
2457             case R.id.font_size_two_hundred_percent:
2458                 mainWebView.getSettings().setTextZoom(200);
2459                 return true;
2460
2461             case R.id.swipe_to_refresh:
2462                 // Toggle swipe to refresh.
2463                 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2464                 return true;
2465
2466             case R.id.display_images:
2467                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2468                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2469                     mainWebView.reload();
2470                 } else {  // Images are not currently loaded automatically.
2471                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2472                 }
2473
2474                 // Set `onTheFlyDisplayImagesSet`.
2475                 onTheFlyDisplayImagesSet = true;
2476                 return true;
2477
2478             case R.id.view_source:
2479                 // Launch the View Source activity.
2480                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2481                 startActivity(viewSourceIntent);
2482                 return true;
2483
2484             case R.id.easylist:
2485                 // Toggle the EasyList status.
2486                 easyListEnabled = !easyListEnabled;
2487
2488                 // Update the menu checkbox.
2489                 menuItem.setChecked(easyListEnabled);
2490
2491                 // Reload the main WebView.
2492                 mainWebView.reload();
2493                 return true;
2494
2495             case R.id.easyprivacy:
2496                 // Toggle the EasyPrivacy status.
2497                 easyPrivacyEnabled = !easyPrivacyEnabled;
2498
2499                 // Update the menu checkbox.
2500                 menuItem.setChecked(easyPrivacyEnabled);
2501
2502                 // Reload the main WebView.
2503                 mainWebView.reload();
2504                 return true;
2505
2506             case R.id.fanboys_annoyance_list:
2507                 // Toggle Fanboy's Annoyance List status.
2508                 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2509
2510                 // Update the menu checkbox.
2511                 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2512
2513                 // Update the staus of Fanboy's Social Blocking List.
2514                 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2515                 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2516
2517                 // Reload the main WebView.
2518                 mainWebView.reload();
2519                 return true;
2520
2521             case R.id.fanboys_social_blocking_list:
2522                 // Toggle Fanboy's Social Blocking List status.
2523                 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2524
2525                 // Update the menu checkbox.
2526                 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2527
2528                 // Reload the main WebView.
2529                 mainWebView.reload();
2530                 return true;
2531
2532             case R.id.ultraprivacy:
2533                 // Toggle the UltraPrivacy status.
2534                 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2535
2536                 // Update the menu checkbox.
2537                 menuItem.setChecked(ultraPrivacyEnabled);
2538
2539                 // Reload the main WebView.
2540                 mainWebView.reload();
2541                 return true;
2542
2543             case R.id.block_all_third_party_requests:
2544                 //Toggle the third-party requests blocker status.
2545                 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2546
2547                 // Update the menu checkbox.
2548                 menuItem.setChecked(blockAllThirdPartyRequests);
2549
2550                 // Reload the main WebView.
2551                 mainWebView.reload();
2552                 return true;
2553
2554             case R.id.share:
2555                 // Setup the share string.
2556                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2557
2558                 // Create the share intent.
2559                 Intent shareIntent = new Intent();
2560                 shareIntent.setAction(Intent.ACTION_SEND);
2561                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2562                 shareIntent.setType("text/plain");
2563
2564                 // Make it so.
2565                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2566                 return true;
2567
2568             case R.id.find_on_page:
2569                 // Hide the URL app bar.
2570                 supportAppBar.setVisibility(View.GONE);
2571
2572                 // Show the Find on Page `RelativeLayout`.
2573                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2574
2575                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2576                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2577                 findOnPageEditText.postDelayed(() -> {
2578                     // Set the focus on `findOnPageEditText`.
2579                     findOnPageEditText.requestFocus();
2580
2581                     // Display the keyboard.  `0` sets no input flags.
2582                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2583                 }, 200);
2584                 return true;
2585
2586             case R.id.print:
2587                 // Get a `PrintManager` instance.
2588                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2589
2590                 // Convert `mainWebView` to `printDocumentAdapter`.
2591                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2592
2593                 // Remove the lint error below that `printManager` might be `null`.
2594                 assert printManager != null;
2595
2596                 // Print the document.  The print attributes are `null`.
2597                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2598                 return true;
2599
2600             case R.id.add_to_homescreen:
2601                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2602                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2603                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2604
2605                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2606                 return true;
2607
2608             case R.id.refresh:
2609                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
2610                     // Reload the WebView.
2611                     mainWebView.reload();
2612                 } else {  // The stop button was pushed.
2613                     // Stop the loading of the WebView.
2614                     mainWebView.stopLoading();
2615                 }
2616                 return true;
2617
2618             case R.id.ad_consent:
2619                 // Display the ad consent dialog.
2620                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2621                 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2622                 return true;
2623
2624             default:
2625                 // Don't consume the event.
2626                 return super.onOptionsItemSelected(menuItem);
2627         }
2628     }
2629
2630     // removeAllCookies is deprecated, but it is required for API < 21.
2631     @SuppressWarnings("deprecation")
2632     @Override
2633     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2634         int menuItemId = menuItem.getItemId();
2635
2636         switch (menuItemId) {
2637             case R.id.home:
2638                 loadUrl(homepage);
2639                 break;
2640
2641             case R.id.back:
2642                 if (mainWebView.canGoBack()) {
2643                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2644                     formattedUrlString = "";
2645
2646                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2647                     navigatingHistory = true;
2648
2649                     // Load the previous website in the history.
2650                     mainWebView.goBack();
2651                 }
2652                 break;
2653
2654             case R.id.forward:
2655                 if (mainWebView.canGoForward()) {
2656                     // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2657                     formattedUrlString = "";
2658
2659                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2660                     navigatingHistory = true;
2661
2662                     // Load the next website in the history.
2663                     mainWebView.goForward();
2664                 }
2665                 break;
2666
2667             case R.id.history:
2668                 // Get the `WebBackForwardList`.
2669                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2670
2671                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2672                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2673                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2674                 break;
2675
2676             case R.id.requests:
2677                 // Launch the requests activity.
2678                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2679                 startActivity(requestsIntent);
2680                 break;
2681
2682             case R.id.downloads:
2683                 // Launch the system Download Manager.
2684                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2685
2686                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2687                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2688
2689                 startActivity(downloadManagerIntent);
2690                 break;
2691
2692             case R.id.domains:
2693                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2694                 reapplyDomainSettingsOnRestart = true;
2695                 currentDomainName = "";
2696
2697                 // Launch the domains activity.
2698                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2699                 startActivity(domainsIntent);
2700                 break;
2701
2702             case R.id.settings:
2703                 // Set the flag to reapply app settings on restart when returning from Settings.
2704                 reapplyAppSettingsOnRestart = true;
2705
2706                 // Set the flag to reapply the domain settings on restart when returning from Settings.
2707                 reapplyDomainSettingsOnRestart = true;
2708                 currentDomainName = "";
2709
2710                 // Launch the settings activity.
2711                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2712                 startActivity(settingsIntent);
2713                 break;
2714
2715             case R.id.guide:
2716                 // Launch `GuideActivity`.
2717                 Intent guideIntent = new Intent(this, GuideActivity.class);
2718                 startActivity(guideIntent);
2719                 break;
2720
2721             case R.id.about:
2722                 // Launch `AboutActivity`.
2723                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2724                 startActivity(aboutIntent);
2725                 break;
2726
2727             case R.id.clearAndExit:
2728                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2729                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2730
2731                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2732
2733                 // Clear cookies.
2734                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2735                     // The command to remove cookies changed slightly in API 21.
2736                     if (Build.VERSION.SDK_INT >= 21) {
2737                         cookieManager.removeAllCookies(null);
2738                     } else {
2739                         cookieManager.removeAllCookie();
2740                     }
2741
2742                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2743                     try {
2744                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2745                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2746                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2747                     } catch (IOException e) {
2748                         // Do nothing if an error is thrown.
2749                     }
2750                 }
2751
2752                 // Clear DOM storage.
2753                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2754                     // Ask `WebStorage` to clear the DOM storage.
2755                     WebStorage webStorage = WebStorage.getInstance();
2756                     webStorage.deleteAllData();
2757
2758                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2759                     try {
2760                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2761                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2762
2763                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2764                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2765                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2766                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2767                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2768                     } catch (IOException e) {
2769                         // Do nothing if an error is thrown.
2770                     }
2771                 }
2772
2773                 // Clear form data if the API < 26.
2774                 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2775                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2776                     webViewDatabase.clearFormData();
2777
2778                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2779                     try {
2780                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2781                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2782                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2783                     } catch (IOException e) {
2784                         // Do nothing if an error is thrown.
2785                     }
2786                 }
2787
2788                 // Clear the cache.
2789                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2790                     // `true` includes disk files.
2791                     mainWebView.clearCache(true);
2792
2793                     // Manually delete the cache directories.
2794                     try {
2795                         // Delete the main cache directory.
2796                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2797
2798                         // Delete the secondary `Service Worker` cache directory.
2799                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2800                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2801                     } catch (IOException e) {
2802                         // Do nothing if an error is thrown.
2803                     }
2804                 }
2805
2806                 // Clear SSL certificate preferences.
2807                 mainWebView.clearSslPreferences();
2808
2809                 // Clear the back/forward history.
2810                 mainWebView.clearHistory();
2811
2812                 // Clear `formattedUrlString`.
2813                 formattedUrlString = null;
2814
2815                 // Clear `customHeaders`.
2816                 customHeaders.clear();
2817
2818                 // Detach all views from `mainWebViewRelativeLayout`.
2819                 mainWebViewRelativeLayout.removeAllViews();
2820
2821                 // Destroy the internal state of `mainWebView`.
2822                 mainWebView.destroy();
2823
2824                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2825                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2826                 if (clearEverything) {
2827                     try {
2828                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2829                     } catch (IOException e) {
2830                         // Do nothing if an error is thrown.
2831                     }
2832                 }
2833
2834                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2835                 if (Build.VERSION.SDK_INT >= 21) {
2836                     finishAndRemoveTask();
2837                 } else {
2838                     finish();
2839                 }
2840
2841                 // Remove the terminated program from RAM.  The status code is `0`.
2842                 System.exit(0);
2843                 break;
2844         }
2845
2846         // Close the navigation drawer.
2847         drawerLayout.closeDrawer(GravityCompat.START);
2848         return true;
2849     }
2850
2851     @Override
2852     public void onPostCreate(Bundle savedInstanceState) {
2853         super.onPostCreate(savedInstanceState);
2854
2855         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2856         drawerToggle.syncState();
2857     }
2858
2859     @Override
2860     public void onConfigurationChanged(Configuration newConfig) {
2861         super.onConfigurationChanged(newConfig);
2862
2863         // Reload the ad for the free flavor if we not in full screen mode.
2864         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2865             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2866             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2867         }
2868
2869         // `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:
2870         // https://code.google.com/p/android/issues/detail?id=20493#c8
2871         // ActivityCompat.invalidateOptionsMenu(this);
2872     }
2873
2874     @Override
2875     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2876         // Store the `HitTestResult`.
2877         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2878
2879         // Create strings.
2880         final String imageUrl;
2881         final String linkUrl;
2882
2883         // Get a handle for the `ClipboardManager`.
2884         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2885
2886         // Remove the lint errors below that `clipboardManager` might be `null`.
2887         assert clipboardManager != null;
2888
2889         switch (hitTestResult.getType()) {
2890             // `SRC_ANCHOR_TYPE` is a link.
2891             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2892                 // Get the target URL.
2893                 linkUrl = hitTestResult.getExtra();
2894
2895                 // Set the target URL as the title of the `ContextMenu`.
2896                 menu.setHeaderTitle(linkUrl);
2897
2898                 // Add a Load URL entry.
2899                 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2900                     loadUrl(linkUrl);
2901                     return false;
2902                 });
2903
2904                 // Add a Copy URL entry.
2905   &nb