Fix the URL formatting bug. https://redmine.stoutner.com/issues/248
[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.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.BitmapFactory;
38 import android.graphics.Typeface;
39 import android.graphics.drawable.BitmapDrawable;
40 import android.graphics.drawable.Drawable;
41 import android.net.Uri;
42 import android.net.http.SslCertificate;
43 import android.net.http.SslError;
44 import android.os.Build;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.preference.PreferenceManager;
48 import android.print.PrintDocumentAdapter;
49 import android.print.PrintManager;
50 import android.support.annotation.NonNull;
51 import android.support.design.widget.CoordinatorLayout;
52 import android.support.design.widget.FloatingActionButton;
53 import android.support.design.widget.NavigationView;
54 import android.support.design.widget.Snackbar;
55 import android.support.v4.content.ContextCompat;
56 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
57 import android.support.v4.content.pm.ShortcutInfoCompat;
58 import android.support.v4.content.pm.ShortcutManagerCompat;
59 import android.support.v4.graphics.drawable.IconCompat;
60 import android.support.v4.view.GravityCompat;
61 import android.support.v4.widget.DrawerLayout;
62 import android.support.v4.widget.SwipeRefreshLayout;
63 import android.support.v7.app.ActionBar;
64 import android.support.v7.app.ActionBarDrawerToggle;
65 import android.support.v7.app.AppCompatActivity;
66 import android.support.v7.app.AppCompatDialogFragment;
67 import android.support.v7.widget.Toolbar;
68 import android.text.Editable;
69 import android.text.Spanned;
70 import android.text.TextWatcher;
71 import android.text.style.ForegroundColorSpan;
72 import android.util.Log;
73 import android.util.Patterns;
74 import android.view.ContextMenu;
75 import android.view.GestureDetector;
76 import android.view.KeyEvent;
77 import android.view.Menu;
78 import android.view.MenuItem;
79 import android.view.MotionEvent;
80 import android.view.View;
81 import android.view.ViewGroup;
82 import android.view.WindowManager;
83 import android.view.inputmethod.InputMethodManager;
84 import android.webkit.CookieManager;
85 import android.webkit.HttpAuthHandler;
86 import android.webkit.SslErrorHandler;
87 import android.webkit.WebBackForwardList;
88 import android.webkit.WebChromeClient;
89 import android.webkit.WebResourceResponse;
90 import android.webkit.WebStorage;
91 import android.webkit.WebView;
92 import android.webkit.WebViewClient;
93 import android.webkit.WebViewDatabase;
94 import android.widget.CursorAdapter;
95 import android.widget.EditText;
96 import android.widget.FrameLayout;
97 import android.widget.ImageView;
98 import android.widget.LinearLayout;
99 import android.widget.ListView;
100 import android.widget.ProgressBar;
101 import android.widget.RadioButton;
102 import android.widget.RelativeLayout;
103 import android.widget.TextView;
104
105 import com.stoutner.privacybrowser.BannerAd;
106 import com.stoutner.privacybrowser.BuildConfig;
107 import com.stoutner.privacybrowser.R;
108 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
109 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
110 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
111 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
112 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
113 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
114 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
115 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
116 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
117 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
118 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
119 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
120 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
121 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
124
125 import java.io.BufferedReader;
126 import java.io.ByteArrayInputStream;
127 import java.io.ByteArrayOutputStream;
128 import java.io.File;
129 import java.io.IOException;
130 import java.io.InputStreamReader;
131 import java.io.UnsupportedEncodingException;
132 import java.net.MalformedURLException;
133 import java.net.URL;
134 import java.net.URLDecoder;
135 import java.net.URLEncoder;
136 import java.util.Date;
137 import java.util.HashMap;
138 import java.util.HashSet;
139 import java.util.LinkedList;
140 import java.util.List;
141 import java.util.Map;
142 import java.util.Set;
143 import java.util.regex.Pattern;
144
145 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
146 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener,
147         CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener,
148         DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
149         NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener,
150         UrlHistoryDialog.UrlHistoryListener {
151
152     // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
153     // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
154     // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
155     //  and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
156     public static boolean darkTheme;
157
158     // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
159     // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`.  It is also used in `onCreate()`,
160     // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
161     public static Bitmap favoriteIconBitmap;
162
163     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
164     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
165     public static String formattedUrlString;
166
167     // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
168     // and `ViewSslCertificateDialog`.  It is also used in `onCreate()`.
169     public static SslCertificate sslCertificate;
170
171     // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`.  It is also used in `onCreate()`.
172     public static String orbotStatus;
173
174     // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`.  It is also used in `onCreate()`.
175     public static String webViewTitle;
176
177     // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`.  It is also used in `applyDomainSettings()`.
178     public static String appliedUserAgentString;
179
180     // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`.  It is also used in `applyAppSettings()` and `applyDomainSettings()`.
181     public static boolean displayWebpageImagesBoolean;
182
183     // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`
184     public static boolean reloadOnRestart;
185
186     // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onRestart()`.
187     public static boolean loadUrlOnRestart;
188
189     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
190     public static boolean restartFromBookmarksActivity;
191
192     // `easyListVersion` is public static so it can be accessed from `AboutTabFragment`.  It is also used in `onCreate()`.
193     public static String easyListVersion;
194
195     // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
196     // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
197     public static String currentBookmarksFolder;
198
199     // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
200     public static int domainSettingsDatabaseId;
201
202     // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`.  They are also used in `onCreate()` and `applyDomainSettings()`.
203     public static String pinnedDomainSslIssuedToCNameString;
204     public static String pinnedDomainSslIssuedToONameString;
205     public static String pinnedDomainSslIssuedToUNameString;
206     public static String pinnedDomainSslIssuedByCNameString;
207     public static String pinnedDomainSslIssuedByONameString;
208     public static String pinnedDomainSslIssuedByUNameString;
209     public static Date pinnedDomainSslStartDate;
210     public static Date pinnedDomainSslEndDate;
211
212
213     // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
214     private ActionBar appBar;
215
216     // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
217     private boolean navigatingHistory;
218
219     // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
220     private Bitmap favoriteIconDefaultBitmap;
221
222     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
223     private DrawerLayout drawerLayout;
224
225     // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
226     private CoordinatorLayout rootCoordinatorLayout;
227
228     // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
229     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
230     private WebView mainWebView;
231
232     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
233     private FrameLayout fullScreenVideoFrameLayout;
234
235     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
236     private SwipeRefreshLayout swipeRefreshLayout;
237
238     // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
239     private RelativeLayout urlAppBarRelativeLayout;
240
241     // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
242     private ImageView favoriteIconImageView;
243
244     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
245     private CookieManager cookieManager;
246
247     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
248     private final Map<String, String> customHeaders = new HashMap<>();
249
250     // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
251     private boolean javaScriptEnabled;
252
253     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
254     private boolean firstPartyCookiesEnabled;
255
256     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
257     private boolean thirdPartyCookiesEnabled;
258
259     // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
260     private boolean domStorageEnabled;
261
262     // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
263     private boolean saveFormDataEnabled;
264
265     // `nightMode` is used in `onCreate()` and  `applyDomainSettings()`.
266     private boolean nightMode;
267
268     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
269     private boolean swipeToRefreshEnabled;
270
271     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
272     private String homepage;
273
274     // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
275     private String searchURL;
276
277     // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
278     private boolean adBlockerEnabled;
279
280     // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
281     private Runtime privacyBrowserRuntime;
282
283     // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
284     private boolean incognitoModeEnabled;
285
286     // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
287     private boolean fullScreenBrowsingModeEnabled;
288
289     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
290     private boolean inFullScreenBrowsingMode;
291
292     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
293     private boolean hideSystemBarsOnFullscreen;
294
295     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
296     private boolean translucentNavigationBarOnFullscreen;
297
298     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
299     private boolean reapplyDomainSettingsOnRestart;
300
301     // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
302     private String currentDomainName;
303
304     // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
305     private boolean ignorePinnedSslCertificate;
306
307     // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
308     private boolean waitingForOrbot;
309
310     // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
311     private boolean domainSettingsApplied;
312
313     // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
314     private int displayWebpageImagesInt;
315
316     // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
317     private boolean onTheFlyDisplayImagesSet;
318
319     // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
320     private String waitingForOrbotHTMLString;
321
322     // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
323     private String privateDataDirectoryString;
324
325     // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
326     private LinearLayout findOnPageLinearLayout;
327
328     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
329     private EditText findOnPageEditText;
330
331     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
332     private Menu mainMenu;
333
334     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
335     private ActionBarDrawerToggle drawerToggle;
336
337     // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
338     private Toolbar supportAppBar;
339
340     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
341     private EditText urlTextBox;
342
343     // The color spans are used in `onCreate()` and `highlightUrlText()`.
344     private ForegroundColorSpan redColorSpan;
345     private ForegroundColorSpan initialGrayColorSpan;
346     private ForegroundColorSpan finalGrayColorSpan;
347
348     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
349     private View adView;
350
351     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
352     private SslErrorHandler sslErrorHandler;
353
354     // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
355     private static HttpAuthHandler httpAuthHandler;
356
357     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
358     private InputMethodManager inputMethodManager;
359
360     // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
361     private RelativeLayout mainWebViewRelativeLayout;
362
363     // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
364     private boolean urlIsLoading;
365
366     // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
367     private boolean pinnedDomainSslCertificate;
368
369     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
370     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
371
372     // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
373     private ListView bookmarksListView;
374
375     // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
376     private TextView bookmarksTitleTextView;
377
378     // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
379     private Cursor bookmarksCursor;
380
381     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
382     private CursorAdapter bookmarksCursorAdapter;
383
384     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
385     private String oldFolderNameString;
386
387     @Override
388     // 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.
389     @SuppressLint({"SetJavaScriptEnabled"})
390     // Remove Android Studio's warning about deprecations.  We have to use the deprecated `getColor()` until API >= 23.
391     @SuppressWarnings("deprecation")
392     protected void onCreate(Bundle savedInstanceState) {
393         // Get a handle for `sharedPreferences`.  `this` references the current context.
394         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
395
396         // Get the theme preference.
397         darkTheme = sharedPreferences.getBoolean("dark_theme", false);
398
399         // Set the activity theme.
400         if (darkTheme) {
401             setTheme(R.style.PrivacyBrowserDark);
402         } else {
403             setTheme(R.style.PrivacyBrowserLight);
404         }
405
406         // Run the default commands.
407         super.onCreate(savedInstanceState);
408
409         Log.i("BlockLists", "Begin populating block lists.");
410
411         // Initialize the block lists.
412         List<String> mainWhiteList = new LinkedList<>();
413         List<String[]> multiEntryWhiteList = new LinkedList<>();
414         List<String[]> domainWhiteList = new LinkedList<>();
415         List<String[]> thirdPartyDomainWhiteList = new LinkedList<>();
416         List<String> mainBlockList = new LinkedList<>();
417         List<String> initialBlockList = new LinkedList<>();
418         List<String> finalBlockList = new LinkedList<>();
419         List<String> thirdPartyBlockList = new LinkedList<>();
420         List<String> thirdPartyInitialBlockList = new LinkedList<>();
421         List<String[]> multiEntryBlockList = new LinkedList<>();
422         List<String[]> multiEntryInitialBlockList = new LinkedList<>();
423         List<String[]> multiEntryFinalBlockList = new LinkedList<>();
424         List<String[]> domainBlockList = new LinkedList<>();
425         List<String[]> domainInitialBlockList = new LinkedList<>();
426         List<String[]> domainFinalBlockList = new LinkedList<>();
427         List<String[]> domainRegularExpressionBlockList = new LinkedList<>();
428         List<String[]> thirdPartyMultiEntryBlockList = new LinkedList<>();
429         List<String[]> thirdPartyMultiEntryInitialBlockList = new LinkedList<>();
430         List<String[]> thirdPartyDomainBlockList = new LinkedList<>();
431         List<String> regularExpressionBlockList = new LinkedList<>();
432         List<String> thirdPartyRegularExpressionBlockList = new LinkedList<>();
433
434         // Populate the block lists.
435         try {
436             // Load `easylist.txt` into a `BufferedReader`.
437             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("easylist.txt")));
438
439             // Create a string for storing the block list entries.
440             String blockListEntry;
441
442             // Parse EasyList.
443             while ((blockListEntry = bufferedReader.readLine()) != null) {
444                 // Remove any `^` from the block list entry.  Privacy Browser does not process them in the interest of efficiency.
445                 blockListEntry = blockListEntry.replace("^", "");
446
447                 //noinspection StatementWithEmptyBody
448                 if (blockListEntry.contains("##") || blockListEntry.contains("#?#") || blockListEntry.contains("#@#") || blockListEntry.startsWith("[")) {
449                     // Entries that contain `##`, `#?#`, and `#@#` are for hiding elements in the main page's HTML.  Entries that start with `[` describe the AdBlock compatibility level.
450
451                     // Do nothing.  Privacy Browser does not currently use these entries.
452
453                     //Log.i("BlackLists", "Not added: " + adBlockerEntry);
454                 } else if (blockListEntry.startsWith("!")){  //  Entries that begin with `!` are comments.
455                     if (blockListEntry.startsWith("! Version:")) {
456                         // Store the EasyList version number.
457                         easyListVersion = blockListEntry.substring(11);
458                     }
459
460                     //Log.i("BlackLists", "Not added: " + adBlockerEntry);
461                 } else if (blockListEntry.startsWith("@@")) {  // Entries that begin with `@@` are whitelists.
462                     // Remove the `@@`
463                     blockListEntry = blockListEntry.substring(2);
464
465                     // Strip out an initial `||`  Privacy Browser doesn't differentiate against items that only match against the end of the domain name.
466                     if (blockListEntry.startsWith("||")) {
467                         blockListEntry = blockListEntry.substring(2);
468                     }
469
470                     // TODO
471
472                     // mainWhiteList.add(blockListEntry);
473
474                     // Log.i("BlockLists", "Main white list added: " + blockListEntry);
475                 } else if (blockListEntry.endsWith("|")){  // Entries that end with `|` match against the end of the URL.
476                     // Strip out the final "|"
477                     blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
478
479                     // Strip out any initial `||`.  They are redundant in this case because the block list entry is being matched against the end of the URL.
480                     if (blockListEntry.startsWith("||")) {
481                         blockListEntry = blockListEntry.substring(2);
482                     }
483
484                     if (blockListEntry.contains("*")) {  // Process a double final entry.
485                         int wildcardIndex = blockListEntry.indexOf("*");
486
487                         String firstEntry = blockListEntry.substring(0, wildcardIndex);
488                         String secondEntry = blockListEntry.substring(wildcardIndex + 1);
489
490
491                         String[] doubleEntry = {firstEntry, secondEntry};
492
493                         multiEntryFinalBlockList.add(doubleEntry);
494
495                         //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry + " , " + secondEntry).
496                     } else {  // Process a standard final entry.
497                         finalBlockList.add(blockListEntry);
498
499                         //Log.i("BlockLists", "Final block list added: " + blockListEntry);
500                     }
501                 } else if (blockListEntry.contains("$")) {  // Entries that contain `$` use filter options.
502                     // Strip out any initial `||`.  These will be treated like any other entry.
503                     if (blockListEntry.startsWith("||")) {
504                         blockListEntry = blockListEntry.substring(2);
505                     }
506
507                     if (blockListEntry.contains("third-party")) {  // Process third party blocklist entries.
508                         //noinspection StatementWithEmptyBody
509                         if (blockListEntry.contains("~third-party")) {  // Process third-party white list entries.
510                             // Do not process these white list entries.  They are designed to combine with block filters that Privacy Browser doesn't use, like `subdocument` and `xmlhttprequest`.
511
512                             // Log.i("BlockLists", "Not added: " + blockListEntry);
513                         } else if (blockListEntry.contains("domain=")) {  // Process third-party domain block list entries.
514                             if (blockListEntry.startsWith("|")) {  // Third-party domain initial block list entries.
515
516                             } else if (blockListEntry.contains("\\")) {  // Third-party domain regular expressions.
517
518                             } else {  // Third-party domain entries.
519                                 // Parse the entry
520                                 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
521                                 String filters = blockListEntry.substring(blockListEntry.indexOf("$") + 1);
522                                 String domains = filters.substring(filters.indexOf("domain=") + 7);
523
524                                 // Strip any trailing "*" on the entries.
525                                 if (entry.endsWith("*")) {
526                                     entry = entry.substring(0, entry.length() - 1);
527                                 }
528
529                                 if (entry.contains("*")) {  // Third-party domain multi-entry.
530
531                                 } else {  // Third-party domain single entry.
532
533                                     boolean whiteListDomain = false;
534
535                                     // Process each domain.
536                                     do {
537                                         String domain;
538
539                                         if (domains.contains("|")) {
540                                             // Get the first domain
541                                             domain = domains.substring(0, domains.indexOf("|"));
542
543                                             // Remove the first domain from the list.
544                                             domains = domains.substring(domains.indexOf("|") + 1);
545                                         } else {
546                                             domain = domains;
547                                         }
548
549                                         // Differentiate between block list domains and white list domains.
550                                         if (domain.startsWith("~")) {  // White list third-party domain entry.
551                                             // Strip the initial `~`.
552                                             domain = domain.substring(1);
553
554                                             // Set the white list domain flag and store the domain.
555                                             whiteListDomain = true;
556
557                                             // Create the domain entry.
558                                             String[] domainEntry = {domain, entry};
559
560                                             // Add the entry to the third-party domain white list.
561                                             thirdPartyDomainWhiteList.add(domainEntry);
562
563                                             Log.i("BlockLists", "Third-party domain white list added: " + domain + " , " + entry);
564                                         } else {  // Block list third-party domain entry.
565                                             String[] domainEntry = {domain, entry};
566
567                                             thirdPartyDomainBlockList.add(domainEntry);
568
569                                             // Log.i("BlockLists", "Third-party domain block list added: " + domain + " , " + entry);
570                                         }
571                                     } while (domains.contains("|"));
572
573                                     // Add a third-party block list entry if a white list domain was processed.
574                                     if (whiteListDomain) {
575                                         // Add an entry to the third-party block list.
576                                         thirdPartyBlockList.add(entry);
577
578                                         Log.i("BlockLists", "Third-party block list added: " + entry);
579                                     }
580                                 }
581                             }
582                         } else if (blockListEntry.startsWith("|")) {  // Third-party initial block list entries.
583                             // Strip the initial `|`.
584                             blockListEntry = blockListEntry.substring(1);
585
586                             // Get the entry.
587                             String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
588
589                             if (entry.contains("*")) {  // Process a third-party multi-entry initial block list.
590                                 int wildcardIndex = entry.indexOf("*");
591
592                                 String firstEntry = entry.substring(0, wildcardIndex);
593                                 String secondEntry = entry.substring(wildcardIndex + 1);
594
595                                 String[] thirdPartyDoubleEntry = {firstEntry, secondEntry};
596
597                                 thirdPartyMultiEntryInitialBlockList.add(thirdPartyDoubleEntry);
598
599                                 //Log.i("BlockLists", "Third-party multi-entry initial block list added: " + firstEntry + " , " + secondEntry);
600                             } else {
601                                 thirdPartyInitialBlockList.add(entry);
602
603                                 //Log.i("BlockLists", "Third-party initial block list added: " + entry);
604                             }
605                         } else if (blockListEntry.contains("*")) {  // Process third-party multi-entry or regular expression blocklist entries.
606                             // Get the entry.
607                             String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
608
609                             if (entry.endsWith("*")) {
610                                 // Strip the final `*`.
611                                 entry = entry.substring(0, entry.length() - 1);
612
613                                 // Add the entry to the block list.
614                                 thirdPartyBlockList.add(entry);
615
616                                 //Log.i("BlockLists", "Third party block list added: " + entry);
617                             } else if (entry.contains("\\")) {  // Process a third-party regular expression.
618                                 // Add the entry to the third-party regular expression block list.
619                                 thirdPartyRegularExpressionBlockList.add(entry);
620
621                                 //Log.i("BlockLists", "Third-party regular expression block list added: " + entry);
622                             } else {  // There are two or more entries.
623                                 int wildcardIndex = entry.indexOf("*");
624
625                                 String firstEntry = entry.substring(0, wildcardIndex);
626                                 String secondEntry = entry.substring(wildcardIndex + 1);
627
628                                 if (secondEntry.contains("*")) {  // there are three or more entries.
629                                     int secondWildcardIndex = secondEntry.indexOf("*");
630
631                                     String realSecondEntry = secondEntry.substring(0, secondWildcardIndex);
632                                     String thirdEntry = secondEntry.substring(secondWildcardIndex + 1);
633
634                                     if (thirdEntry.contains("*")) {  // Process a third-party quadruple entry.
635                                         int thirdWildcardIndex = thirdEntry.indexOf("*");
636
637                                         String realThirdEntry = thirdEntry.substring(0, thirdWildcardIndex);
638                                         String fourthEntry = thirdEntry.substring(thirdWildcardIndex + 1);
639
640                                         String[] thirdPartyQuadrupleEntry = {firstEntry, realSecondEntry, realThirdEntry, fourthEntry};
641
642                                         thirdPartyMultiEntryBlockList.add(thirdPartyQuadrupleEntry);
643
644                                         //Log.i("BlockLists", "Third-party multi-entry block list added: " + firstEntry + " , " + realSecondEntry + " , " + realThirdEntry + " , " + fourthEntry);
645                                     } else {  // Process a third-party triple entry.
646                                         String[] thirdPartyTripleEntry = {firstEntry, realSecondEntry, thirdEntry};
647
648                                         thirdPartyMultiEntryBlockList.add(thirdPartyTripleEntry);
649
650                                         //Log.i("BlockLists", "Third-party multi-entry block list added: " + firstEntry + " , " + realSecondEntry + " , " + thirdEntry);
651                                     }
652                                 } else {  // Process a third-party double entry.
653                                     String[] thirdPartyDoubleEntry = {firstEntry, secondEntry};
654
655                                     thirdPartyMultiEntryBlockList.add(thirdPartyDoubleEntry);
656
657                                     //Log.i("BlockLists", "Third-party multi-entry block list added: " + firstEntry + " , " + secondEntry);
658                                 }
659                             }
660                         } else {  // Process standard third party entries.
661                             // Get the entry.
662                             String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
663
664                             // Add the entry to the block list.
665                             thirdPartyBlockList.add(entry);
666
667                             //Log.i("BlockLists", "Third party block list added: " + entry);
668                         }
669                     } else if (blockListEntry.substring(blockListEntry.indexOf("$")).contains("domain")) {
670                         if (blockListEntry.contains("~")) {  // Whitelist.
671                             // Separate the filters.
672                             String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
673                             String filters = blockListEntry.substring(blockListEntry.indexOf("$") + 1);
674                             String domains = filters.substring(filters.indexOf("domain=") + 7);
675
676                             // Strip any final `*` from the entry.  They are redundant.
677                             if (entry.endsWith("*")) {
678                                 entry = entry.substring(0, entry.length() - 1);
679                             }
680
681                             // Process each domain.
682                             do {
683                                 String domain;
684
685                                 if (domains.contains("|")) {
686                                     // Get the first domain
687                                     domain = domains.substring(0, domains.indexOf("|"));
688
689                                     // Remove the first domain from the list.
690                                     domains = domains.substring(domains.indexOf("|") + 1);
691                                 } else {
692                                     domain = domains;
693                                 }
694
695                                 // Strip the initial `~`.
696                                 domain = domain.substring(1);
697
698                                 if (entry.contains("*")) {  // Process a double entry.
699                                     int wildcardIndex = entry.indexOf("*");
700
701                                     String firstEntry = entry.substring(0, wildcardIndex);
702                                     String secondEntry = entry.substring(wildcardIndex + 1);
703
704                                     String[] domainDoubleEntry = {firstEntry, secondEntry};
705
706                                     domainWhiteList.add(domainDoubleEntry);
707
708                                     //Log.i("BlockLists", "Domain white list added: " + domain + " , " + firstEntry + " , " + secondEntry);
709                                 } else {  // Process a single entry.
710                                     String[] domainEntry = {domain, entry};
711
712                                     domainWhiteList.add(domainEntry);
713
714                                     //Log.i("BlockLists", "Domain white list added: " + domain + " , " + entry);
715                                 }
716                             } while (domains.contains("|"));
717                         } else {  // The block list entry contains a domain, but not a third party designation and isn't a whitelist.
718                             // Separate the filters.
719                             String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
720                             String filters = blockListEntry.substring(blockListEntry.indexOf("$") + 1);
721                             String domains = filters.substring(filters.indexOf("domain=") + 7);
722
723                             // Only process the block list item if the entry is not null.  Some lines in EasyList begin with `$websocket`, which create a null entry.
724                             if (!entry.equals("")) {
725                                 do {
726                                     String domain;
727
728                                     if (domains.contains("|")) {
729                                         // Get the first domain.
730                                         domain = domains.substring(0, domains.indexOf("|"));
731
732                                         // Remove the first domain from the list.
733                                         domains = domains.substring(domains.indexOf("|") + 1);
734                                     } else {
735                                         domain = domains;
736                                     }
737
738                                     if (entry.contains("*")) {
739                                         int wildcardIndex = entry.indexOf("*");
740
741                                         String firstEntry = entry.substring(0, wildcardIndex);
742                                         String secondEntry = entry.substring(wildcardIndex + 1);
743
744                                         String[] domainDoubleEntry = {domain, firstEntry, secondEntry};
745
746                                         domainBlockList.add(domainDoubleEntry);
747
748                                         //Log.i("BlockLists", "Domain double entry block list added: " + domain + " , " + firstEntry + " , " + secondEntry);
749                                     } else if (entry.startsWith("|")) {
750                                         // Remove the initial `|`;
751                                         String entryBase = entry.substring(1);
752
753                                         //noinspection StatementWithEmptyBody
754                                         if (entryBase.equals("http://") || entryBase.equals("https://")) {
755                                             // Do nothing.  These entries will entirely block the website.
756                                             // Often the original entry blocks `$script` but Privacy Browser does not currently differentiate between scripts and other entries.
757                                         } else {
758                                             String[] domainEntry = {domain, entryBase};
759
760                                             domainInitialBlockList.add(domainEntry);
761
762                                             //Log.i("BlockLists", "Domain initial block list added: " + domain + " , " + entryBase);
763                                         }
764                                     } else if (entry.endsWith("|")) {
765                                         // Remove the final `|`.
766                                         String entryBase = entry.substring(0, entry.length() - 1);
767
768                                         String[] domainEntry = {domain, entryBase};
769
770                                         domainFinalBlockList.add(domainEntry);
771
772                                         //Log.i("BlockLists", "Domain final block list added: " + domain + " , " + entryBase);
773                                     } else if (entry.contains("\\")) {
774                                         String[] domainEntry = {domain, entry};
775
776                                         domainRegularExpressionBlockList.add(domainEntry);
777
778                                         // Log.i("BlockLists", "Domain regular expression block list added: " + domain + " , " + entry);
779                                     } else {
780                                         String[] domainEntry = {domain, entry};
781
782                                         domainBlockList.add(domainEntry);
783
784                                         //Log.i("BlockLists", "Domain block list added: " + domain + " , " + entry);
785                                     }
786                                 } while (domains.contains("|"));
787                             }
788                         }
789                     } else if (blockListEntry.contains("~")) {  // Whitelist entries.
790                         // Remove the filter options.
791                         blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
792
793                         // Strip any trailing `*`.
794                         if (blockListEntry.endsWith("*")) {
795                             blockListEntry = blockListEntry.substring(0, blockListEntry.length() -1);
796                         }
797
798                         if (blockListEntry.contains("*")) {
799                             int wildcardIndex = blockListEntry.indexOf("*");
800
801                             String firstEntry = blockListEntry.substring(0, wildcardIndex);
802                             String secondEntry = blockListEntry.substring(wildcardIndex + 1);
803
804
805                             String[] doubleEntry = {firstEntry, secondEntry};
806
807                             multiEntryWhiteList.add(doubleEntry);
808
809                             //Log.i("BlockLists", "Multi entry white list added: " + firstEntry + " , " + secondEntry);
810                         } else {
811                             mainWhiteList.add(blockListEntry);
812
813                             // Log.i("BlockLists", "Main white list added: " + blockListEntry);
814                         }
815                     } else if (blockListEntry.contains("\\")) {  // Regular expressions.
816                         // Remove the filter options.
817                         blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
818
819                         regularExpressionBlockList.add(blockListEntry);
820
821                         //Log.i("BlockLists", "Regular expression list added: " + blockListEntry);
822                     } else {
823                         // Remove the filter options.
824                         blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
825
826                         // Strip any trailing `*`.  These are redundant.
827                         if (blockListEntry.endsWith("*")) {
828                             blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
829                         }
830
831                         if (blockListEntry.contains("*")) {  // Use a multi entry list.
832                             int wildcardIndex = blockListEntry.indexOf("*");
833
834                             String firstEntry = blockListEntry.substring(0, wildcardIndex);
835                             String secondEntry = blockListEntry.substring(wildcardIndex + 1);
836
837                             // Remove `.*` if it appears at the beginning of the second entry.
838                             if (secondEntry.startsWith(".*")) {
839                                 secondEntry = secondEntry.substring(2);
840                             }
841
842                             // Create a third entry if required.
843                             if (secondEntry.contains("*")) {
844                                 wildcardIndex = secondEntry.indexOf("*");
845
846                                 String thirdEntry = secondEntry.substring(wildcardIndex + 1);
847                                 secondEntry = secondEntry.substring(0, wildcardIndex);
848
849
850                                 if (thirdEntry.endsWith("|")) {
851                                     thirdEntry = thirdEntry.substring(0, thirdEntry.length() - 1);
852
853                                     String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
854
855                                     multiEntryFinalBlockList.add(tripleEntry);
856
857                                     //Log.i("BlockLists", "Multi entry final tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
858                                 } else {
859                                     String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
860
861                                     multiEntryBlockList.add(tripleEntry);
862
863                                     // Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
864                                 }
865                             } else {  // This is a double entry.
866                                 if (firstEntry.startsWith("|")) {
867                                     String[] doubleEntry = {firstEntry.substring(1), secondEntry};
868
869                                     multiEntryInitialBlockList.add(doubleEntry);
870
871                                     //Log.i("BlockLists", "Multi entry initial block list added: " + firstEntry.substring(1) + " , " + secondEntry);
872                                 } else {
873                                     String[] doubleEntry = {firstEntry, secondEntry};
874
875                                     multiEntryBlockList.add(doubleEntry);
876
877                                     //Log.i("BlockLists", "Multi entry block list added: " + firstEntry + " , " + secondEntry);
878                                 }
879                             }
880                         } else if (blockListEntry.startsWith("|")) {  // Populate the initial block list.
881                             // Strip the initial `|`.
882                             blockListEntry = blockListEntry.substring(1);
883
884                             // Populate the initial block list.
885                             initialBlockList.add(blockListEntry);
886
887                             //Log.i("BlockLists", "Initial block list added: " + blockListEntry);
888                         } else {  // Populate the main block list.
889                             mainBlockList.add(blockListEntry);
890
891                             //Log.i("BlockLists", "Main block list added: " + blockListEntry);
892                         }
893                     }
894                 } else {  // Populate the standard lists.
895                     // Strip out any initial `||`.  These will be treated like any other entry.
896                     if (blockListEntry.startsWith("||")) {
897                         blockListEntry = blockListEntry.substring(2);
898                     }
899
900                     // Strip out any initial `*`.
901                     if (blockListEntry.startsWith("*")) {
902                         blockListEntry = blockListEntry.substring(1);
903                     }
904
905                     // Strip out any trailing `*`.
906                     if (blockListEntry.endsWith("*")) {
907                         blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
908                     }
909
910                     if (blockListEntry.contains("*")) {  // Entries that contain a `*` in the middle have to be treated specially.
911                         int wildcardIndex = blockListEntry.indexOf("*");
912
913                         String firstEntry = blockListEntry.substring(0, wildcardIndex);
914                         String secondEntry = blockListEntry.substring(wildcardIndex + 1);
915
916                         // Remove `.*` if it appears at the beginning of the second entry.
917                         if (secondEntry.startsWith(".*")) {
918                             secondEntry = secondEntry.substring(2);
919                         }
920
921                         // Create a third entry if required.
922                         if (secondEntry.contains("*")) {
923                             wildcardIndex = secondEntry.indexOf("*");
924
925                             String thirdEntry = secondEntry.substring(wildcardIndex + 1);
926                             secondEntry = secondEntry.substring(0, wildcardIndex);
927
928                             String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
929
930                             multiEntryBlockList.add(tripleEntry);
931
932                             //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
933                         } else {
934                             if (firstEntry.startsWith("|")) {
935                                 String[] doubleEntry = {firstEntry.substring(1), secondEntry};
936
937                                 multiEntryInitialBlockList.add(doubleEntry);
938
939                                 //Log.i("BlockLists", "Multi entry initial block list added: " + firstEntry.substring(1) + " , " + secondEntry);
940                             } else {
941                                 String[] doubleEntry = {firstEntry, secondEntry};
942
943                                 multiEntryBlockList.add(doubleEntry);
944
945                                 //Log.i("BlockLists", "Multi entry block list added: " + firstEntry + " , " + secondEntry);
946                             }
947                         }
948                     } else {  // This is a basic entry.
949                         // Add the modified block list entry to the main block list.
950                         mainBlockList.add(blockListEntry);
951
952                         //Log.i("BlockLists", "Main block list added: " + blockListEntry);
953                     }
954                 }
955             }
956
957             // Close `bufferedReader`.
958             bufferedReader.close();
959         } catch (IOException e) {
960             // The asset exists, so the `IOException` will never be thrown.
961         }
962
963         Log.i("BlockLists", "Finish populating block lists");
964
965         // Set the content view.
966         setContentView(R.layout.main_drawerlayout);
967
968         // Get a handle for `inputMethodManager`.
969         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
970
971         // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
972         supportAppBar = findViewById(R.id.app_bar);
973         setSupportActionBar(supportAppBar);
974         appBar = getSupportActionBar();
975
976         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
977         assert appBar != null;
978
979         // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
980         appBar.setCustomView(R.layout.url_app_bar);
981         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
982
983         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
984         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
985         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
986         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
987
988         // Get a handle for `urlTextBox`.
989         urlTextBox = findViewById(R.id.url_edittext);
990
991         // Remove the formatting from `urlTextBar` when the user is editing the text.
992         urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
993             if (hasFocus) {  // The user is editing `urlTextBox`.
994                 // Remove the highlighting.
995                 urlTextBox.getText().removeSpan(redColorSpan);
996                 urlTextBox.getText().removeSpan(initialGrayColorSpan);
997                 urlTextBox.getText().removeSpan(finalGrayColorSpan);
998             } else {  // The user has stopped editing `urlTextBox`.
999                 // Reapply the highlighting.
1000                 highlightUrlText();
1001             }
1002         });
1003
1004         // Set the go button on the keyboard to load the URL in `urlTextBox`.
1005         urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
1006             // If the event is a key-down event on the `enter` button, load the URL.
1007             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
1008                 // Load the URL into the mainWebView and consume the event.
1009                 try {
1010                     loadUrlFromTextBox();
1011                 } catch (UnsupportedEncodingException e) {
1012                     e.printStackTrace();
1013                 }
1014                 // If the enter key was pressed, consume the event.
1015                 return true;
1016             } else {
1017                 // If any other key was pressed, do not consume the event.
1018                 return false;
1019             }
1020         });
1021
1022         // Set `waitingForOrbotHTMLString`.
1023         waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
1024
1025         // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
1026         currentDomainName = "";
1027         orbotStatus = "unknown";
1028         waitingForOrbot = false;
1029
1030         // Create an Orbot status `BroadcastReceiver`.
1031         BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
1032             @Override
1033             public void onReceive(Context context, Intent intent) {
1034                 // Store the content of the status message in `orbotStatus`.
1035                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
1036
1037                 // If we are waiting on Orbot, load the website now that Orbot is connected.
1038                 if (orbotStatus.equals("ON") && waitingForOrbot) {
1039                     // Reset `waitingForOrbot`.
1040                     waitingForOrbot = false;
1041
1042                     // Load `formattedUrlString
1043                     loadUrl(formattedUrlString);
1044                 }
1045             }
1046         };
1047
1048         // Register `orbotStatusBroadcastReceiver` on `this` context.
1049         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
1050
1051         // Get handles for views that need to be accessed.
1052         drawerLayout = findViewById(R.id.drawerlayout);
1053         rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
1054         bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
1055         bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
1056         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
1057         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
1058         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
1059         mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
1060         mainWebView = findViewById(R.id.main_webview);
1061         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1062         findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1063         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
1064         urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
1065         favoriteIconImageView = findViewById(R.id.favorite_icon);
1066
1067         // 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.
1068         if (darkTheme) {
1069             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
1070             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
1071             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
1072             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
1073         } else {
1074             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
1075             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
1076             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
1077             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
1078         }
1079
1080         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
1081         launchBookmarksActivityFab.setOnClickListener(v -> {
1082             // Create an intent to launch the bookmarks activity.
1083             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
1084
1085             // Include the current folder with the `Intent`.
1086             bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
1087
1088             // Make it so.
1089             startActivity(bookmarksIntent);
1090         });
1091
1092         // Set the create new bookmark folder FAB to display the `AlertDialog`.
1093         createBookmarkFolderFab.setOnClickListener(v -> {
1094             // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
1095             AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
1096             createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
1097         });
1098
1099         // Set the create new bookmark FAB to display the `AlertDialog`.
1100         createBookmarkFab.setOnClickListener(view -> {
1101             // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
1102             AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
1103             createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
1104         });
1105
1106         // Create a double-tap listener to toggle full-screen mode.
1107         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
1108             // Override `onDoubleTap()`.  All other events are handled using the default settings.
1109             @Override
1110             public boolean onDoubleTap(MotionEvent event) {
1111                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
1112                     // Toggle `inFullScreenBrowsingMode`.
1113                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
1114
1115                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
1116                         // Hide the `appBar`.
1117                         appBar.hide();
1118
1119                         // Hide the `BannerAd` in the free flavor.
1120                         if (BuildConfig.FLAVOR.contentEquals("free")) {
1121                             BannerAd.hideAd(adView);
1122                         }
1123
1124                         // Modify the system bars.
1125                         if (hideSystemBarsOnFullscreen) {  // Hide everything.
1126                             // Remove the translucent overlays.
1127                             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1128
1129                             // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1130                             drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1131
1132                             /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1133                              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1134                              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1135                              */
1136                             rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1137
1138                             // Set `rootCoordinatorLayout` to fill the whole screen.
1139                             rootCoordinatorLayout.setFitsSystemWindows(false);
1140                         } else {  // Hide everything except the status and navigation bars.
1141                             // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
1142                             rootCoordinatorLayout.setFitsSystemWindows(false);
1143
1144                             // 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.
1145                             if (translucentNavigationBarOnFullscreen) {
1146                                 // Set the navigation bar to be translucent.
1147                                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1148                             }
1149                         }
1150                     } else {  // Switch to normal viewing mode.
1151                         // Show the `appBar`.
1152                         appBar.show();
1153
1154                         // Show the `BannerAd` in the free flavor.
1155                         if (BuildConfig.FLAVOR.contentEquals("free")) {
1156                             // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
1157                             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1158
1159                             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1160                             adView = findViewById(R.id.adview);
1161                         }
1162
1163                         // Remove the translucent navigation bar flag if it is set.
1164                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1165
1166                         // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1167                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1168
1169                         // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1170                         rootCoordinatorLayout.setSystemUiVisibility(0);
1171
1172                         // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1173                         rootCoordinatorLayout.setFitsSystemWindows(true);
1174                     }
1175
1176                     // Consume the double-tap.
1177                     return true;
1178                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
1179                     return false;
1180                 }
1181             }
1182         });
1183
1184         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
1185         mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
1186             // Call `performClick()` on the view, which is required for accessibility.
1187             v.performClick();
1188
1189             // Send the `event` to `gestureDetector`.
1190             return gestureDetector.onTouchEvent(event);
1191         });
1192
1193         // Update `findOnPageCountTextView`.
1194         mainWebView.setFindListener(new WebView.FindListener() {
1195             // Get a handle for `findOnPageCountTextView`.
1196             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
1197
1198             @Override
1199             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
1200                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
1201                     // Set `findOnPageCountTextView` to `0/0`.
1202                     findOnPageCountTextView.setText(R.string.zero_of_zero);
1203                 } else if (isDoneCounting) {  // There are matches.
1204                     // `activeMatchOrdinal` is zero-based.
1205                     int activeMatch = activeMatchOrdinal + 1;
1206
1207                     // Build the match string.
1208                     String matchString = activeMatch + "/" + numberOfMatches;
1209
1210                     // Set `findOnPageCountTextView`.
1211                     findOnPageCountTextView.setText(matchString);
1212                 }
1213             }
1214         });
1215
1216         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
1217         findOnPageEditText.addTextChangedListener(new TextWatcher() {
1218             @Override
1219             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1220                 // Do nothing.
1221             }
1222
1223             @Override
1224             public void onTextChanged(CharSequence s, int start, int before, int count) {
1225                 // Do nothing.
1226             }
1227
1228             @Override
1229             public void afterTextChanged(Editable s) {
1230                 // Search for the text in `mainWebView`.
1231                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
1232             }
1233         });
1234
1235         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
1236         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
1237             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
1238                 // Hide the soft keyboard.  `0` indicates no additional flags.
1239                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1240
1241                 // Consume the event.
1242                 return true;
1243             } else {  // A different key was pressed.
1244                 // Do not consume the event.
1245                 return false;
1246             }
1247         });
1248
1249         // Implement swipe to refresh
1250         swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
1251         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
1252         swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
1253
1254         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
1255         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
1256         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
1257
1258         // Listen for touches on the navigation menu.
1259         final NavigationView navigationView = findViewById(R.id.navigationview);
1260         navigationView.setNavigationItemSelectedListener(this);
1261
1262         // 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.
1263         final Menu navigationMenu = navigationView.getMenu();
1264         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
1265         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
1266         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
1267
1268         // Initialize the bookmarks database helper.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
1269         // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
1270         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
1271
1272         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
1273         currentBookmarksFolder = "";
1274
1275         // Load the home folder, which is `""` in the database.
1276         loadBookmarksFolder();
1277
1278         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
1279             // Convert the id from long to int to match the format of the bookmarks database.
1280             int databaseID = (int) id;
1281
1282             // Get the bookmark `Cursor` for this ID and move it to the first row.
1283             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
1284             bookmarkCursor.moveToFirst();
1285
1286             // Act upon the bookmark according to the type.
1287             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
1288                 // Store the new folder name in `currentBookmarksFolder`.
1289                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1290
1291                 // Load the new folder.
1292                 loadBookmarksFolder();
1293             } else {  // The selected bookmark is not a folder.
1294                 // Load the bookmark URL.
1295                 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
1296
1297                 // Close the bookmarks drawer.
1298                 drawerLayout.closeDrawer(GravityCompat.END);
1299             }
1300
1301             // Close the `Cursor`.
1302             bookmarkCursor.close();
1303         });
1304
1305         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
1306             // Convert the database ID from `long` to `int`.
1307             int databaseId = (int) id;
1308
1309             // Find out if the selected bookmark is a folder.
1310             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
1311
1312             if (isFolder) {
1313                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
1314                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1315
1316                 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
1317                 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
1318                 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
1319             } else {
1320                 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
1321                 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
1322                 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
1323             }
1324
1325             // Consume the event.
1326             return true;
1327         });
1328
1329         // The `DrawerListener` allows us to update the Navigation Menu.
1330         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
1331             @Override
1332             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
1333             }
1334
1335             @Override
1336             public void onDrawerOpened(@NonNull View drawerView) {
1337             }
1338
1339             @Override
1340             public void onDrawerClosed(@NonNull View drawerView) {
1341             }
1342
1343             @Override
1344             public void onDrawerStateChanged(int newState) {
1345                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // The drawer is opening or closing.
1346                     // Update the `Back`, `Forward`, and `History` menu items.
1347                     navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
1348                     navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
1349                     navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
1350
1351                     // Hide the keyboard (if displayed) so we can see the navigation menu.  `0` indicates no additional flags.
1352                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1353
1354                     // Clear the focus from `urlTextBox` if it has it.
1355                     urlTextBox.clearFocus();
1356                 }
1357             }
1358         });
1359
1360         // drawerToggle creates the hamburger icon at the start of the AppBar.
1361         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
1362
1363         mainWebView.setWebViewClient(new WebViewClient() {
1364             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1365             // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
1366             @SuppressWarnings("deprecation")
1367             @Override
1368             public boolean shouldOverrideUrlLoading(WebView view, String url) {
1369                 if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
1370                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1371                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1372
1373                     // Parse the url and set it as the data for the `Intent`.
1374                     emailIntent.setData(Uri.parse(url));
1375
1376                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1377                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1378
1379                     // Make it so.
1380                     startActivity(emailIntent);
1381
1382                     // Returning `true` indicates the application is handling the URL.
1383                     return true;
1384                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
1385                     // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
1386                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1387
1388                     // Add the phone number to the intent.
1389                     dialIntent.setData(Uri.parse(url));
1390
1391                     // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
1392                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1393
1394                     // Make it so.
1395                     startActivity(dialIntent);
1396
1397                     // Returning `true` indicates the application is handling the URL.
1398                     return true;
1399                 } else {  // Load the URL in Privacy Browser.
1400                     // Apply the domain settings for the new URL.
1401                     applyDomainSettings(url);
1402
1403                     // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1404                     return false;
1405                 }
1406             }
1407
1408             // Check requests against the block lists.  The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1409             @SuppressWarnings("deprecation")
1410             @Override
1411             public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1412                 if (adBlockerEnabled) {  // Check the block lists.
1413                     Log.i("BlockLists", "Begin check for " + url);
1414
1415                     Uri currentUri = Uri.parse(formattedUrlString);
1416                     String currentDomain = currentUri.getHost();
1417
1418                     Uri requestUri = Uri.parse(url);
1419                     String requestDomain = requestUri.getHost();
1420
1421                     boolean thirdPartyRequest = !requestDomain.equals(currentDomain);
1422
1423                     WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1424
1425                     for (String whiteListEntry : mainWhiteList) {
1426                         if (url.contains(whiteListEntry)) {
1427                             Log.i("BlockLists", "Request allowed by main white list: " + whiteListEntry + " | " + url);
1428
1429                             // `Return null` loads the requested resource.
1430                             return null;
1431                         }
1432                     }
1433
1434                     for (String[] whiteListEntry : multiEntryWhiteList) {
1435                         if (whiteListEntry.length == 2) {  // There are two entries.
1436                             if (url.contains(whiteListEntry[0]) && url.contains(whiteListEntry[1])) {
1437                                 Log.i("BlockLists", "Request allowed by multi entry white list:  " + whiteListEntry[0] + " , " + whiteListEntry[1] + " | " + url);
1438
1439                                 // `Return null` loads the requested resource.
1440                                 return null;
1441                             }
1442                         } else {  // There are three entries.
1443                             if (url.contains(whiteListEntry[0]) && url.contains(whiteListEntry[1]) && url.contains(whiteListEntry[2])) {
1444                                 Log.i("BlockLists", "Request allowed by multi entry white list:  " + whiteListEntry[0] + " , " + whiteListEntry[1] + " , " + whiteListEntry[2] + " | " + url);
1445
1446                                 // `Return null` loads the requested resource.
1447                                 return null;
1448                             }
1449                         }
1450                     }
1451
1452                     for (String[] whiteListEntry : domainWhiteList) {
1453                         if (requestDomain.endsWith(whiteListEntry[0]) && url.contains(whiteListEntry[1])) {
1454                             Log.i("BlockLists", "Request allowed by domain white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " | " + url);
1455
1456                             // `Return null` loads the requested resource.
1457                             return null;
1458                         }
1459                     }
1460
1461                     // Only check the third-party white lists if this is a third-party request.
1462                     if (thirdPartyRequest) {
1463                         for (String[] whiteListEntry : thirdPartyDomainWhiteList) {
1464                             if (requestDomain.endsWith(whiteListEntry[0]) && url.contains(whiteListEntry[1])) {
1465                                 Log.i("BlockLists", "Request allowed by third-party domain white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " | " + url);
1466
1467                                 // `Return null` loads the requested resource.
1468                                 return null;
1469                             }
1470                         }
1471                     }
1472
1473                     for (String blockListEntry : mainBlockList) {
1474                         if (url.contains(blockListEntry)) {
1475                             Log.i("BlockLists", "Request blocked by main block list: " + blockListEntry + " | " + url);
1476
1477                             // Return an empty `WebResourceResponse`.
1478                             return emptyWebResourceResponse;
1479                         }
1480                     }
1481
1482                     for (String blockListEntry : initialBlockList) {
1483                         if (url.startsWith(blockListEntry)) {
1484                             Log.i("BlockLists", "Request blocked by initial block list: " + blockListEntry + " | " + url);
1485
1486                             // Return an empty `WebResourceResponse`.
1487                             return emptyWebResourceResponse;
1488                         }
1489                     }
1490
1491                     for (String blockListEntry : finalBlockList) {
1492                         if (url.endsWith(blockListEntry)) {
1493                             Log.i("BlockLists", "Request blocked by final block list: " + blockListEntry + " | " + url);
1494
1495                             // Return an empty `WebResourceResponse`.
1496                             return emptyWebResourceResponse;
1497                         }
1498                     }
1499
1500                     for (String[] blockListEntry : multiEntryBlockList) {
1501                         if (blockListEntry.length == 2) {  // There are two entries.
1502                             if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1503                                 Log.i("BlockLists", "Request blocked by multi entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1504
1505                                 // Return an empty `WebResourceResponse`.
1506                                 return emptyWebResourceResponse;
1507                             }
1508                         } else {  // There are three entries.
1509                             if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1510                                 Log.i("BlockLists", "Request blocked by multi entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] + " | " + url);
1511
1512                                 // Return an empty `WebResourceResponse`.
1513                                 return emptyWebResourceResponse;
1514                             }
1515                         }
1516                     }
1517
1518                     for (String[] blockListEntry : multiEntryInitialBlockList) {
1519                         if (url.startsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1520                             Log.i("BlockLists", "Request blocked by multi entry initial block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1521
1522                             // Return an empty `WebResourceResponse`.
1523                             return emptyWebResourceResponse;
1524                         }
1525                     }
1526
1527                     for (String[] blockListEntry : multiEntryFinalBlockList) {
1528                         if (url.contains(blockListEntry[0]) && url.endsWith(blockListEntry[1])) {
1529                             Log.i("BlockLists", "Request blocked by multi entry final block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1530
1531                             // Return an empty `WebResourceResponse`.
1532                             return emptyWebResourceResponse;
1533                         }
1534                     }
1535
1536                     for (String[] blockListEntry : domainBlockList) {
1537                         if (blockListEntry.length == 2) {  // There is one entry.
1538                             if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1539                                 Log.i("BlockLists", "Request blocked by domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1540
1541                                 // Return an empty `WebResourceResponse`.
1542                                 return emptyWebResourceResponse;
1543                             }
1544                         } else { // There are two entries.
1545                             if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1546                                 Log.i("BlockLists", "Request blocked by domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] + " | " + url);
1547
1548                                 // Return an empty `WebResourceResponse`.
1549                                 return emptyWebResourceResponse;
1550                             }
1551                         }
1552                     }
1553
1554                     for (String[] blockListEntry : domainInitialBlockList) {
1555                         if (requestDomain.endsWith(blockListEntry[0]) && url.startsWith(blockListEntry[1])) {
1556                             Log.i("BlockLists", "Request blocked by domain initial block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1557
1558                             // Return an empty `WebResourceResponse`.
1559                             return emptyWebResourceResponse;
1560                         }
1561                     }
1562
1563                     for (String[] blockListEntry : domainFinalBlockList) {
1564                         if (requestDomain.endsWith(blockListEntry[0]) && url.endsWith(blockListEntry[2])) {
1565                             Log.i("BlockLists", "Request blocked by domain final block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1566
1567                             // Return an empty `WebResourceResponse`.
1568                             return emptyWebResourceResponse;
1569                         }
1570                     }
1571
1572                     for (String[] blockListEntry : domainRegularExpressionBlockList) {
1573                         if (requestDomain.endsWith(blockListEntry[0]) && Pattern.matches(blockListEntry[1], url)) {
1574                             Log.i("BlockLists", "Request blocked by domain regular expression block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1575
1576                             // Return an empty `WebResourceResponse`.
1577                             return emptyWebResourceResponse;
1578                         }
1579                     }
1580
1581                     // Only check the third-party block lists if this is a third-party request.
1582                     if (thirdPartyRequest) {
1583                         for (String blockListEntry : thirdPartyBlockList) {
1584                             if (url.contains(blockListEntry)) {
1585                                 Log.i("BlockLists", "Request blocked by third-party block list: " + blockListEntry + " | " + url);
1586
1587                                 // Return an empty `WebResourceResponse`.
1588                                 return emptyWebResourceResponse;
1589                             }
1590                         }
1591
1592                         for (String blockListEntry : thirdPartyInitialBlockList) {
1593                             if (url.startsWith(blockListEntry)) {
1594                                 Log.i("BlockLists", "Request blocked by third-party initial block list: " + blockListEntry + " | " + url);
1595
1596                                 // Return an empty `WebResourceResponse`.
1597                                 return emptyWebResourceResponse;
1598                             }
1599                         }
1600
1601                         for (String[] blockListEntry : thirdPartyMultiEntryBlockList) {
1602                             switch (blockListEntry.length) {
1603                                 case 2:  // There are two entries.
1604                                     if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1605                                         Log.i("BlockLists", "Request blocked by third-party multi-entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1606
1607                                         // Return an empty `WebResourceResponse`.
1608                                         return emptyWebResourceResponse;
1609                                     }
1610                                     break;
1611
1612                                 case 3:  // There are three entries.
1613                                     if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1614                                         Log.i("BlockLists", "Request blocked by third-party multi-entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] +
1615                                                 " | " + url);
1616
1617                                         // Return an empty `WebResourceResponse`.
1618                                         return emptyWebResourceResponse;
1619                                     }
1620                                     break;
1621
1622                                 case 4:  // There are four entries.
1623                                     if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2]) && url.contains(blockListEntry[3])) {
1624                                         Log.i("BlockLists", "Request blocked by third-party multi-entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] +
1625                                                 " , " + blockListEntry[3] + " | " + url);
1626
1627                                         // Return an empty `WebResourceResponse`.
1628                                         return emptyWebResourceResponse;
1629                                     }
1630                                     break;
1631                             }
1632                         }
1633
1634                         for (String[] blockListEntry : thirdPartyMultiEntryInitialBlockList) {
1635                             if (url.startsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1636                                 Log.i("BlockLists", "Request blocked by third-party multi-entry initial block list");
1637
1638                                 // Return an empty `WebResourceResponse`.
1639                                 return emptyWebResourceResponse;
1640                             }
1641                         }
1642
1643                         for (String[] blockListEntry : thirdPartyDomainBlockList) {
1644                             if (blockListEntry.length == 2) {  // There is one entry.
1645                                 if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1646                                     Log.i("BlockLists", "Request blocked by third-party domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1647
1648                                     // Return an empty `WebResourceResponse`.
1649                                     return emptyWebResourceResponse;
1650                                 }
1651                             } else { // There are two entries.
1652                                 if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1653                                     Log.i("BlockLists", "Request blocked by third-party domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] +  " , " + blockListEntry[2] + " | " +
1654                                             url);
1655
1656                                     // Return an empty `WebResourceResponse`.
1657                                     return emptyWebResourceResponse;
1658                                 }
1659                             }
1660                         }
1661
1662                         for (String blockListEntry : thirdPartyRegularExpressionBlockList) {
1663                             if (Pattern.matches(blockListEntry, url)) {
1664                                 Log.i("BlockLists", "Request blocked by third-party regular expression block list: " + blockListEntry + " | " + url);
1665
1666                                 // Return an empty `WebResourceResponse`.
1667                                 return emptyWebResourceResponse;
1668                             }
1669                         }
1670                     }
1671
1672                     for (String blockListEntry : regularExpressionBlockList) {
1673                         if (Pattern.matches(blockListEntry, url)) {
1674                             Log.i("BlockLists", "Request blocked by regular expression block list: " + blockListEntry + " | " + url);
1675
1676                             // Return an empty `WebResourceResponse`.
1677                             return emptyWebResourceResponse;
1678                         }
1679                     }
1680
1681                     Log.i("BlockLists", "End check for " + url);
1682
1683                     // `return null` loads the requested resource.
1684                     return null;
1685                 } else {  // Ad blocking is disabled.
1686                     // `return null` loads the requested resource.
1687                     return null;
1688                 }
1689             }
1690
1691             // Handle HTTP authentication requests.
1692             @Override
1693             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1694                 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1695                 httpAuthHandler = handler;
1696
1697                 // Display the HTTP authentication dialog.
1698                 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1699                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1700             }
1701
1702             // Update the URL in urlTextBox when the page starts to load.
1703             @Override
1704             public void onPageStarted(WebView view, String url, Bitmap favicon) {
1705                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1706                 if (nightMode) {
1707                     mainWebView.setVisibility(View.INVISIBLE);
1708                 }
1709
1710                 // Hide the keyboard.  `0` indicates no additional flags.
1711                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1712
1713                 // Check to see if we are waiting on Orbot.
1714                 if (!waitingForOrbot) {  // We are not waiting on Orbot, so we need to process the URL.
1715                     // 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.
1716                     formattedUrlString = url;
1717
1718                     // Display the formatted URL text.
1719                     urlTextBox.setText(formattedUrlString);
1720
1721                     // Apply text highlighting to `urlTextBox`.
1722                     highlightUrlText();
1723
1724                     // Apply any custom domain settings if the URL was loaded by navigating history.
1725                     if (navigatingHistory) {
1726                         applyDomainSettings(url);
1727                     }
1728
1729                     // 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.
1730                     urlIsLoading = true;
1731                 }
1732             }
1733
1734             // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1735             @Override
1736             public void onPageFinished(WebView view, String url) {
1737                 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1738                 urlIsLoading = false;
1739
1740                 // Clear the cache and history if Incognito Mode is enabled.
1741                 if (incognitoModeEnabled) {
1742                     // Clear the cache.  `true` includes disk files.
1743                     mainWebView.clearCache(true);
1744
1745                     // Clear the back/forward history.
1746                     mainWebView.clearHistory();
1747
1748                     // Manually delete cache folders.
1749                     try {
1750                         // Delete the main `cache` folder.
1751                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1752
1753                         // Delete the `app_webview` folder, which contains an additional `WebView` cache.  See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1754                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1755                     } catch (IOException e) {
1756                         // Do nothing if an error is thrown.
1757                     }
1758                 }
1759
1760                 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1761                 if (!waitingForOrbot) {
1762                     // Check to see if `WebView` has set `url` to be `about:blank`.
1763                     if (url.equals("about:blank")) {  // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1764                         // Set `formattedUrlString` to `""`.
1765                         formattedUrlString = "";
1766
1767                         urlTextBox.setText(formattedUrlString);
1768
1769                         // Request focus for `urlTextBox`.
1770                         urlTextBox.requestFocus();
1771
1772                         // Display the keyboard.
1773                         inputMethodManager.showSoftInput(urlTextBox, 0);
1774
1775                         // Apply the domain settings.  This clears any settings from the previous domain.
1776                         applyDomainSettings(formattedUrlString);
1777                     } else {  // `WebView` has loaded a webpage.
1778                         // Set `formattedUrlString`.
1779                         formattedUrlString = url;
1780
1781                         // Only update `urlTextBox` if the user is not typing in it.
1782                         if (!urlTextBox.hasFocus()) {
1783                             // Display the formatted URL text.
1784                             urlTextBox.setText(formattedUrlString);
1785
1786                             // Apply text highlighting to `urlTextBox`.
1787                             highlightUrlText();
1788                         }
1789                     }
1790
1791                     // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1792                     sslCertificate = mainWebView.getCertificate();
1793
1794                     // 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.
1795                     if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1796                         // Initialize the current SSL certificate variables.
1797                         String currentWebsiteIssuedToCName = "";
1798                         String currentWebsiteIssuedToOName = "";
1799                         String currentWebsiteIssuedToUName = "";
1800                         String currentWebsiteIssuedByCName = "";
1801                         String currentWebsiteIssuedByOName = "";
1802                         String currentWebsiteIssuedByUName = "";
1803                         Date currentWebsiteSslStartDate = null;
1804                         Date currentWebsiteSslEndDate = null;
1805
1806
1807                         // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1808                         if (sslCertificate != null) {
1809                             currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1810                             currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1811                             currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1812                             currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1813                             currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1814                             currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1815                             currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1816                             currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1817                         }
1818
1819                         // 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`.
1820                         String currentWebsiteSslStartDateString = "";
1821                         String currentWebsiteSslEndDateString = "";
1822                         String pinnedDomainSslStartDateString = "";
1823                         String pinnedDomainSslEndDateString = "";
1824
1825                         // Convert the `Dates` to `Strings` if they are not `null`.
1826                         if (currentWebsiteSslStartDate != null) {
1827                             currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1828                         }
1829
1830                         if (currentWebsiteSslEndDate != null) {
1831                             currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1832                         }
1833
1834                         if (pinnedDomainSslStartDate != null) {
1835                             pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1836                         }
1837
1838                         if (pinnedDomainSslEndDate != null) {
1839                             pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1840                         }
1841
1842                         // Check to see if the pinned SSL certificate matches the current website certificate.
1843                         if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1844                                 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1845                                 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1846                                 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1847                                 // The pinned SSL certificate doesn't match the current domain certificate.
1848                             //Display the pinned SSL certificate mismatch `AlertDialog`.
1849                             AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1850                             pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1851                         }
1852                     }
1853                 }
1854             }
1855
1856             // Handle SSL Certificate errors.
1857             @Override
1858             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1859                 // Get the current website SSL certificate.
1860                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1861
1862                 // Extract the individual pieces of information from the current website SSL certificate.
1863                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1864                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1865                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1866                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1867                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1868                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1869                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1870                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1871
1872                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1873                 if (pinnedDomainSslCertificate &&
1874                         currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1875                         currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1876                         currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1877                         currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1878                         // An SSL certificate is pinned and matches the current domain certificate.
1879                     // Proceed to the website without displaying an error.
1880                     handler.proceed();
1881                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1882                     // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1883                     sslErrorHandler = handler;
1884
1885                     // Display the SSL error `AlertDialog`.
1886                     AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1887                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1888                 }
1889             }
1890         });
1891
1892         // Get a handle for the progress bar.
1893         final ProgressBar progressBar = findViewById(R.id.progress_bar);
1894
1895         mainWebView.setWebChromeClient(new WebChromeClient() {
1896             // Update the progress bar when a page is loading.
1897             @Override
1898             public void onProgressChanged(WebView view, int progress) {
1899                 // Inject the night mode CSS if night mode is enabled.
1900                 if (nightMode) {
1901                     // `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
1902                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
1903                     // `border: none` removes all borders, which can also be used to underline text.
1904                     // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
1905                     mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
1906                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
1907                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
1908                                 // Initialize a `Handler` to display `mainWebView`.
1909                                 Handler displayWebViewHandler = new Handler();
1910
1911                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1912                                 Runnable displayWebViewRunnable = () -> {
1913                                     // Only display `mainWebView` if the progress bar is one.  This prevents the display of the `WebView` while it is still loading.
1914                                     if (progressBar.getVisibility() == View.GONE) {
1915                                         mainWebView.setVisibility(View.VISIBLE);
1916                                     }
1917                                 };
1918
1919                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1920                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1921                             });
1922                 }
1923
1924                 // Update the progress bar.
1925                 progressBar.setProgress(progress);
1926
1927                 // Set the visibility of the progress bar.
1928                 if (progress < 100) {
1929                     // Show the progress bar.
1930                     progressBar.setVisibility(View.VISIBLE);
1931                 } else {
1932                     // Hide the progress bar.
1933                     progressBar.setVisibility(View.GONE);
1934
1935                     // Display `mainWebView` if night mode is disabled.
1936                     // 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
1937                     // currently enabled.
1938                     if (!nightMode) {
1939                         mainWebView.setVisibility(View.VISIBLE);
1940                     }
1941
1942                     //Stop the `SwipeToRefresh` indicator if it is running
1943                     swipeRefreshLayout.setRefreshing(false);
1944                 }
1945             }
1946
1947             // Set the favorite icon when it changes.
1948             @Override
1949             public void onReceivedIcon(WebView view, Bitmap icon) {
1950                 // Only update the favorite icon if the website has finished loading.
1951                 if (progressBar.getVisibility() == View.GONE) {
1952                     // Save a copy of the favorite icon.
1953                     favoriteIconBitmap = icon;
1954
1955                     // Place the favorite icon in the appBar.
1956                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1957                 }
1958             }
1959
1960             // Save a copy of the title when it changes.
1961             @Override
1962             public void onReceivedTitle(WebView view, String title) {
1963                 // Save a copy of the title.
1964                 webViewTitle = title;
1965             }
1966
1967             // Enter full screen video
1968             @Override
1969             public void onShowCustomView(View view, CustomViewCallback callback) {
1970                 // Pause the ad if this is the free flavor.
1971                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1972                     BannerAd.pauseAd(adView);
1973                 }
1974
1975                 // Remove the translucent overlays.
1976                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1977
1978                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1979                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1980
1981                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1982                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1983                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1984                  */
1985                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1986
1987                 // Set `rootCoordinatorLayout` to fill the entire screen.
1988                 rootCoordinatorLayout.setFitsSystemWindows(false);
1989
1990                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1991                 fullScreenVideoFrameLayout.addView(view);
1992                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1993             }
1994
1995             // Exit full screen video
1996             public void onHideCustomView() {
1997                 // Hide `fullScreenVideoFrameLayout`.
1998                 fullScreenVideoFrameLayout.removeAllViews();
1999                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2000
2001                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2002                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2003
2004                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
2005                 rootCoordinatorLayout.setFitsSystemWindows(true);
2006
2007                 // Show the ad if this is the free flavor.
2008                 if (BuildConfig.FLAVOR.contentEquals("free")) {
2009                     // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
2010                     BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2011
2012                     // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2013                     adView = findViewById(R.id.adview);
2014                 }
2015             }
2016         });
2017
2018         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
2019         registerForContextMenu(mainWebView);
2020
2021         // Allow the downloading of files.
2022         mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
2023             // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
2024             AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
2025             downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2026         });
2027
2028         // Allow pinch to zoom.
2029         mainWebView.getSettings().setBuiltInZoomControls(true);
2030
2031         // Hide zoom controls.
2032         mainWebView.getSettings().setDisplayZoomControls(false);
2033
2034         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
2035         mainWebView.getSettings().setUseWideViewPort(true);
2036
2037         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
2038         mainWebView.getSettings().setLoadWithOverviewMode(true);
2039
2040         // Explicitly disable geolocation.
2041         mainWebView.getSettings().setGeolocationEnabled(false);
2042
2043         // Initialize cookieManager.
2044         cookieManager = CookieManager.getInstance();
2045
2046         // 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).
2047         customHeaders.put("X-Requested-With", "");
2048
2049         // Initialize the default preference values the first time the program is run.  `this` is the context.  `false` keeps this command from resetting any current preferences back to default.
2050         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
2051
2052         // Get the intent that started the app.
2053         final Intent launchingIntent = getIntent();
2054
2055         // Extract the launching intent data as `launchingIntentUriData`.
2056         final Uri launchingIntentUriData = launchingIntent.getData();
2057
2058         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
2059         if (launchingIntentUriData != null) {
2060             formattedUrlString = launchingIntentUriData.toString();
2061         }
2062
2063         // Get a handle for the `Runtime`.
2064         privacyBrowserRuntime = Runtime.getRuntime();
2065
2066         // Store the application's private data directory.
2067         privateDataDirectoryString = getApplicationInfo().dataDir;
2068         // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
2069
2070         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
2071         inFullScreenBrowsingMode = false;
2072
2073         // Initialize AdView for the free flavor.
2074         adView = findViewById(R.id.adview);
2075
2076         // Initialize the privacy settings variables.
2077         javaScriptEnabled = false;
2078         firstPartyCookiesEnabled = false;
2079         thirdPartyCookiesEnabled = false;
2080         domStorageEnabled = false;
2081         saveFormDataEnabled = false;
2082         nightMode = false;
2083
2084         // Initialize `webViewTitle`.
2085         webViewTitle = getString(R.string.no_title);
2086
2087         // Initialize `favoriteIconBitmap`.  `ContextCompat` must be used until API >= 21.
2088         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
2089         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
2090         assert favoriteIconBitmapDrawable != null;
2091         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
2092
2093         // If the favorite icon is null, load the default.
2094         if (favoriteIconBitmap == null) {
2095             favoriteIconBitmap = favoriteIconDefaultBitmap;
2096         }
2097
2098         // Apply the app settings from the shared preferences.
2099         applyAppSettings();
2100
2101         // Load `formattedUrlString` if we are not waiting for Orbot to connect.
2102         if (!waitingForOrbot) {
2103             loadUrl(formattedUrlString);
2104         }
2105     }
2106
2107     @Override
2108     protected void onNewIntent(Intent intent) {
2109         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
2110         setIntent(intent);
2111
2112         if (intent.getData() != null) {
2113             // Get the intent data and convert it to a string.
2114             final Uri intentUriData = intent.getData();
2115             formattedUrlString = intentUriData.toString();
2116         }
2117
2118         // Close the navigation drawer if it is open.
2119         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2120             drawerLayout.closeDrawer(GravityCompat.START);
2121         }
2122
2123         // Load the website.
2124         loadUrl(formattedUrlString);
2125
2126         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
2127         mainWebView.requestFocus();
2128     }
2129
2130     @Override
2131     public void onRestart() {
2132         // Run the default commands.
2133         super.onRestart();
2134
2135         // Apply the app settings, which may have been changed in `SettingsActivity`.
2136         applyAppSettings();
2137
2138         // Apply the domain settings if returning from the Domains Activity.
2139         if (reapplyDomainSettingsOnRestart) {
2140             // Reset `reapplyDomainSettingsOnRestart`.
2141             reapplyDomainSettingsOnRestart = false;
2142
2143             // Reapply the domain settings.
2144             applyDomainSettings(formattedUrlString);
2145         }
2146
2147         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2148         updatePrivacyIcons(true);
2149
2150         // Set the display webpage images mode.
2151         setDisplayWebpageImages();
2152
2153         // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
2154         if (reloadOnRestart) {
2155             // Reload `mainWebView`.
2156             mainWebView.reload();
2157
2158             // Reset `reloadOnRestartBoolean`.
2159             reloadOnRestart = false;
2160         }
2161
2162         // Load the URL on restart to apply changes to night mode.
2163         if (loadUrlOnRestart) {
2164             // Load the current `formattedUrlString`.
2165             loadUrl(formattedUrlString);
2166
2167             // Reset `loadUrlOnRestart.
2168             loadUrlOnRestart = false;
2169         }
2170
2171         //
2172         if (restartFromBookmarksActivity) {
2173             // Close the bookmarks drawer.
2174             drawerLayout.closeDrawer(GravityCompat.END);
2175
2176             // Reload the bookmarks drawer.
2177             loadBookmarksFolder();
2178
2179             // Reset `restartFromBookmarksActivity`.
2180             restartFromBookmarksActivity = false;
2181         }
2182     }
2183
2184     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
2185     @Override
2186     public void onResume() {
2187         // Run the default commands.
2188         super.onResume();
2189
2190         // Resume JavaScript (if enabled).
2191         mainWebView.resumeTimers();
2192
2193         // Resume `mainWebView`.
2194         mainWebView.onResume();
2195
2196         // Resume the adView for the free flavor.
2197         if (BuildConfig.FLAVOR.contentEquals("free")) {
2198             BannerAd.resumeAd(adView);
2199         }
2200     }
2201
2202     @Override
2203     public void onPause() {
2204         // Pause `mainWebView`.
2205         mainWebView.onPause();
2206
2207         // Stop all JavaScript.
2208         mainWebView.pauseTimers();
2209
2210         // Pause the adView or it will continue to consume resources in the background on the free flavor.
2211         if (BuildConfig.FLAVOR.contentEquals("free")) {
2212             BannerAd.pauseAd(adView);
2213         }
2214
2215         super.onPause();
2216     }
2217
2218     @Override
2219     public boolean onCreateOptionsMenu(Menu menu) {
2220         // Inflate the menu; this adds items to the action bar if it is present.
2221         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
2222
2223         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
2224         mainMenu = menu;
2225
2226         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
2227         updatePrivacyIcons(false);
2228
2229         // Get handles for the menu items.
2230         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2231         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2232         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2233         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
2234
2235         // Only display third-party cookies if SDK >= 21
2236         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
2237
2238         // Get the shared preference values.  `this` references the current context.
2239         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2240
2241         // Set the status of the additional app bar icons.  The default is `false`.
2242         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
2243             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2244             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2245             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2246         } else { //Do not display the additional icons.
2247             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2248             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2249             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2250         }
2251
2252         return true;
2253     }
2254
2255     @Override
2256     public boolean onPrepareOptionsMenu(Menu menu) {
2257         // Get handles for the menu items.
2258         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2259         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2260         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2261         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2262         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
2263         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2264         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2265         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2266         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
2267         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2268         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2269         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
2270
2271         // Set the text for the domain menu item.
2272         if (domainSettingsApplied) {
2273             addOrEditDomain.setTitle(R.string.edit_domain_settings);
2274         } else {
2275             addOrEditDomain.setTitle(R.string.add_domain_settings);
2276         }
2277
2278         // Set the status of the menu item checkboxes.
2279         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2280         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2281         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2282         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
2283         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2284
2285         // Enable third-party cookies if first-party cookies are enabled.
2286         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2287
2288         // Enable `DOM Storage` if JavaScript is enabled.
2289         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2290
2291         // Enable `Clear Cookies` if there are any.
2292         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2293
2294         // Get a count of the number of files in the `Local Storage` directory.
2295         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2296         int localStorageDirectoryNumberOfFiles = 0;
2297         if (localStorageDirectory.exists()) {
2298             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2299         }
2300
2301         // Get a count of the number of files in the `IndexedDB` directory.
2302         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2303         int indexedDBDirectoryNumberOfFiles = 0;
2304         if (indexedDBDirectory.exists()) {
2305             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2306         }
2307
2308         // Enable `Clear DOM Storage` if there is any.
2309         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2310
2311         // Enable `Clear Form Data` is there is any.
2312         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2313         clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2314
2315         // Enable `Clear Data` if any of the submenu items are enabled.
2316         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2317
2318         // Initialize font size variables.
2319         int fontSize = mainWebView.getSettings().getTextZoom();
2320         String fontSizeTitle;
2321         MenuItem selectedFontSizeMenuItem;
2322
2323         // Prepare the font size title and current size menu item.
2324         switch (fontSize) {
2325             case 25:
2326                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2327                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2328                 break;
2329
2330             case 50:
2331                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2332                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2333                 break;
2334
2335             case 75:
2336                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2337                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2338                 break;
2339
2340             case 100:
2341                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2342                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2343                 break;
2344
2345             case 125:
2346                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2347                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2348                 break;
2349
2350             case 150:
2351                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2352                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2353                 break;
2354
2355             case 175:
2356                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2357                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2358                 break;
2359
2360             case 200:
2361                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2362                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2363                 break;
2364
2365             default:
2366                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2367                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2368                 break;
2369         }
2370
2371         // Set the font size title and select the current size menu item.
2372         fontSizeMenuItem.setTitle(fontSizeTitle);
2373         selectedFontSizeMenuItem.setChecked(true);
2374
2375         // Only show `Refresh` if `swipeToRefresh` is disabled.
2376         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
2377
2378         // Run all the other default commands.
2379         super.onPrepareOptionsMenu(menu);
2380
2381         // Display the menu.
2382         return true;
2383     }
2384
2385     @Override
2386     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2387     @SuppressLint("SetJavaScriptEnabled")
2388     // removeAllCookies is deprecated, but it is required for API < 21.
2389     @SuppressWarnings("deprecation")
2390     public boolean onOptionsItemSelected(MenuItem menuItem) {
2391         // Get the selected menu item ID.
2392         int menuItemId = menuItem.getItemId();
2393
2394         // Set the commands that relate to the menu entries.
2395         switch (menuItemId) {
2396             case R.id.add_or_edit_domain:
2397                 if (domainSettingsApplied) {  // Edit the current domain settings.
2398                     // Reapply the domain settings on returning to `MainWebViewActivity`.
2399                     reapplyDomainSettingsOnRestart = true;
2400                     currentDomainName = "";
2401
2402                     // Create an intent to launch the domains activity.
2403                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
2404
2405                     // Put extra information instructing the domains activity to directly load the current domain.
2406                     domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
2407
2408                     // Make it so.
2409                     startActivity(domainsIntent);
2410                 } else {  // Add a new domain.
2411                     // Show the add domain `AlertDialog`.
2412                     AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
2413                     addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
2414                 }
2415                 return true;
2416
2417             case R.id.toggle_javascript:
2418                 // Switch the status of javaScriptEnabled.
2419                 javaScriptEnabled = !javaScriptEnabled;
2420
2421                 // Apply the new JavaScript status.
2422                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2423
2424                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2425                 updatePrivacyIcons(true);
2426
2427                 // Display a `Snackbar`.
2428                 if (javaScriptEnabled) {  // JavaScrip is enabled.
2429                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2430                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
2431                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2432                 } else {  // Privacy mode.
2433                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2434                 }
2435
2436                 // Reload the WebView.
2437                 mainWebView.reload();
2438                 return true;
2439
2440             case R.id.toggle_first_party_cookies:
2441                 // Switch the status of firstPartyCookiesEnabled.
2442                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2443
2444                 // Update the menu checkbox.
2445                 menuItem.setChecked(firstPartyCookiesEnabled);
2446
2447                 // Apply the new cookie status.
2448                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2449
2450                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2451                 updatePrivacyIcons(true);
2452
2453                 // Display a `Snackbar`.
2454                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2455                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2456                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
2457                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2458                 } else {  // Privacy mode.
2459                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2460                 }
2461
2462                 // Reload the WebView.
2463                 mainWebView.reload();
2464                 return true;
2465
2466             case R.id.toggle_third_party_cookies:
2467                 if (Build.VERSION.SDK_INT >= 21) {
2468                     // Switch the status of thirdPartyCookiesEnabled.
2469                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2470
2471                     // Update the menu checkbox.
2472                     menuItem.setChecked(thirdPartyCookiesEnabled);
2473
2474                     // Apply the new cookie status.
2475                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2476
2477                     // Display a `Snackbar`.
2478                     if (thirdPartyCookiesEnabled) {
2479                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2480                     } else {
2481                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2482                     }
2483
2484                     // Reload the WebView.
2485                     mainWebView.reload();
2486                 } // Else do nothing because SDK < 21.
2487                 return true;
2488
2489             case R.id.toggle_dom_storage:
2490                 // Switch the status of domStorageEnabled.
2491                 domStorageEnabled = !domStorageEnabled;
2492
2493                 // Update the menu checkbox.
2494                 menuItem.setChecked(domStorageEnabled);
2495
2496                 // Apply the new DOM Storage status.
2497                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2498
2499                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2500                 updatePrivacyIcons(true);
2501
2502                 // Display a `Snackbar`.
2503                 if (domStorageEnabled) {
2504                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2505                 } else {
2506                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2507                 }
2508
2509                 // Reload the WebView.
2510                 mainWebView.reload();
2511                 return true;
2512
2513             case R.id.toggle_save_form_data:
2514                 // Switch the status of saveFormDataEnabled.
2515                 saveFormDataEnabled = !saveFormDataEnabled;
2516
2517                 // Update the menu checkbox.
2518                 menuItem.setChecked(saveFormDataEnabled);
2519
2520                 // Apply the new form data status.
2521                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2522
2523                 // Display a `Snackbar`.
2524                 if (saveFormDataEnabled) {
2525                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2526                 } else {
2527                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2528                 }
2529
2530                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
2531                 updatePrivacyIcons(true);
2532
2533                 // Reload the WebView.
2534                 mainWebView.reload();
2535                 return true;
2536
2537             case R.id.clear_cookies:
2538                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2539                         .setAction(R.string.undo, v -> {
2540                             // Do nothing because everything will be handled by `onDismissed()` below.
2541                         })
2542                         .addCallback(new Snackbar.Callback() {
2543                             @Override
2544                             public void onDismissed(Snackbar snackbar, int event) {
2545                                 switch (event) {
2546                                     // The user pushed the `Undo` button.
2547                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2548                                         // Do nothing.
2549                                         break;
2550
2551                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2552                                     default:
2553                                         // `cookieManager.removeAllCookie()` varies by SDK.
2554                                         if (Build.VERSION.SDK_INT < 21) {
2555                                             cookieManager.removeAllCookie();
2556                                         } else {
2557                                             // `null` indicates no callback.
2558                                             cookieManager.removeAllCookies(null);
2559                                         }
2560                                 }
2561                             }
2562                         })
2563                         .show();
2564                 return true;
2565
2566             case R.id.clear_dom_storage:
2567                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2568                         .setAction(R.string.undo, v -> {
2569                             // Do nothing because everything will be handled by `onDismissed()` below.
2570                         })
2571                         .addCallback(new Snackbar.Callback() {
2572                             @Override
2573                             public void onDismissed(Snackbar snackbar, int event) {
2574                                 switch (event) {
2575                                     // The user pushed the `Undo` button.
2576                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2577                                         // Do nothing.
2578                                         break;
2579
2580                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2581                                     default:
2582                                         // Delete the DOM Storage.
2583                                         WebStorage webStorage = WebStorage.getInstance();
2584                                         webStorage.deleteAllData();
2585
2586                                         // Manually delete the DOM storage files and directories.
2587                                         try {
2588                                             // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2589                                             privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2590
2591                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2592                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2593                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2594                                             privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2595                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2596                                         } catch (IOException e) {
2597                                             // Do nothing if an error is thrown.
2598                                         }
2599                                 }
2600                             }
2601                         })
2602                         .show();
2603                 return true;
2604
2605             case R.id.clear_form_data:
2606                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2607                         .setAction(R.string.undo, v -> {
2608                             // Do nothing because everything will be handled by `onDismissed()` below.
2609                         })
2610                         .addCallback(new Snackbar.Callback() {
2611                             @Override
2612                             public void onDismissed(Snackbar snackbar, int event) {
2613                                 switch (event) {
2614                                     // The user pushed the `Undo` button.
2615                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
2616                                         // Do nothing.
2617                                         break;
2618
2619                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
2620                                     default:
2621                                         // Delete the form data.
2622                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2623                                         mainWebViewDatabase.clearFormData();
2624                                 }
2625                             }
2626                         })
2627                         .show();
2628                 return true;
2629
2630             case R.id.font_size_twenty_five_percent:
2631                 mainWebView.getSettings().setTextZoom(25);
2632                 return true;
2633
2634             case R.id.font_size_fifty_percent:
2635                 mainWebView.getSettings().setTextZoom(50);
2636                 return true;
2637
2638             case R.id.font_size_seventy_five_percent:
2639                 mainWebView.getSettings().setTextZoom(75);
2640                 return true;
2641
2642             case R.id.font_size_one_hundred_percent:
2643                 mainWebView.getSettings().setTextZoom(100);
2644                 return true;
2645
2646             case R.id.font_size_one_hundred_twenty_five_percent:
2647                 mainWebView.getSettings().setTextZoom(125);
2648                 return true;
2649
2650             case R.id.font_size_one_hundred_fifty_percent:
2651                 mainWebView.getSettings().setTextZoom(150);
2652                 return true;
2653
2654             case R.id.font_size_one_hundred_seventy_five_percent:
2655                 mainWebView.getSettings().setTextZoom(175);
2656                 return true;
2657
2658             case R.id.font_size_two_hundred_percent:
2659                 mainWebView.getSettings().setTextZoom(200);
2660                 return true;
2661
2662             case R.id.display_images:
2663                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
2664                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
2665                     mainWebView.reload();
2666                 } else {  // Images are not currently loaded automatically.
2667                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
2668                 }
2669
2670                 // Set `onTheFlyDisplayImagesSet`.
2671                 onTheFlyDisplayImagesSet = true;
2672                 return true;
2673
2674             case R.id.share:
2675                 // Setup the share string.
2676                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2677
2678                 // Create the share intent.
2679                 Intent shareIntent = new Intent();
2680                 shareIntent.setAction(Intent.ACTION_SEND);
2681                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2682                 shareIntent.setType("text/plain");
2683
2684                 // Make it so.
2685                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2686                 return true;
2687
2688             case R.id.find_on_page:
2689                 // Hide the URL app bar.
2690                 supportAppBar.setVisibility(View.GONE);
2691
2692                 // Show the Find on Page `RelativeLayout`.
2693                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2694
2695                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
2696                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2697                 findOnPageEditText.postDelayed(() -> {
2698                     // Set the focus on `findOnPageEditText`.
2699                     findOnPageEditText.requestFocus();
2700
2701                     // Display the keyboard.  `0` sets no input flags.
2702                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
2703                 }, 200);
2704                 return true;
2705
2706             case R.id.print:
2707                 // Get a `PrintManager` instance.
2708                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2709
2710                 // Convert `mainWebView` to `printDocumentAdapter`.
2711                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2712
2713                 // Remove the lint error below that `printManager` might be `null`.
2714                 assert printManager != null;
2715
2716                 // Print the document.  The print attributes are `null`.
2717                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2718                 return true;
2719
2720             case R.id.view_source:
2721                 // Launch the Vew Source activity.
2722                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2723                 startActivity(viewSourceIntent);
2724                 return true;
2725
2726             case R.id.add_to_homescreen:
2727                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2728                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2729                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2730
2731                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2732                 return true;
2733
2734             case R.id.refresh:
2735                 mainWebView.reload();
2736                 return true;
2737
2738             default:
2739                 // Don't consume the event.
2740                 return super.onOptionsItemSelected(menuItem);
2741         }
2742     }
2743
2744     // removeAllCookies is deprecated, but it is required for API < 21.
2745     @SuppressWarnings("deprecation")
2746     @Override
2747     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2748         int menuItemId = menuItem.getItemId();
2749
2750         switch (menuItemId) {
2751             case R.id.home:
2752                 loadUrl(homepage);
2753                 break;
2754
2755             case R.id.back:
2756                 if (mainWebView.canGoBack()) {
2757                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2758                     navigatingHistory = true;
2759
2760                     // Load the previous website in the history.
2761                     mainWebView.goBack();
2762                 }
2763                 break;
2764
2765             case R.id.forward:
2766                 if (mainWebView.canGoForward()) {
2767                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2768                     navigatingHistory = true;
2769
2770                     // Load the next website in the history.
2771                     mainWebView.goForward();
2772                 }
2773                 break;
2774
2775             case R.id.history:
2776                 // Get the `WebBackForwardList`.
2777                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2778
2779                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
2780                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2781                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2782                 break;
2783
2784             case R.id.downloads:
2785                 // Launch the system Download Manager.
2786                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2787
2788                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2789                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2790
2791                 startActivity(downloadManagerIntent);