Add Russian strings translation. Partial EasyList Implementation.
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
8  * Privacy Browser is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.annotation.SuppressLint;
25 import android.app.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