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