]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Fix the URL formatting bug. https://redmine.stoutner.com/issues/248
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.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);
2792                 break;
2793
2794             case R.id.domains:
2795                 // Reapply the domain settings on returning to `MainWebViewActivity`.
2796                 reapplyDomainSettingsOnRestart = true;
2797                 currentDomainName = "";
2798
2799                 // Launch `DomainsActivity`.
2800                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2801                 startActivity(domainsIntent);
2802                 break;
2803
2804             case R.id.settings:
2805                 // Reapply the domain settings on returning to `MainWebViewActivity`.
2806                 reapplyDomainSettingsOnRestart = true;
2807                 currentDomainName = "";
2808
2809                 // Launch `SettingsActivity`.
2810                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2811                 startActivity(settingsIntent);
2812                 break;
2813
2814             case R.id.guide:
2815                 // Launch `GuideActivity`.
2816                 Intent guideIntent = new Intent(this, GuideActivity.class);
2817                 startActivity(guideIntent);
2818                 break;
2819
2820             case R.id.about:
2821                 // Launch `AboutActivity`.
2822                 Intent aboutIntent = new Intent(this, AboutActivity.class);
2823                 startActivity(aboutIntent);
2824                 break;
2825
2826             case R.id.clearAndExit:
2827                 // Get a handle for `sharedPreferences`.  `this` references the current context.
2828                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2829
2830                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2831
2832                 // Clear cookies.
2833                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2834                     // The command to remove cookies changed slightly in API 21.
2835                     if (Build.VERSION.SDK_INT >= 21) {
2836                         cookieManager.removeAllCookies(null);
2837                     } else {
2838                         cookieManager.removeAllCookie();
2839                     }
2840
2841                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2842                     try {
2843                         // We have to use two commands because `Runtime.exec()` does not like `*`.
2844                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2845                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2846                     } catch (IOException e) {
2847                         // Do nothing if an error is thrown.
2848                     }
2849                 }
2850
2851                 // Clear DOM storage.
2852                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2853                     // Ask `WebStorage` to clear the DOM storage.
2854                     WebStorage webStorage = WebStorage.getInstance();
2855                     webStorage.deleteAllData();
2856
2857                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2858                     try {
2859                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2860                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2861
2862                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2863                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2864                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2865                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2866                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2867                     } catch (IOException e) {
2868                         // Do nothing if an error is thrown.
2869                     }
2870                 }
2871
2872                 // Clear form data.
2873                 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2874                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2875                     webViewDatabase.clearFormData();
2876
2877                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2878                     try {
2879                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2880                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2881                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2882                     } catch (IOException e) {
2883                         // Do nothing if an error is thrown.
2884                     }
2885                 }
2886
2887                 // Clear the cache.
2888                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2889                     // `true` includes disk files.
2890                     mainWebView.clearCache(true);
2891
2892                     // Manually delete the cache directories.
2893                     try {
2894                         // Delete the main cache directory.
2895                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2896                         // Delete the secondary `Service Worker` cache directory.
2897                         // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2898                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2899                     } catch (IOException e) {
2900                         // Do nothing if an error is thrown.
2901                     }
2902                 }
2903
2904                 // Clear SSL certificate preferences.
2905                 mainWebView.clearSslPreferences();
2906
2907                 // Clear the back/forward history.
2908                 mainWebView.clearHistory();
2909
2910                 // Clear `formattedUrlString`.
2911                 formattedUrlString = null;
2912
2913                 // Clear `customHeaders`.
2914                 customHeaders.clear();
2915
2916                 // Detach all views from `mainWebViewRelativeLayout`.
2917                 mainWebViewRelativeLayout.removeAllViews();
2918
2919                 // Destroy the internal state of `mainWebView`.
2920                 mainWebView.destroy();
2921
2922                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2923                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2924                 if (clearEverything) {
2925                     try {
2926                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2927                     } catch (IOException e) {
2928                         // Do nothing if an error is thrown.
2929                     }
2930                 }
2931
2932                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2933                 if (Build.VERSION.SDK_INT >= 21) {
2934                     finishAndRemoveTask();
2935                 } else {
2936                     finish();
2937                 }
2938
2939                 // Remove the terminated program from RAM.  The status code is `0`.
2940                 System.exit(0);
2941                 break;
2942         }
2943
2944         // Close the navigation drawer.
2945         drawerLayout.closeDrawer(GravityCompat.START);
2946         return true;
2947     }
2948
2949     @Override
2950     public void onPostCreate(Bundle savedInstanceState) {
2951         super.onPostCreate(savedInstanceState);
2952
2953         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2954         drawerToggle.syncState();
2955     }
2956
2957     @Override
2958     public void onConfigurationChanged(Configuration newConfig) {
2959         super.onConfigurationChanged(newConfig);
2960
2961         // Reload the ad for the free flavor if we are not in full screen mode.
2962         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2963             // Reload the ad.
2964             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2965
2966             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2967             adView = findViewById(R.id.adview);
2968         }
2969
2970         // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
2971         // https://code.google.com/p/android/issues/detail?id=20493#c8
2972         // ActivityCompat.invalidateOptionsMenu(this);
2973     }
2974
2975     @Override
2976     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2977         // Store the `HitTestResult`.
2978         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2979
2980         // Create strings.
2981         final String imageUrl;
2982         final String linkUrl;
2983
2984         // Get a handle for the `ClipboardManager`.
2985         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2986
2987         // Remove the lint errors below that `clipboardManager` might be `null`.
2988         assert clipboardManager != null;
2989
2990         switch (hitTestResult.getType()) {
2991             // `SRC_ANCHOR_TYPE` is a link.
2992             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2993                 // Get the target URL.
2994                 linkUrl = hitTestResult.getExtra();
2995
2996                 // Set the target URL as the title of the `ContextMenu`.
2997                 menu.setHeaderTitle(linkUrl);
2998
2999                 // Add a `Load URL` entry.
3000                 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
3001                     loadUrl(linkUrl);
3002                     return false;
3003                 });
3004
3005                 // Add a `Copy URL` entry.
3006                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3007                     // Save the link URL in a `ClipData`.
3008                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3009
3010                     // Set the `ClipData` as the clipboard's primary clip.
3011                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3012                     return false;
3013                 });
3014
3015                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3016                 menu.add(R.string.cancel);
3017                 break;
3018
3019             case WebView.HitTestResult.EMAIL_TYPE:
3020                 // Get the target URL.
3021                 linkUrl = hitTestResult.getExtra();
3022
3023                 // Set the target URL as the title of the `ContextMenu`.
3024                 menu.setHeaderTitle(linkUrl);
3025
3026                 // Add a `Write Email` entry.
3027                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3028                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3029                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3030
3031                     // Parse the url and set it as the data for the `Intent`.
3032                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3033
3034                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3035                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3036
3037                     // Make it so.
3038                     startActivity(emailIntent);
3039                     return false;
3040                 });
3041
3042                 // Add a `Copy Email Address` entry.
3043                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3044                     // Save the email address in a `ClipData`.
3045                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3046
3047                     // Set the `ClipData` as the clipboard's primary clip.
3048                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3049                     return false;
3050                 });
3051
3052                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3053                 menu.add(R.string.cancel);
3054                 break;
3055
3056             // `IMAGE_TYPE` is an image.
3057             case WebView.HitTestResult.IMAGE_TYPE:
3058                 // Get the image URL.
3059                 imageUrl = hitTestResult.getExtra();
3060
3061                 // Set the image URL as the title of the `ContextMenu`.
3062                 menu.setHeaderTitle(imageUrl);
3063
3064                 // Add a `View Image` entry.
3065                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3066                     loadUrl(imageUrl);
3067                     return false;
3068                 });
3069
3070                 // Add a `Download Image` entry.
3071                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3072                     // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
3073                     AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3074                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3075                     return false;
3076                 });
3077
3078                 // Add a `Copy URL` entry.
3079                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3080                     // Save the image URL in a `ClipData`.
3081                     ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3082
3083                     // Set the `ClipData` as the clipboard's primary clip.
3084                     clipboardManager.setPrimaryClip(srcImageTypeClipData);
3085                     return false;
3086                 });
3087
3088                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3089                 menu.add(R.string.cancel);
3090                 break;
3091
3092
3093             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3094             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3095                 // Get the image URL.
3096                 imageUrl = hitTestResult.getExtra();
3097
3098                 // Set the image URL as the title of the `ContextMenu`.
3099                 menu.setHeaderTitle(imageUrl);
3100
3101                 // Add a `View Image` entry.
3102                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3103                     loadUrl(imageUrl);
3104                     return false;
3105                 });
3106
3107                 // Add a `Download Image` entry.
3108                 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3109                     // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
3110                     AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3111                     downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3112                     return false;
3113                 });
3114
3115                 // Add a `Copy URL` entry.
3116                 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3117                     // Save the image URL in a `ClipData`.
3118                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3119
3120                     // Set the `ClipData` as the clipboard's primary clip.
3121                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3122                     return false;
3123                 });
3124
3125                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3126                 menu.add(R.string.cancel);
3127                 break;
3128         }
3129     }
3130
3131     @Override
3132     public void onAddDomain(AppCompatDialogFragment dialogFragment) {
3133         // Reapply the domain settings on returning to `MainWebViewActivity`.
3134         reapplyDomainSettingsOnRestart = true;
3135         currentDomainName = "";
3136
3137         // Get the new domain name `String` from `dialogFragment`.
3138         EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
3139         String domainNameString = domainNameEditText.getText().toString();
3140
3141         // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3142         // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3143         DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3144
3145         // Create the domain and store the database ID in `currentDomainDatabaseId`.
3146         int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
3147
3148         // Create an intent to launch the domains activity.
3149         Intent domainsIntent = new Intent(this, DomainsActivity.class);
3150
3151         // Put extra information instructing the domains activity to directly load the current domain.
3152         domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
3153
3154         // Make it so.
3155         startActivity(domainsIntent);
3156     }
3157
3158     @Override
3159     public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3160         // Get the `EditTexts` from the `dialogFragment`.
3161         EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3162         EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3163
3164         // Extract the strings from the `EditTexts`.
3165         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3166         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3167
3168         // Convert the favoriteIcon Bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
3169         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3170         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3171         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3172
3173         // Display the new bookmark below the current items in the (0 indexed) list.
3174         int newBookmarkDisplayOrder = bookmarksListView.getCount();
3175
3176         // Create the bookmark.
3177         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3178
3179         // Update `bookmarksCursor` with the current contents of this folder.
3180         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3181
3182         // Update the `ListView`.
3183         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3184
3185         // Scroll to the new bookmark.
3186         bookmarksListView.setSelection(newBookmarkDisplayOrder);
3187     }
3188
3189     @Override
3190     public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3191         // Get handles for the views in `dialogFragment`.
3192         EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3193         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3194         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3195
3196         // Get new folder name string.
3197         String folderNameString = createFolderNameEditText.getText().toString();
3198
3199         // Get the new folder icon `Bitmap`.
3200         Bitmap folderIconBitmap;
3201         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
3202             // Get the default folder icon and convert it to a `Bitmap`.
3203             Drawable folderIconDrawable = folderIconImageView.getDrawable();
3204             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3205             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3206         } else {  // Use the `WebView` favorite icon.
3207             folderIconBitmap = favoriteIconBitmap;
3208         }
3209
3210         // Convert `folderIconBitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3211         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3212         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3213         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3214
3215         // Move all the bookmarks down one in the display order.
3216         for (int i = 0; i < bookmarksListView.getCount(); i++) {
3217             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3218             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3219         }
3220
3221         // Create the folder, which will be placed at the top of the `ListView`.
3222         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3223
3224         // Update `bookmarksCursor` with the current contents of this folder.
3225         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3226
3227         // Update the `ListView`.
3228         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3229
3230         // Scroll to the new folder.
3231         bookmarksListView.setSelection(0);
3232     }
3233
3234     @Override
3235     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3236         // Get the shortcut name.
3237         EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3238         String shortcutNameString = shortcutNameEditText.getText().toString();
3239
3240         // Convert the favorite icon bitmap to an `Icon`.  `IconCompat` is required until API >= 26.
3241         IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3242
3243         // Setup the shortcut intent.
3244         Intent shortcutIntent = new Intent();
3245         shortcutIntent.setAction(Intent.ACTION_VIEW);
3246         shortcutIntent.setData(Uri.parse(formattedUrlString));
3247
3248         // Create a shortcut info builder.  The shortcut name becomes the shortcut ID.
3249         ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3250
3251         // Add the required fields to the shortcut info builder.
3252         shortcutInfoBuilder.setIcon(favoriteIcon);
3253         shortcutInfoBuilder.setIntent(shortcutIntent);
3254         shortcutInfoBuilder.setShortLabel(shortcutNameString);
3255
3256         // Request the pin.  `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3257         ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3258     }
3259
3260     @Override
3261     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3262         // Download the image if it has an HTTP or HTTPS URI.
3263         if (imageUrl.startsWith("http")) {
3264             // Get a handle for the system `DOWNLOAD_SERVICE`.
3265             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3266
3267             // Parse `imageUrl`.
3268             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3269
3270             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
3271             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3272             if (firstPartyCookiesEnabled) {
3273                 // Get the cookies for `imageUrl`.
3274                 String cookies = cookieManager.getCookie(imageUrl);
3275
3276                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3277                 downloadRequest.addRequestHeader("Cookie", cookies);
3278             }
3279
3280             // Get the file name from `dialogFragment`.
3281             EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3282             String imageName = downloadImageNameEditText.getText().toString();
3283
3284             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
3285             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
3286                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
3287             } else { // Only set the title using `imageName`.
3288                 downloadRequest.setTitle(imageName);
3289             }
3290
3291             // Allow `MediaScanner` to index the download if it is a media file.
3292             downloadRequest.allowScanningByMediaScanner();
3293
3294             // Add the URL as the description for the download.
3295             downloadRequest.setDescription(imageUrl);
3296
3297             // Show the download notification after the download is completed.
3298             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3299
3300             // Remove the lint warning below that `downloadManager` might be `null`.
3301             assert downloadManager != null;
3302
3303             // Initiate the download.
3304             downloadManager.enqueue(downloadRequest);
3305         } else {  // The image is not an HTTP or HTTPS URI.
3306             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3307         }
3308     }
3309
3310     @Override
3311     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3312         // Download the file if it has an HTTP or HTTPS URI.
3313         if (downloadUrl.startsWith("http")) {
3314
3315             // Get a handle for the system `DOWNLOAD_SERVICE`.
3316             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3317
3318             // Parse `downloadUrl`.
3319             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3320
3321             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
3322             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3323             if (firstPartyCookiesEnabled) {
3324                 // Get the cookies for `downloadUrl`.
3325                 String cookies = cookieManager.getCookie(downloadUrl);
3326
3327                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
3328                 downloadRequest.addRequestHeader("Cookie", cookies);
3329             }
3330
3331             // Get the file name from `dialogFragment`.
3332             EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3333             String fileName = downloadFileNameEditText.getText().toString();
3334
3335             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
3336             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
3337                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
3338             } else { // Only set the title using `fileName`.
3339                 downloadRequest.setTitle(fileName);
3340             }
3341
3342             // Allow `MediaScanner` to index the download if it is a media file.
3343             downloadRequest.allowScanningByMediaScanner();
3344
3345             // Add the URL as the description for the download.
3346             downloadRequest.setDescription(downloadUrl);
3347
3348             // Show the download notification after the download is completed.
3349             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3350
3351             // Remove the lint warning below that `downloadManager` might be `null`.
3352             assert downloadManager != null;
3353
3354             // Initiate the download.
3355             downloadManager.enqueue(downloadRequest);
3356         } else {  // The download is not an HTTP or HTTPS URI.
3357             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3358         }
3359     }
3360
3361     @Override
3362     public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3363         // Get handles for the views from `dialogFragment`.
3364         EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3365         EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3366         RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3367
3368         // Store the bookmark strings.
3369         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3370         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3371
3372         // Update the bookmark.
3373         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
3374             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3375         } else {  // Update the bookmark using the `WebView` favorite icon.
3376             // Convert the favorite icon to a byte array.  `0` is for lossless compression (the only option for a PNG).
3377             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3378             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3379             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3380
3381             //  Update the bookmark and the favorite icon.
3382             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3383         }
3384
3385         // Update `bookmarksCursor` with the current contents of this folder.
3386         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3387
3388         // Update the `ListView`.
3389         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3390     }
3391
3392     @Override
3393     public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3394         // Get handles for the views from `dialogFragment`.
3395         EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3396         RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3397         RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3398         ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3399
3400         // Get the new folder name.
3401         String newFolderNameString = editFolderNameEditText.getText().toString();
3402
3403         // Check if the favorite icon has changed.
3404         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
3405             // Update the name in the database.
3406             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3407         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
3408             // Get the new folder icon `Bitmap`.
3409             Bitmap folderIconBitmap;
3410             if (defaultFolderIconRadioButton.isChecked()) {
3411                 // Get the default folder icon and convert it to a `Bitmap`.
3412                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3413                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3414                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3415             } else {  // Use the `WebView` favorite icon.
3416                 folderIconBitmap = favoriteIconBitmap;
3417             }
3418
3419             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3420             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3421             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3422             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3423
3424             // Update the folder icon in the database.
3425             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3426         } else {  // The folder icon and the name have changed.
3427             // Get the new folder icon `Bitmap`.
3428             Bitmap folderIconBitmap;
3429             if (defaultFolderIconRadioButton.isChecked()) {
3430                 // Get the default folder icon and convert it to a `Bitmap`.
3431                 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3432                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3433                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3434             } else {  // Use the `WebView` favorite icon.
3435                 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3436             }
3437
3438             // Convert the folder `Bitmap` to a byte array.  `0` is for lossless compression (the only option for a PNG).
3439             ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3440             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3441             byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3442
3443             // Update the folder name and icon in the database.
3444             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3445         }
3446
3447         // Update `bookmarksCursor` with the current contents of this folder.
3448         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3449
3450         // Update the `ListView`.
3451         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3452     }
3453
3454     @Override
3455     public void onHttpAuthenticationCancel() {
3456         // Cancel the `HttpAuthHandler`.
3457         httpAuthHandler.cancel();
3458     }
3459
3460     @Override
3461     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3462         // Get handles for the `EditTexts`.
3463         EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3464         EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3465
3466         // Proceed with the HTTP authentication.
3467         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3468     }
3469
3470     public void viewSslCertificate(View view) {
3471         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3472         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3473         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3474     }
3475
3476     @Override
3477     public void onSslErrorCancel() {
3478         sslErrorHandler.cancel();
3479     }
3480
3481     @Override
3482     public void onSslErrorProceed() {
3483         sslErrorHandler.proceed();
3484     }
3485
3486     @Override
3487     public void onSslMismatchBack() {
3488         if (mainWebView.canGoBack()) {  // There is a back page in the history.
3489             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3490             navigatingHistory = true;
3491
3492             // Go back.
3493             mainWebView.goBack();
3494         } else {  // There are no pages to go back to.
3495             // Load a blank page
3496             loadUrl("");
3497         }
3498     }
3499
3500     @Override
3501     public void onSslMismatchProceed() {
3502         // Do not check the pinned SSL certificate for this domain again until the domain changes.
3503         ignorePinnedSslCertificate = true;
3504     }
3505
3506     @Override
3507     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3508         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3509         navigatingHistory = true;
3510
3511         // Load the history entry.
3512         mainWebView.goBackOrForward(moveBackOrForwardSteps);
3513     }
3514
3515     @Override
3516     public void onClearHistory() {
3517         // Clear the history.
3518         mainWebView.clearHistory();
3519     }
3520
3521     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3522     @Override
3523     public void onBackPressed() {
3524         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
3525             // Close the navigation drawer.
3526             drawerLayout.closeDrawer(GravityCompat.START);
3527         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
3528             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
3529                 // close the bookmarks drawer.
3530                 drawerLayout.closeDrawer(GravityCompat.END);
3531             } else {  // A subfolder is displayed.
3532                 // Place the former parent folder in `currentFolder`.
3533                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3534
3535                 // Load the new folder.
3536                 loadBookmarksFolder();
3537             }
3538
3539         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
3540             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3541             navigatingHistory = true;
3542
3543             // Go back.
3544             mainWebView.goBack();
3545         } else {  // There isn't anything to do in Privacy Browser.
3546             // Pass `onBackPressed()` to the system.
3547             super.onBackPressed();
3548         }
3549     }
3550
3551     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3552         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
3553         String unformattedUrlString = urlTextBox.getText().toString().trim();
3554
3555         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
3556         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3557             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
3558             if (!unformattedUrlString.startsWith("http")) {
3559                 unformattedUrlString = "http://" + unformattedUrlString;
3560             }
3561
3562             // Initialize `unformattedUrl`.
3563             URL unformattedUrl = null;
3564
3565             // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
3566             try {
3567                 unformattedUrl = new URL(unformattedUrlString);
3568             } catch (MalformedURLException e) {
3569                 e.printStackTrace();
3570             }
3571
3572             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3573             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3574             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3575             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3576             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3577             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3578
3579             // Build the URI.
3580             Uri.Builder formattedUri = new Uri.Builder();
3581             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3582
3583             // Decode `formattedUri` as a `String` in `UTF-8`.
3584             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3585         } else {
3586             // Sanitize the search input and convert it to a search.
3587             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3588
3589             // Add the base search URL.
3590             formattedUrlString = searchURL + encodedUrlString;
3591         }
3592
3593         // Clear the focus from the URL text box.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3594         urlTextBox.clearFocus();
3595
3596         loadUrl(formattedUrlString);
3597     }
3598
3599
3600     private void loadUrl(String url) {
3601         // Apply any custom domain settings.
3602         applyDomainSettings(url);
3603
3604         // Load the URL.
3605         mainWebView.loadUrl(url, customHeaders);
3606
3607         // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3608         urlIsLoading = true;
3609     }
3610
3611     public void findPreviousOnPage(View view) {
3612         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
3613         mainWebView.findNext(false);
3614     }
3615
3616     public void findNextOnPage(View view) {
3617         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3618         mainWebView.findNext(true);
3619     }
3620
3621     public void closeFindOnPage(View view) {
3622         // Delete the contents of `find_on_page_edittext`.
3623         findOnPageEditText.setText(null);
3624
3625         // Clear the highlighted phrases.
3626         mainWebView.clearMatches();
3627
3628         // Hide the Find on Page `RelativeLayout`.
3629         findOnPageLinearLayout.setVisibility(View.GONE);
3630
3631         // Show the URL app bar.
3632         supportAppBar.setVisibility(View.VISIBLE);
3633
3634         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
3635         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3636     }
3637
3638     private void applyAppSettings() {
3639         // Get a handle for the shared preferences.
3640         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3641
3642         // Store the values from the shared preferences in variables.
3643         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3644         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3645         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3646         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3647         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3648         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3649         adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
3650         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3651         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3652         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3653         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3654         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3655         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3656         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3657         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3658
3659         // Set the homepage, search, and proxy options.
3660         if (proxyThroughOrbot) {  // Set the Tor options.
3661             // Set `torHomepageString` as `homepage`.
3662             homepage = torHomepageString;
3663
3664             // If formattedUrlString is null assign the homepage to it.
3665             if (formattedUrlString == null) {
3666                 formattedUrlString = homepage;
3667             }
3668
3669             // Set the search URL.
3670             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
3671                 searchURL = torSearchCustomURLString;
3672             } else {  // Use the string from the pre-built list.
3673                 searchURL = torSearchString;
3674             }
3675
3676             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
3677             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3678
3679             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
3680             if (darkTheme) {
3681                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3682             } else {
3683                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3684             }
3685
3686             // Display a message to the user if we are waiting on Orbot.
3687             if (!orbotStatus.equals("ON")) {
3688                 // Set `waitingForOrbot`.
3689                 waitingForOrbot = true;
3690
3691                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
3692                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3693             }
3694         } else {  // Set the non-Tor options.
3695             // Set `homepageString` as `homepage`.
3696             homepage = homepageString;
3697
3698             // If formattedUrlString is null assign the homepage to it.
3699             if (formattedUrlString == null) {
3700                 formattedUrlString = homepage;
3701             }
3702
3703             // Set the search URL.
3704             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
3705                 searchURL = searchCustomURLString;
3706             } else {  // Use the string from the pre-built list.
3707                 searchURL = searchString;
3708             }
3709
3710             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
3711             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3712
3713             // Set the default `appBar` background.  `this` refers to the context.
3714             if (darkTheme) {
3715                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3716             } else {
3717                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3718             }
3719
3720             // Reset `waitingForOrbot.
3721             waitingForOrbot = false;
3722         }
3723
3724         // Set swipe to refresh.
3725         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3726
3727         // Set Do Not Track status.
3728         if (doNotTrackEnabled) {
3729             customHeaders.put("DNT", "1");
3730         } else {
3731             customHeaders.remove("DNT");
3732         }
3733
3734         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3735         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3736             if (hideSystemBarsOnFullscreen) {  // Hide everything.
3737                 // Remove the translucent navigation setting if it is currently flagged.
3738                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3739
3740                 // Remove the translucent status bar overlay.
3741                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3742
3743                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3744                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3745
3746                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3747                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3748                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
3749                  */
3750                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3751             } else {  // Hide everything except the status and navigation bars.
3752                 // Add the translucent status flag if it is unset.
3753                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3754
3755                 if (translucentNavigationBarOnFullscreen) {
3756                     // Set the navigation bar to be translucent.
3757                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3758                 } else {
3759                     // Set the navigation bar to be black.
3760                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3761                 }
3762             }
3763         } else {  // Switch to normal viewing mode.
3764             // Reset `inFullScreenBrowsingMode` to `false`.
3765             inFullScreenBrowsingMode = false;
3766
3767             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3768             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3769                 appBar.show();
3770             }
3771
3772             // Show the `BannerAd` in the free flavor.
3773             if (BuildConfig.FLAVOR.contentEquals("free")) {
3774                 // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
3775                 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3776
3777                 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3778                 adView = findViewById(R.id.adview);
3779             }
3780
3781             // Remove the translucent navigation bar flag if it is set.
3782             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3783
3784             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3785             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3786
3787             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3788             rootCoordinatorLayout.setSystemUiVisibility(0);
3789
3790             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3791             rootCoordinatorLayout.setFitsSystemWindows(true);
3792         }
3793     }
3794
3795     // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3796     @SuppressWarnings("deprecation")
3797     private void applyDomainSettings(String url) {
3798         // Reset `navigatingHistory`.
3799         navigatingHistory = false;
3800
3801         // Parse the URL into a URI.
3802         Uri uri = Uri.parse(url);
3803
3804         // Extract the domain from `uri`.
3805         String hostName = uri.getHost();
3806
3807         // Initialize `loadingNewDomainName`.
3808         boolean loadingNewDomainName;
3809
3810         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3811         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3812         //noinspection SimplifiableIfStatement
3813         if ((hostName == null) || (currentDomainName == null)) {
3814             loadingNewDomainName = true;
3815         } else {  // Determine if `hostName` equals `currentDomainName`.
3816             loadingNewDomainName = !hostName.equals(currentDomainName);
3817         }
3818
3819         // Only apply the domain settings if we are loading a new domain.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3820         if (loadingNewDomainName) {
3821             // Set the new `hostname` as the `currentDomainName`.
3822             currentDomainName = hostName;
3823
3824             // Reset `ignorePinnedSslCertificate`.
3825             ignorePinnedSslCertificate = false;
3826
3827             // Reset `favoriteIconBitmap` and display it in the `appbar`.
3828             favoriteIconBitmap = favoriteIconDefaultBitmap;
3829             favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3830
3831             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
3832             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3833             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3834
3835             // Get a full cursor from `domainsDatabaseHelper`.
3836             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3837
3838             // Initialize `domainSettingsSet`.
3839             Set<String> domainSettingsSet = new HashSet<>();
3840
3841             // Get the domain name column index.
3842             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3843
3844             // Populate `domainSettingsSet`.
3845             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3846                 // Move `domainsCursor` to the current row.
3847                 domainNameCursor.moveToPosition(i);
3848
3849                 // Store the domain name in `domainSettingsSet`.
3850                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3851             }
3852
3853             // Close `domainNameCursor.
3854             domainNameCursor.close();
3855
3856             // Initialize variables to track if domain settings will be applied and, if so, under which name.
3857             domainSettingsApplied = false;
3858             String domainNameInDatabase = null;
3859
3860             // Check the hostname.
3861             if (domainSettingsSet.contains(hostName)) {
3862                 domainSettingsApplied = true;
3863                 domainNameInDatabase = hostName;
3864             }
3865
3866             // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3867             if (hostName != null) {
3868                 while (hostName.contains(".") && !domainSettingsApplied) {  // Stop checking if we run out of  `.` or if we already know that `domainSettingsApplied` is `true`.
3869                     if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
3870                         domainSettingsApplied = true;
3871                         domainNameInDatabase = "*." + hostName;
3872                     }
3873
3874                     // Strip out the lowest subdomain of `host`.
3875                     hostName = hostName.substring(hostName.indexOf(".") + 1);
3876                 }
3877             }
3878
3879             // Get a handle for the shared preference.  `this` references the current context.
3880             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3881
3882             // Store the general preference information.
3883             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3884             String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3885             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3886             nightMode = sharedPreferences.getBoolean("night_mode", false);
3887
3888             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
3889                 // Get a cursor for the current host and move it to the first position.
3890                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3891                 currentHostDomainSettingsCursor.moveToFirst();
3892
3893                 // Get the settings from the cursor.
3894                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3895                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3896                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3897                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3898                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3899                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3900                 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3901                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3902                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3903                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3904                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3905                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3906                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3907                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3908                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3909                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3910                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3911
3912                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3913                 switch (nightModeInt) {
3914                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3915                         nightMode = true;
3916                         break;
3917
3918                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3919                         nightMode = false;
3920                         break;
3921                 }
3922
3923                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3924                 if (nightMode) {
3925                     javaScriptEnabled = true;
3926                 }
3927
3928                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3929                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3930                     pinnedDomainSslStartDate = null;
3931                 } else {
3932                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3933                 }
3934
3935                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3936                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3937                     pinnedDomainSslEndDate = null;
3938                 } else {
3939                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3940                 }
3941
3942                 // Close `currentHostDomainSettingsCursor`.
3943                 currentHostDomainSettingsCursor.close();
3944
3945                 // Apply the domain settings.
3946                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3947                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3948                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3949                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3950
3951                 // Apply the font size.
3952                 if (fontSize == 0) {  // Apply the default font size.
3953                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3954                 } else {  // Apply the specified font size.
3955                     mainWebView.getSettings().setTextZoom(fontSize);
3956                 }
3957
3958                 // Set third-party cookies status if API >= 21.
3959                 if (Build.VERSION.SDK_INT >= 21) {
3960                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3961                 }
3962
3963                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
3964                 // <https://redmine.stoutner.com/issues/160>
3965                 if (!urlIsLoading) {
3966                     switch (userAgentString) {
3967                         case "System default user agent":
3968                             // Set the user agent according to the system default.
3969                             switch (defaultUserAgentString) {
3970                                 case "WebView default user agent":
3971                                     // Set the user agent to `""`, which uses the default value.
3972                                     mainWebView.getSettings().setUserAgentString("");
3973                                     break;
3974
3975                                 case "Custom user agent":
3976                                     // Set the custom user agent.
3977                                     mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3978                                     break;
3979
3980                                 default:
3981                                     // Use the selected user agent.
3982                                     mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3983                             }
3984                             break;
3985
3986                         case "WebView default user agent":
3987                             // Set the user agent to `""`, which uses the default value.
3988                             mainWebView.getSettings().setUserAgentString("");
3989                             break;
3990
3991                         default:
3992                             // Use the selected user agent.
3993                             mainWebView.getSettings().setUserAgentString(userAgentString);
3994                     }
3995
3996                     // Store the applied user agent string.
3997                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3998                 }
3999
4000                 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4001                 if (darkTheme) {
4002                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4003                 } else {
4004                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4005                 }
4006             } else {  // The URL we are loading does not have custom domain settings.  Load the defaults.
4007                 // Store the values from `sharedPreferences` in variables.
4008                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4009                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4010                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4011                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4012                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
4013
4014                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4015                 if (nightMode) {
4016                     javaScriptEnabled = true;
4017                 }
4018
4019                 // Apply the default settings.
4020                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4021                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4022                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4023                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4024                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4025
4026                 // Reset the pinned SSL certificate information.
4027                 domainSettingsDatabaseId = -1;
4028                 pinnedDomainSslCertificate = false;
4029                 pinnedDomainSslIssuedToCNameString = "";
4030                 pinnedDomainSslIssuedToONameString = "";
4031                 pinnedDomainSslIssuedToUNameString = "";
4032                 pinnedDomainSslIssuedByCNameString = "";
4033                 pinnedDomainSslIssuedByONameString = "";
4034                 pinnedDomainSslIssuedByUNameString = "";
4035                 pinnedDomainSslStartDate = null;
4036                 pinnedDomainSslEndDate = null;
4037
4038                 // Set third-party cookies status if API >= 21.
4039                 if (Build.VERSION.SDK_INT >= 21) {
4040                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4041                 }
4042
4043                 // Only set the user agent if the webpage is not currently loading.  Otherwise, changing the user agent on redirects can cause the original website to reload.
4044                 // <https://redmine.stoutner.com/issues/160>
4045                 if (!urlIsLoading) {
4046                     switch (defaultUserAgentString) {
4047                         case "WebView default user agent":
4048                             // Set the user agent to `""`, which uses the default value.
4049                             mainWebView.getSettings().setUserAgentString("");
4050                             break;
4051
4052                         case "Custom user agent":
4053                             // Set the custom user agent.
4054                             mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4055                             break;
4056
4057                         default:
4058                             // Use the selected user agent.
4059                             mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
4060                     }
4061
4062                     // Store the applied user agent string.
4063                     appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4064                 }
4065
4066                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4067                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4068             }
4069
4070             // Close `domainsDatabaseHelper`.
4071             domainsDatabaseHelper.close();
4072
4073             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
4074             onTheFlyDisplayImagesSet = false;
4075             setDisplayWebpageImages();
4076
4077             // Update the privacy icons, but only if `mainMenu` has already been populated.
4078             if (mainMenu != null) {
4079                 updatePrivacyIcons(true);
4080             }
4081         }
4082     }
4083
4084     private void setDisplayWebpageImages() {
4085         if (!onTheFlyDisplayImagesSet) {
4086             if (domainSettingsApplied) {  // Custom domain settings are applied.
4087                 switch (displayWebpageImagesInt) {
4088                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4089                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4090                         break;
4091
4092                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4093                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
4094                         break;
4095
4096                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4097                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
4098                         break;
4099                 }
4100             } else {  // Default settings are applied.
4101                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4102             }
4103         }
4104     }
4105
4106     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4107         // Get handles for the icons.
4108         MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4109         MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4110         MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4111         MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
4112
4113         // Update `privacyIcon`.
4114         if (javaScriptEnabled) {  // JavaScript is enabled.
4115             privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
4116         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
4117             privacyIconMenuItem.setIcon(R.drawable.warning);
4118         } else {  // All the dangerous features are disabled.
4119             privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
4120         }
4121
4122         // Update `firstPartyCookiesIcon`.
4123         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
4124             firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
4125         } else {  // First-party cookies are disabled.
4126             if (darkTheme) {
4127                 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4128             } else {
4129                 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
4130             }
4131         }
4132
4133         // Update `domStorageIcon`.
4134         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
4135             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
4136         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
4137             if (darkTheme) {
4138                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4139             } else {
4140                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4141             }
4142         } else {  // JavaScript is disabled, so DOM storage is ghosted.
4143             if (darkTheme) {
4144                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4145             } else {
4146                 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4147             }
4148         }
4149
4150         // Update `formDataIcon`.
4151         if (saveFormDataEnabled) {  // Form data is enabled.
4152             formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
4153         } else {  // Form data is disabled.
4154             if (darkTheme) {
4155                 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
4156             } else {
4157                 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
4158             }
4159         }
4160
4161         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4162         if (runInvalidateOptionsMenu) {
4163             invalidateOptionsMenu();
4164         }
4165     }
4166
4167     private void highlightUrlText() {
4168         String urlString = urlTextBox.getText().toString();
4169
4170         if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4171             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4172         } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4173             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4174         }
4175
4176         // Get the index of the `/` immediately after the domain name.
4177         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4178
4179         // De-emphasize the text after the domain name.
4180         if (endOfDomainName > 0) {
4181             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4182         }
4183     }
4184
4185     private void loadBookmarksFolder() {
4186         // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
4187         bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4188
4189         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
4190         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4191             @Override
4192             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4193                 // Inflate the individual item layout.  `false` does not attach it to the root.
4194                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4195             }
4196
4197             @Override
4198             public void bindView(View view, Context context, Cursor cursor) {
4199                 // Get handles for the views.
4200                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4201                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4202
4203                 // Get the favorite icon byte array from the `Cursor`.
4204                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4205
4206                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4207                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4208
4209                 // Display the bitmap in `bookmarkFavoriteIcon`.
4210                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4211
4212                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4213                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4214                 bookmarkNameTextView.setText(bookmarkNameString);
4215
4216                 // Make the font bold for folders.
4217                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4218                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4219                 } else {  // Reset the font to default for normal bookmarks.
4220                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4221                 }
4222             }
4223         };
4224
4225         // Populate the `ListView` with the adapter.
4226         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4227
4228         // Set the bookmarks drawer title.
4229         if (currentBookmarksFolder.isEmpty()) {
4230             bookmarksTitleTextView.setText(R.string.bookmarks);
4231         } else {
4232             bookmarksTitleTextView.setText(currentBookmarksFolder);
4233         }
4234     }
4235 }