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