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