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