Partial bookmarks drawer implemention.
[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                 progressBar.setProgress(progress);
1025                 if (progress < 100) {
1026                     // Show the progress bar.
1027                     progressBar.setVisibility(View.VISIBLE);
1028                 } else {
1029                     // Hide the progress bar.
1030                     progressBar.setVisibility(View.GONE);
1031
1032                     // Inject the night mode CSS if night mode is enabled.
1033                     if (nightMode) {  // Night mode is enabled.
1034                         // `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.
1035                         // `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.
1036                         // `a {color: #1565C0}` sets links to be a dark blue.  `!important` takes precedent over any existing sub-settings.
1037                         mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1038                                 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1039                                 "a {color: #1565C0 !important;}" +
1040                                 "'; parent.appendChild(style)})()", new ValueCallback<String>() {
1041                             @Override
1042                             public void onReceiveValue(String value) {
1043                                 // Initialize a `Handler` to display `mainWebView`.
1044                                 Handler displayWebViewHandler = new Handler();
1045
1046                                 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1047                                 Runnable displayWebViewRunnable = new Runnable() {
1048                                     public void run() {
1049                                         mainWebView.setVisibility(View.VISIBLE);
1050                                     }
1051                                 };
1052
1053                                 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1054                                 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1055                             }
1056                         });
1057                     } else {  // Night mode is disabled.
1058                         // Display `mainWebView` in case it was hidden before loading domain settings.
1059                         mainWebView.setVisibility(View.VISIBLE);
1060                     }
1061
1062                     //Stop the `SwipeToRefresh` indicator if it is running
1063                     swipeRefreshLayout.setRefreshing(false);
1064                 }
1065             }
1066
1067             // Set the favorite icon when it changes.
1068             @Override
1069             public void onReceivedIcon(WebView view, Bitmap icon) {
1070                 // Only update the favorite icon if the website has finished loading.
1071                 if (progressBar.getVisibility() == View.GONE) {
1072                     // Save a copy of the favorite icon.
1073                     favoriteIconBitmap = icon;
1074
1075                     // Place the favorite icon in the appBar.
1076                     favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1077                 }
1078             }
1079
1080             // Save a copy of the title when it changes.
1081             @Override
1082             public void onReceivedTitle(WebView view, String title) {
1083                 // Save a copy of the title.
1084                 webViewTitle = title;
1085             }
1086
1087             // Enter full screen video
1088             @Override
1089             public void onShowCustomView(View view, CustomViewCallback callback) {
1090                 // Pause the ad if this is the free flavor.
1091                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1092                     BannerAd.pauseAd(adView);
1093                 }
1094
1095                 // Remove the translucent overlays.
1096                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1097
1098                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1099                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1100
1101                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1102                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1103                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1104                  */
1105                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1106
1107                 // Set `rootCoordinatorLayout` to fill the entire screen.
1108                 rootCoordinatorLayout.setFitsSystemWindows(false);
1109
1110                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1111                 fullScreenVideoFrameLayout.addView(view);
1112                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1113             }
1114
1115             // Exit full screen video
1116             public void onHideCustomView() {
1117                 // Hide `fullScreenVideoFrameLayout`.
1118                 fullScreenVideoFrameLayout.removeAllViews();
1119                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1120
1121                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1122                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1123
1124                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
1125                 rootCoordinatorLayout.setFitsSystemWindows(true);
1126
1127                 // Show the ad if this is the free flavor.
1128                 if (BuildConfig.FLAVOR.contentEquals("free")) {
1129                     // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
1130                     BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1131
1132                     // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1133                     adView = findViewById(R.id.adview);
1134                 }
1135             }
1136         });
1137
1138         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
1139         registerForContextMenu(mainWebView);
1140
1141         // Allow the downloading of files.
1142         mainWebView.setDownloadListener(new DownloadListener() {
1143             @Override
1144             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1145                 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1146                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1147                 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1148             }
1149         });
1150
1151         // Allow pinch to zoom.
1152         mainWebView.getSettings().setBuiltInZoomControls(true);
1153
1154         // Hide zoom controls.
1155         mainWebView.getSettings().setDisplayZoomControls(false);
1156
1157         // Set `mainWebView` to use a wide viewport.  Otherwise, some web pages will be scrunched and some content will render outside the screen.
1158         mainWebView.getSettings().setUseWideViewPort(true);
1159
1160         // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1161         mainWebView.getSettings().setLoadWithOverviewMode(true);
1162
1163         // Explicitly disable geolocation.
1164         mainWebView.getSettings().setGeolocationEnabled(false);
1165
1166         // Initialize cookieManager.
1167         cookieManager = CookieManager.getInstance();
1168
1169         // 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).
1170         customHeaders.put("X-Requested-With", "");
1171
1172         // 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.
1173         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1174
1175         // Get the intent that started the app.
1176         final Intent launchingIntent = getIntent();
1177
1178         // Extract the launching intent data as `launchingIntentUriData`.
1179         final Uri launchingIntentUriData = launchingIntent.getData();
1180
1181         // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1182         if (launchingIntentUriData != null) {
1183             formattedUrlString = launchingIntentUriData.toString();
1184         }
1185
1186         // Get a handle for the `Runtime`.
1187         privacyBrowserRuntime = Runtime.getRuntime();
1188
1189         // Store the application's private data directory.
1190         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`.
1191
1192         // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1193         inFullScreenBrowsingMode = false;
1194
1195         // Initialize AdView for the free flavor.
1196         adView = findViewById(R.id.adview);
1197
1198         // Initialize the privacy settings variables.
1199         javaScriptEnabled = false;
1200         firstPartyCookiesEnabled = false;
1201         thirdPartyCookiesEnabled = false;
1202         domStorageEnabled = false;
1203         saveFormDataEnabled = false;
1204         nightMode = false;
1205
1206         // Initialize `webViewTitle`.
1207         webViewTitle = getString(R.string.no_title);
1208
1209         // Initialize `favoriteIconBitmap`.  We have to use `ContextCompat` until API >= 21.
1210         Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1211         BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1212         favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1213
1214         // If the favorite icon is null, load the default.
1215         if (favoriteIconBitmap == null) {
1216             favoriteIconBitmap = favoriteIconDefaultBitmap;
1217         }
1218
1219         // Apply the app settings from the shared preferences.
1220         applyAppSettings();
1221
1222         // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1223         if (!waitingForOrbot) {
1224             loadUrl(formattedUrlString);
1225         }
1226     }
1227
1228     @Override
1229     protected void onNewIntent(Intent intent) {
1230         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1231         setIntent(intent);
1232
1233         if (intent.getData() != null) {
1234             // Get the intent data and convert it to a string.
1235             final Uri intentUriData = intent.getData();
1236             formattedUrlString = intentUriData.toString();
1237         }
1238
1239         // Close the navigation drawer if it is open.
1240         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1241             drawerLayout.closeDrawer(GravityCompat.START);
1242         }
1243
1244         // Load the website.
1245         loadUrl(formattedUrlString);
1246
1247         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1248         mainWebView.requestFocus();
1249     }
1250
1251     @Override
1252     public void onRestart() {
1253         super.onRestart();
1254
1255         // Apply the app settings, which may have been changed in `SettingsActivity`.
1256         applyAppSettings();
1257
1258         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1259         updatePrivacyIcons(true);
1260
1261         // Set the display webpage images mode.
1262         setDisplayWebpageImages();
1263
1264         // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1265         if (reloadOnRestart) {
1266             // Reload `mainWebView`.
1267             mainWebView.reload();
1268
1269             // Reset `reloadOnRestartBoolean`.
1270             reloadOnRestart = false;
1271         }
1272
1273         // Load the URL on restart to apply changes to night mode.
1274         if (loadUrlOnRestart) {
1275             // Load the current `formattedUrlString`.
1276             loadUrl(formattedUrlString);
1277
1278             // Reset `loadUrlOnRestart.
1279             loadUrlOnRestart = false;
1280         }
1281     }
1282
1283     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1284     @Override
1285     public void onResume() {
1286         super.onResume();
1287
1288         // Resume JavaScript (if enabled).
1289         mainWebView.resumeTimers();
1290
1291         // Resume `mainWebView`.
1292         mainWebView.onResume();
1293
1294         // Resume the adView for the free flavor.
1295         if (BuildConfig.FLAVOR.contentEquals("free")) {
1296             BannerAd.resumeAd(adView);
1297         }
1298     }
1299
1300     @Override
1301     public void onPause() {
1302         // Pause `mainWebView`.
1303         mainWebView.onPause();
1304
1305         // Stop all JavaScript.
1306         mainWebView.pauseTimers();
1307
1308         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1309         if (BuildConfig.FLAVOR.contentEquals("free")) {
1310             BannerAd.pauseAd(adView);
1311         }
1312
1313         super.onPause();
1314     }
1315
1316     @Override
1317     public boolean onCreateOptionsMenu(Menu menu) {
1318         // Inflate the menu; this adds items to the action bar if it is present.
1319         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1320
1321         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1322         mainMenu = menu;
1323
1324         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
1325         updatePrivacyIcons(false);
1326
1327         // Get handles for the menu items.
1328         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1329         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1330         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1331         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1332
1333         // Only display third-party cookies if SDK >= 21
1334         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1335
1336         // Get the shared preference values.  `this` references the current context.
1337         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1338
1339         // Set the status of the additional app bar icons.  The default is `false`.
1340         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1341             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1342             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1343             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1344         } else { //Do not display the additional icons.
1345             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1346             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1347             toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1348         }
1349
1350         return true;
1351     }
1352
1353     @Override
1354     public boolean onPrepareOptionsMenu(Menu menu) {
1355         // Get handles for the menu items.
1356         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1357         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1358         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1359         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1360         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1361         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1362         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1363         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1364         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1365         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1366
1367         // Set the status of the menu item checkboxes.
1368         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1369         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1370         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1371         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1372         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1373
1374         // Enable third-party cookies if first-party cookies are enabled.
1375         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1376
1377         // Enable `DOM Storage` if JavaScript is enabled.
1378         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1379
1380         // Enable `Clear Cookies` if there are any.
1381         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1382
1383         // Get a count of the number of files in the `Local Storage` directory.
1384         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1385         int localStorageDirectoryNumberOfFiles = 0;
1386         if (localStorageDirectory.exists()) {
1387             localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1388         }
1389
1390         // Get a count of the number of files in the `IndexedDB` directory.
1391         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1392         int indexedDBDirectoryNumberOfFiles = 0;
1393         if (indexedDBDirectory.exists()) {
1394             indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1395         }
1396
1397         // Enable `Clear DOM Storage` if there is any.
1398         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1399
1400         // Enable `Clear Form Data` is there is any.
1401         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1402         clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1403
1404         // Initialize font size variables.
1405         int fontSize = mainWebView.getSettings().getTextZoom();
1406         String fontSizeTitle;
1407         MenuItem selectedFontSizeMenuItem;
1408
1409         // Prepare the font size title and current size menu item.
1410         switch (fontSize) {
1411             case 25:
1412                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1413                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1414                 break;
1415
1416             case 50:
1417                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1418                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1419                 break;
1420
1421             case 75:
1422                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1423                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1424                 break;
1425
1426             case 100:
1427                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1428                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1429                 break;
1430
1431             case 125:
1432                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1433                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1434                 break;
1435
1436             case 150:
1437                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1438                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1439                 break;
1440
1441             case 175:
1442                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1443                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1444                 break;
1445
1446             case 200:
1447                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1448                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1449                 break;
1450
1451             default:
1452                 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1453                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1454                 break;
1455         }
1456
1457         // Set the font size title and select the current size menu item.
1458         fontSizeMenuItem.setTitle(fontSizeTitle);
1459         selectedFontSizeMenuItem.setChecked(true);
1460
1461         // Only show `Refresh` if `swipeToRefresh` is disabled.
1462         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1463
1464         // Run all the other default commands.
1465         super.onPrepareOptionsMenu(menu);
1466
1467         // `return true` displays the menu.
1468         return true;
1469     }
1470
1471     @Override
1472     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1473     @SuppressLint("SetJavaScriptEnabled")
1474     // removeAllCookies is deprecated, but it is required for API < 21.
1475     @SuppressWarnings("deprecation")
1476     public boolean onOptionsItemSelected(MenuItem menuItem) {
1477         int menuItemId = menuItem.getItemId();
1478
1479         // Set the commands that relate to the menu entries.
1480         switch (menuItemId) {
1481             case R.id.toggle_javascript:
1482                 // Switch the status of javaScriptEnabled.
1483                 javaScriptEnabled = !javaScriptEnabled;
1484
1485                 // Apply the new JavaScript status.
1486                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1487
1488                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1489                 updatePrivacyIcons(true);
1490
1491                 // Display a `Snackbar`.
1492                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1493                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1494                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1495                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1496                 } else {  // Privacy mode.
1497                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1498                 }
1499
1500                 // Reload the WebView.
1501                 mainWebView.reload();
1502                 return true;
1503
1504             case R.id.toggle_first_party_cookies:
1505                 // Switch the status of firstPartyCookiesEnabled.
1506                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1507
1508                 // Update the menu checkbox.
1509                 menuItem.setChecked(firstPartyCookiesEnabled);
1510
1511                 // Apply the new cookie status.
1512                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1513
1514                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1515                 updatePrivacyIcons(true);
1516
1517                 // Display a `Snackbar`.
1518                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1519                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1520                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
1521                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1522                 } else {  // Privacy mode.
1523                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1524                 }
1525
1526                 // Reload the WebView.
1527                 mainWebView.reload();
1528                 return true;
1529
1530             case R.id.toggle_third_party_cookies:
1531                 if (Build.VERSION.SDK_INT >= 21) {
1532                     // Switch the status of thirdPartyCookiesEnabled.
1533                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1534
1535                     // Update the menu checkbox.
1536                     menuItem.setChecked(thirdPartyCookiesEnabled);
1537
1538                     // Apply the new cookie status.
1539                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1540
1541                     // Display a `Snackbar`.
1542                     if (thirdPartyCookiesEnabled) {
1543                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1544                     } else {
1545                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1546                     }
1547
1548                     // Reload the WebView.
1549                     mainWebView.reload();
1550                 } // Else do nothing because SDK < 21.
1551                 return true;
1552
1553             case R.id.toggle_dom_storage:
1554                 // Switch the status of domStorageEnabled.
1555                 domStorageEnabled = !domStorageEnabled;
1556
1557                 // Update the menu checkbox.
1558                 menuItem.setChecked(domStorageEnabled);
1559
1560                 // Apply the new DOM Storage status.
1561                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1562
1563                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1564                 updatePrivacyIcons(true);
1565
1566                 // Display a `Snackbar`.
1567                 if (domStorageEnabled) {
1568                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1569                 } else {
1570                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1571                 }
1572
1573                 // Reload the WebView.
1574                 mainWebView.reload();
1575                 return true;
1576
1577             case R.id.toggle_save_form_data:
1578                 // Switch the status of saveFormDataEnabled.
1579                 saveFormDataEnabled = !saveFormDataEnabled;
1580
1581                 // Update the menu checkbox.
1582                 menuItem.setChecked(saveFormDataEnabled);
1583
1584                 // Apply the new form data status.
1585                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1586
1587                 // Display a `Snackbar`.
1588                 if (saveFormDataEnabled) {
1589                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1590                 } else {
1591                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1592                 }
1593
1594                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1595                 updatePrivacyIcons(true);
1596
1597                 // Reload the WebView.
1598                 mainWebView.reload();
1599                 return true;
1600
1601             case R.id.clear_cookies:
1602                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1603                         .setAction(R.string.undo, new View.OnClickListener() {
1604                             @Override
1605                             public void onClick(View v) {
1606                                 // Do nothing because everything will be handled by `onDismissed()` below.
1607                             }
1608                         })
1609                         .addCallback(new Snackbar.Callback() {
1610                             @Override
1611                             public void onDismissed(Snackbar snackbar, int event) {
1612                                 switch (event) {
1613                                     // The user pushed the `Undo` button.
1614                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1615                                         // Do nothing.
1616                                         break;
1617
1618                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1619                                     default:
1620                                         // `cookieManager.removeAllCookie()` varies by SDK.
1621                                         if (Build.VERSION.SDK_INT < 21) {
1622                                             cookieManager.removeAllCookie();
1623                                         } else {
1624                                             // `null` indicates no callback.
1625                                             cookieManager.removeAllCookies(null);
1626                                         }
1627                                 }
1628                             }
1629                         })
1630                         .show();
1631                 return true;
1632
1633             case R.id.clear_dom_storage:
1634                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1635                         .setAction(R.string.undo, new View.OnClickListener() {
1636                             @Override
1637                             public void onClick(View v) {
1638                                 // Do nothing because everything will be handled by `onDismissed()` below.
1639                             }
1640                         })
1641                         .addCallback(new Snackbar.Callback() {
1642                             @Override
1643                             public void onDismissed(Snackbar snackbar, int event) {
1644                                 switch (event) {
1645                                     // The user pushed the `Undo` button.
1646                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1647                                         // Do nothing.
1648                                         break;
1649
1650                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1651                                     default:
1652                                         // Delete the DOM Storage.
1653                                         WebStorage webStorage = WebStorage.getInstance();
1654                                         webStorage.deleteAllData();
1655
1656                                         // Manually remove `IndexedDB` if it exists.
1657                                         try {
1658                                             privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1659                                         } catch (IOException e) {
1660                                             // Do nothing if an error is thrown.
1661                                         }
1662                                 }
1663                             }
1664                         })
1665                         .show();
1666                 return true;
1667
1668             case R.id.clear_form_data:
1669                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1670                         .setAction(R.string.undo, new View.OnClickListener() {
1671                             @Override
1672                             public void onClick(View v) {
1673                                 // Do nothing because everything will be handled by `onDismissed()` below.
1674                             }
1675                         })
1676                         .addCallback(new Snackbar.Callback() {
1677                             @Override
1678                             public void onDismissed(Snackbar snackbar, int event) {
1679                                 switch (event) {
1680                                     // The user pushed the `Undo` button.
1681                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1682                                         // Do nothing.
1683                                         break;
1684
1685                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1686                                     default:
1687                                         // Delete the form data.
1688                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1689                                         mainWebViewDatabase.clearFormData();
1690                                 }
1691                             }
1692                         })
1693                         .show();
1694                 return true;
1695
1696             case R.id.font_size_twenty_five_percent:
1697                 mainWebView.getSettings().setTextZoom(25);
1698                 return true;
1699
1700             case R.id.font_size_fifty_percent:
1701                 mainWebView.getSettings().setTextZoom(50);
1702                 return true;
1703
1704             case R.id.font_size_seventy_five_percent:
1705                 mainWebView.getSettings().setTextZoom(75);
1706                 return true;
1707
1708             case R.id.font_size_one_hundred_percent:
1709                 mainWebView.getSettings().setTextZoom(100);
1710                 return true;
1711
1712             case R.id.font_size_one_hundred_twenty_five_percent:
1713                 mainWebView.getSettings().setTextZoom(125);
1714                 return true;
1715
1716             case R.id.font_size_one_hundred_fifty_percent:
1717                 mainWebView.getSettings().setTextZoom(150);
1718                 return true;
1719
1720             case R.id.font_size_one_hundred_seventy_five_percent:
1721                 mainWebView.getSettings().setTextZoom(175);
1722                 return true;
1723
1724             case R.id.font_size_two_hundred_percent:
1725                 mainWebView.getSettings().setTextZoom(200);
1726                 return true;
1727
1728             case R.id.display_images:
1729                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1730                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
1731                     mainWebView.reload();
1732                 } else {  // Images are not currently loaded automatically.
1733                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
1734                 }
1735
1736                 // Set `onTheFlyDisplayImagesSet`.
1737                 onTheFlyDisplayImagesSet = true;
1738                 return true;
1739
1740             case R.id.share:
1741                 // Setup the share string.
1742                 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1743
1744                 // Create the share intent.
1745                 Intent shareIntent = new Intent();
1746                 shareIntent.setAction(Intent.ACTION_SEND);
1747                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1748                 shareIntent.setType("text/plain");
1749
1750                 // Make it so.
1751                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1752                 return true;
1753
1754             case R.id.find_on_page:
1755                 // Hide the URL app bar.
1756                 supportAppBar.setVisibility(View.GONE);
1757
1758                 // Show the Find on Page `RelativeLayout`.
1759                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1760
1761                 // 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
1762                 findOnPageEditText.postDelayed(new Runnable() {
1763                     @Override
1764                     public void run()
1765                     {
1766                         // Set the focus on `findOnPageEditText`.
1767                         findOnPageEditText.requestFocus();
1768
1769                         // Display the keyboard.  `0` sets no input flags.
1770                         inputMethodManager.showSoftInput(findOnPageEditText, 0);
1771                     }
1772                 }, 200);
1773                 return true;
1774
1775             case R.id.print:
1776                 // Get a `PrintManager` instance.
1777                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1778
1779                 // Convert `mainWebView` to `printDocumentAdapter`.
1780                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1781
1782                 // Print the document.  The print attributes are `null`.
1783                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1784                 return true;
1785
1786             case R.id.add_to_homescreen:
1787                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1788                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1789                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1790
1791                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1792                 return true;
1793
1794             case R.id.refresh:
1795                 mainWebView.reload();
1796                 return true;
1797
1798             default:
1799                 // Don't consume the event.
1800                 return super.onOptionsItemSelected(menuItem);
1801         }
1802     }
1803
1804     // removeAllCookies is deprecated, but it is required for API < 21.
1805     @SuppressWarnings("deprecation")
1806     @Override
1807     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1808         int menuItemId = menuItem.getItemId();
1809
1810         switch (menuItemId) {
1811             case R.id.home:
1812                 loadUrl(homepage);
1813                 break;
1814
1815             case R.id.back:
1816                 if (mainWebView.canGoBack()) {
1817                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1818                     navigatingHistory = true;
1819
1820                     // Load the previous website in the history.
1821                     mainWebView.goBack();
1822                 }
1823                 break;
1824
1825             case R.id.forward:
1826                 if (mainWebView.canGoForward()) {
1827                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1828                     navigatingHistory = true;
1829
1830                     // Load the next website in the history.
1831                     mainWebView.goForward();
1832                 }
1833                 break;
1834
1835             case R.id.history:
1836                 // Get the `WebBackForwardList`.
1837                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1838
1839                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
1840                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1841                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1842                 break;
1843
1844             case R.id.bookmarks:
1845                 // Launch BookmarksActivity.
1846                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1847                 startActivity(bookmarksIntent);
1848                 break;
1849
1850             case R.id.downloads:
1851                 // Launch the system Download Manager.
1852                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1853
1854                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1855                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1856
1857                 startActivity(downloadManagerIntent);
1858                 break;
1859
1860             case R.id.settings:
1861                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1862                 currentDomainName = "";
1863
1864                 // Launch `SettingsActivity`.
1865                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1866                 startActivity(settingsIntent);
1867                 break;
1868
1869             case R.id.domains:
1870                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1871                 currentDomainName = "";
1872
1873                 // Launch `DomainsActivity`.
1874                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1875                 startActivity(domainsIntent);
1876                 break;
1877
1878             case R.id.guide:
1879                 // Launch `GuideActivity`.
1880                 Intent guideIntent = new Intent(this, GuideActivity.class);
1881                 startActivity(guideIntent);
1882                 break;
1883
1884             case R.id.about:
1885                 // Launch `AboutActivity`.
1886                 Intent aboutIntent = new Intent(this, AboutActivity.class);
1887                 startActivity(aboutIntent);
1888                 break;
1889
1890             case R.id.clearAndExit:
1891                 // Get a handle for `sharedPreferences`.  `this` references the current context.
1892                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1893
1894                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1895
1896                 // Clear cookies.
1897                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1898                     // The command to remove cookies changed slightly in API 21.
1899                     if (Build.VERSION.SDK_INT >= 21) {
1900                         cookieManager.removeAllCookies(null);
1901                     } else {
1902                         cookieManager.removeAllCookie();
1903                     }
1904
1905                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1906                     try {
1907                         // We have to use two commands because `Runtime.exec()` does not like `*`.
1908                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1909                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1910                     } catch (IOException e) {
1911                         // Do nothing if an error is thrown.
1912                     }
1913                 }
1914
1915                 // Clear DOM storage.
1916                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1917                     // Ask `WebStorage` to clear the DOM storage.
1918                     WebStorage webStorage = WebStorage.getInstance();
1919                     webStorage.deleteAllData();
1920
1921                     // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1922                     try {
1923                         // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1924                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1925
1926                         // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1927                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1928                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1929                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1930                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1931                     } catch (IOException e) {
1932                         // Do nothing if an error is thrown.
1933                     }
1934                 }
1935
1936                 // Clear form data.
1937                 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1938                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1939                     webViewDatabase.clearFormData();
1940
1941                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1942                     try {
1943                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1944                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1945                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1946                     } catch (IOException e) {
1947                         // Do nothing if an error is thrown.
1948                     }
1949                 }
1950
1951                 // Clear the cache.
1952                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1953                     // `true` includes disk files.
1954                     mainWebView.clearCache(true);
1955
1956                     // Manually delete the cache directories.
1957                     try {
1958                         // Delete the main cache directory.
1959                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1960
1961                         // 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.
1962                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1963                     } catch (IOException e) {
1964                         // Do nothing if an error is thrown.
1965                     }
1966                 }
1967
1968                 // Clear SSL certificate preferences.
1969                 mainWebView.clearSslPreferences();
1970
1971                 // Clear the back/forward history.
1972                 mainWebView.clearHistory();
1973
1974                 // Clear `formattedUrlString`.
1975                 formattedUrlString = null;
1976
1977                 // Clear `customHeaders`.
1978                 customHeaders.clear();
1979
1980                 // Detach all views from `mainWebViewRelativeLayout`.
1981                 mainWebViewRelativeLayout.removeAllViews();
1982
1983                 // Destroy the internal state of `mainWebView`.
1984                 mainWebView.destroy();
1985
1986                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1987                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1988                 if (clearEverything) {
1989                     try {
1990                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1991                     } catch (IOException e) {
1992                         // Do nothing if an error is thrown.
1993                     }
1994                 }
1995
1996                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1997                 if (Build.VERSION.SDK_INT >= 21) {
1998                     finishAndRemoveTask();
1999                 } else {
2000                     finish();
2001                 }
2002
2003                 // Remove the terminated program from RAM.  The status code is `0`.
2004                 System.exit(0);
2005                 break;
2006         }
2007
2008         // Close the navigation drawer.
2009         drawerLayout.closeDrawer(GravityCompat.START);
2010         return true;
2011     }
2012
2013     @Override
2014     public void onPostCreate(Bundle savedInstanceState) {
2015         super.onPostCreate(savedInstanceState);
2016
2017         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2018         drawerToggle.syncState();
2019     }
2020
2021     @Override
2022     public void onConfigurationChanged(Configuration newConfig) {
2023         super.onConfigurationChanged(newConfig);
2024
2025         // Reload the ad for the free flavor if we are not in full screen mode.
2026         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2027             // Reload the ad.
2028             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2029
2030             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2031             adView = findViewById(R.id.adview);
2032         }
2033
2034         // `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
2035         // ActivityCompat.invalidateOptionsMenu(this);
2036     }
2037
2038     @Override
2039     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2040         // Store the `HitTestResult`.
2041         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2042
2043         // Create strings.
2044         final String imageUrl;
2045         final String linkUrl;
2046
2047         // Get a handle for the `ClipboardManager`.
2048         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2049
2050         switch (hitTestResult.getType()) {
2051             // `SRC_ANCHOR_TYPE` is a link.
2052             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2053                 // Get the target URL.
2054                 linkUrl = hitTestResult.getExtra();
2055
2056                 // Set the target URL as the title of the `ContextMenu`.
2057                 menu.setHeaderTitle(linkUrl);
2058
2059                 // Add a `Load URL` entry.
2060                 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2061                     @Override
2062                     public boolean onMenuItemClick(MenuItem item) {
2063                         loadUrl(linkUrl);
2064                         return false;
2065                     }
2066                 });
2067
2068                 // Add a `Copy URL` entry.
2069                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2070                     @Override
2071                     public boolean onMenuItemClick(MenuItem item) {
2072                         // Save the link URL in a `ClipData`.
2073                         ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2074
2075                         // Set the `ClipData` as the clipboard's primary clip.
2076                         clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2077                         return false;
2078                     }
2079                 });
2080
2081                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2082                 menu.add(R.string.cancel);
2083                 break;
2084
2085             case WebView.HitTestResult.EMAIL_TYPE:
2086                 // Get the target URL.
2087                 linkUrl = hitTestResult.getExtra();
2088
2089                 // Set the target URL as the title of the `ContextMenu`.
2090                 menu.setHeaderTitle(linkUrl);
2091
2092                 // Add a `Write Email` entry.
2093                 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2094                     @Override
2095                     public boolean onMenuItemClick(MenuItem item) {
2096                         // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2097                         Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2098
2099                         // Parse the url and set it as the data for the `Intent`.
2100                         emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2101
2102                         // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2103                         emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2104
2105                         // Make it so.
2106                         startActivity(emailIntent);
2107                         return false;
2108                     }
2109                 });
2110
2111                 // Add a `Copy Email Address` entry.
2112                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2113                     @Override
2114                     public boolean onMenuItemClick(MenuItem item) {
2115                         // Save the email address in a `ClipData`.
2116                         ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2117
2118                         // Set the `ClipData` as the clipboard's primary clip.
2119                         clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2120                         return false;
2121                     }
2122                 });
2123
2124                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2125                 menu.add(R.string.cancel);
2126                 break;
2127
2128             // `IMAGE_TYPE` is an image.
2129             case WebView.HitTestResult.IMAGE_TYPE:
2130                 // Get the image URL.
2131                 imageUrl = hitTestResult.getExtra();
2132
2133                 // Set the image URL as the title of the `ContextMenu`.
2134                 menu.setHeaderTitle(imageUrl);
2135
2136                 // Add a `View Image` entry.
2137                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2138                     @Override
2139                     public boolean onMenuItemClick(MenuItem item) {
2140                         loadUrl(imageUrl);
2141                         return false;
2142                     }
2143                 });
2144
2145                 // Add a `Download Image` entry.
2146                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2147                     @Override
2148                     public boolean onMenuItemClick(MenuItem item) {
2149                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2150                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2151                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2152                         return false;
2153                     }
2154                 });
2155
2156                 // Add a `Copy URL` entry.
2157                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2158                     @Override
2159                     public boolean onMenuItemClick(MenuItem item) {
2160                         // Save the image URL in a `ClipData`.
2161                         ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2162
2163                         // Set the `ClipData` as the clipboard's primary clip.
2164                         clipboardManager.setPrimaryClip(srcImageTypeClipData);
2165                         return false;
2166                     }
2167                 });
2168
2169                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2170                 menu.add(R.string.cancel);
2171                 break;
2172
2173
2174             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2175             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2176                 // Get the image URL.
2177                 imageUrl = hitTestResult.getExtra();
2178
2179                 // Set the image URL as the title of the `ContextMenu`.
2180                 menu.setHeaderTitle(imageUrl);
2181
2182                 // Add a `View Image` entry.
2183                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2184                     @Override
2185                     public boolean onMenuItemClick(MenuItem item) {
2186                         loadUrl(imageUrl);
2187                         return false;
2188                     }
2189                 });
2190
2191                 // Add a `Download Image` entry.
2192                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2193                     @Override
2194                     public boolean onMenuItemClick(MenuItem item) {
2195                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2196                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2197                         downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2198                         return false;
2199                     }
2200                 });
2201
2202                 // Add a `Copy URL` entry.
2203                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2204                     @Override
2205                     public boolean onMenuItemClick(MenuItem item) {
2206                         // Save the image URL in a `ClipData`.
2207                         ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2208
2209                         // Set the `ClipData` as the clipboard's primary clip.
2210                         clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2211                         return false;
2212                     }
2213                 });
2214
2215                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2216                 menu.add(R.string.cancel);
2217                 break;
2218         }
2219     }
2220
2221     @Override
2222     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2223         // Get shortcutNameEditText from the alert dialog.
2224         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2225
2226         // Create the bookmark shortcut based on formattedUrlString.
2227         Intent bookmarkShortcut = new Intent();
2228         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2229         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2230
2231         // Place the bookmark shortcut on the home screen.
2232         Intent placeBookmarkShortcut = new Intent();
2233         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2234         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2235         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2236         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2237         sendBroadcast(placeBookmarkShortcut);
2238     }
2239
2240     @Override
2241     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2242         // Download the image if it has an HTTP or HTTPS URI.
2243         if (imageUrl.startsWith("http")) {
2244             // Get a handle for the system `DOWNLOAD_SERVICE`.
2245             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2246
2247             // Parse `imageUrl`.
2248             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2249
2250             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
2251             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2252             if (firstPartyCookiesEnabled) {
2253                 // Get the cookies for `imageUrl`.
2254                 String cookies = cookieManager.getCookie(imageUrl);
2255
2256                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2257                 downloadRequest.addRequestHeader("Cookie", cookies);
2258             }
2259
2260             // Get the file name from `dialogFragment`.
2261             EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2262             String imageName = downloadImageNameEditText.getText().toString();
2263
2264             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2265             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2266                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2267             } else { // Only set the title using `imageName`.
2268                 downloadRequest.setTitle(imageName);
2269             }
2270
2271             // Allow `MediaScanner` to index the download if it is a media file.
2272             downloadRequest.allowScanningByMediaScanner();
2273
2274             // Add the URL as the description for the download.
2275             downloadRequest.setDescription(imageUrl);
2276
2277             // Show the download notification after the download is completed.
2278             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2279
2280             // Initiate the download.
2281             downloadManager.enqueue(downloadRequest);
2282         } else {  // The image is not an HTTP or HTTPS URI.
2283             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2284         }
2285     }
2286
2287     @Override
2288     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2289         // Download the file if it has an HTTP or HTTPS URI.
2290         if (downloadUrl.startsWith("http")) {
2291
2292             // Get a handle for the system `DOWNLOAD_SERVICE`.
2293             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2294
2295             // Parse `downloadUrl`.
2296             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2297
2298             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
2299             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2300             if (firstPartyCookiesEnabled) {
2301                 // Get the cookies for `downloadUrl`.
2302                 String cookies = cookieManager.getCookie(downloadUrl);
2303
2304                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2305                 downloadRequest.addRequestHeader("Cookie", cookies);
2306             }
2307
2308             // Get the file name from `dialogFragment`.
2309             EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2310             String fileName = downloadFileNameEditText.getText().toString();
2311
2312             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2313             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2314                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2315             } else { // Only set the title using `fileName`.
2316                 downloadRequest.setTitle(fileName);
2317             }
2318
2319             // Allow `MediaScanner` to index the download if it is a media file.
2320             downloadRequest.allowScanningByMediaScanner();
2321
2322             // Add the URL as the description for the download.
2323             downloadRequest.setDescription(downloadUrl);
2324
2325             // Show the download notification after the download is completed.
2326             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2327
2328             // Initiate the download.
2329             downloadManager.enqueue(downloadRequest);
2330         } else {  // The download is not an HTTP or HTTPS URI.
2331             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2332         }
2333     }
2334
2335     @Override
2336     public void onHttpAuthenticationCancel() {
2337         // Cancel the `HttpAuthHandler`.
2338         httpAuthHandler.cancel();
2339     }
2340
2341     @Override
2342     public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2343         // Get handles for the `EditTexts`.
2344         EditText usernameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2345         EditText passwordEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2346
2347         // Proceed with the HTTP authentication.
2348         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2349     }
2350
2351     public void viewSslCertificate(View view) {
2352         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2353         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2354         viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2355     }
2356
2357     @Override
2358     public void onSslErrorCancel() {
2359         sslErrorHandler.cancel();
2360     }
2361
2362     @Override
2363     public void onSslErrorProceed() {
2364         sslErrorHandler.proceed();
2365     }
2366
2367     @Override
2368     public void onSslMismatchBack() {
2369         if (mainWebView.canGoBack()) {  // There is a back page in the history.
2370             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2371             navigatingHistory = true;
2372
2373             // Go back.
2374             mainWebView.goBack();
2375         } else {  // There are no pages to go back to.
2376             // Load a blank page
2377             loadUrl("");
2378         }
2379     }
2380
2381     @Override
2382     public void onSslMismatchProceed() {
2383         // Do not check the pinned SSL certificate for this domain again until the domain changes.
2384         ignorePinnedSslCertificate = true;
2385     }
2386
2387     @Override
2388     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2389         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2390         navigatingHistory = true;
2391
2392         // Load the history entry.
2393         mainWebView.goBackOrForward(moveBackOrForwardSteps);
2394     }
2395
2396     @Override
2397     public void onClearHistory() {
2398         // Clear the history.
2399         mainWebView.clearHistory();
2400     }
2401
2402     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2403     @Override
2404     public void onBackPressed() {
2405         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
2406             // Close the navigation drawer.
2407             drawerLayout.closeDrawer(GravityCompat.START);
2408         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
2409             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
2410                 // close the bookmarks drawer.
2411                 drawerLayout.closeDrawer(GravityCompat.END);
2412             } else {  // A subfolder is displayed.
2413                 // Place the former parent folder in `currentFolder`.
2414                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2415
2416                 // Load the new folder.
2417                 loadBookmarksFolder();
2418             }
2419
2420         } else if (mainWebView.canGoBack()) {  // There is at least one item in the `WebView` history.
2421             // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2422             navigatingHistory = true;
2423
2424             // Go back.
2425             mainWebView.goBack();
2426         } else {  // There isn't anything to do in Privacy Browser.
2427             // Pass `onBackPressed()` to the system.
2428             super.onBackPressed();
2429         }
2430     }
2431
2432     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2433         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
2434         String unformattedUrlString = urlTextBox.getText().toString().trim();
2435
2436         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
2437         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2438             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
2439             if (!unformattedUrlString.startsWith("http")) {
2440                 unformattedUrlString = "http://" + unformattedUrlString;
2441             }
2442
2443             // Initialize `unformattedUrl`.
2444             URL unformattedUrl = null;
2445
2446             // 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.
2447             try {
2448                 unformattedUrl = new URL(unformattedUrlString);
2449             } catch (MalformedURLException e) {
2450                 e.printStackTrace();
2451             }
2452
2453             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2454             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2455             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2456             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2457             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2458             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2459
2460             // Build the URI.
2461             Uri.Builder formattedUri = new Uri.Builder();
2462             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2463
2464             // Decode `formattedUri` as a `String` in `UTF-8`.
2465             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2466         } else {
2467             // Sanitize the search input and convert it to a search.
2468             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2469
2470             // Add the base search URL.
2471             formattedUrlString = searchURL + encodedUrlString;
2472         }
2473
2474         loadUrl(formattedUrlString);
2475
2476         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2477         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2478     }
2479
2480
2481     private void loadUrl(String url) {
2482         // Apply any custom domain settings.
2483         applyDomainSettings(url);
2484
2485         // Load the URL.
2486         mainWebView.loadUrl(url, customHeaders);
2487
2488         // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2489         urlIsLoading = true;
2490     }
2491
2492     public void findPreviousOnPage(View view) {
2493         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
2494         mainWebView.findNext(false);
2495     }
2496
2497     public void findNextOnPage(View view) {
2498         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2499         mainWebView.findNext(true);
2500     }
2501
2502     public void closeFindOnPage(View view) {
2503         // Delete the contents of `find_on_page_edittext`.
2504         findOnPageEditText.setText(null);
2505
2506         // Clear the highlighted phrases.
2507         mainWebView.clearMatches();
2508
2509         // Hide the Find on Page `RelativeLayout`.
2510         findOnPageLinearLayout.setVisibility(View.GONE);
2511
2512         // Show the URL app bar.
2513         supportAppBar.setVisibility(View.VISIBLE);
2514
2515         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2516         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2517     }
2518
2519     private void applyAppSettings() {
2520         // Get a handle for `sharedPreferences`.  `this` references the current context.
2521         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2522
2523         // Store the values from `sharedPreferences` in variables.
2524         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2525         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2526         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2527         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2528         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2529         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2530         adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2531         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2532         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2533         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2534         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2535         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2536         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2537         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2538         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2539
2540         // Set the homepage, search, and proxy options.
2541         if (proxyThroughOrbot) {  // Set the Tor options.
2542             // Set `torHomepageString` as `homepage`.
2543             homepage = torHomepageString;
2544
2545             // If formattedUrlString is null assign the homepage to it.
2546             if (formattedUrlString == null) {
2547                 formattedUrlString = homepage;
2548             }
2549
2550             // Set the search URL.
2551             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
2552                 searchURL = torSearchCustomURLString;
2553             } else {  // Use the string from the pre-built list.
2554                 searchURL = torSearchString;
2555             }
2556
2557             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
2558             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2559
2560             // Set the `appBar` background to indicate proxying through Orbot is enabled.  `this` refers to the context.
2561             if (darkTheme) {
2562                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2563             } else {
2564                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2565             }
2566
2567             // Display a message to the user if we are waiting on Orbot.
2568             if (!orbotStatus.equals("ON")) {
2569                 // Set `waitingForOrbot`.
2570                 waitingForOrbot = true;
2571
2572                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
2573                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2574             }
2575         } else {  // Set the non-Tor options.
2576             // Set `homepageString` as `homepage`.
2577             homepage = homepageString;
2578
2579             // If formattedUrlString is null assign the homepage to it.
2580             if (formattedUrlString == null) {
2581                 formattedUrlString = homepage;
2582             }
2583
2584             // Set the search URL.
2585             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
2586                 searchURL = searchCustomURLString;
2587             } else {  // Use the string from the pre-built list.
2588                 searchURL = searchString;
2589             }
2590
2591             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
2592             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2593
2594             // Set the default `appBar` background.  `this` refers to the context.
2595             if (darkTheme) {
2596                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2597             } else {
2598                 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2599             }
2600
2601             // Reset `waitingForOrbot.
2602             waitingForOrbot = false;
2603         }
2604
2605         // Set swipe to refresh.
2606         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2607
2608         // Set Do Not Track status.
2609         if (doNotTrackEnabled) {
2610             customHeaders.put("DNT", "1");
2611         } else {
2612             customHeaders.remove("DNT");
2613         }
2614
2615         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2616         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2617             if (hideSystemBarsOnFullscreen) {  // Hide everything.
2618                 // Remove the translucent navigation setting if it is currently flagged.
2619                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2620
2621                 // Remove the translucent status bar overlay.
2622                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2623
2624                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2625                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2626
2627                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2628                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2629                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2630                  */
2631                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2632             } else {  // Hide everything except the status and navigation bars.
2633                 // Add the translucent status flag if it is unset.
2634                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2635
2636                 if (translucentNavigationBarOnFullscreen) {
2637                     // Set the navigation bar to be translucent.
2638                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2639                 } else {
2640                     // Set the navigation bar to be black.
2641                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2642                 }
2643             }
2644         } else {  // Switch to normal viewing mode.
2645             // Reset `inFullScreenBrowsingMode` to `false`.
2646             inFullScreenBrowsingMode = false;
2647
2648             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2649             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2650                 appBar.show();
2651             }
2652
2653             // Show the `BannerAd` in the free flavor.
2654             if (BuildConfig.FLAVOR.contentEquals("free")) {
2655                 // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
2656                 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2657
2658                 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2659                 adView = findViewById(R.id.adview);
2660             }
2661
2662             // Remove the translucent navigation bar flag if it is set.
2663             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2664
2665             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2666             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2667
2668             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2669             rootCoordinatorLayout.setSystemUiVisibility(0);
2670
2671             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2672             rootCoordinatorLayout.setFitsSystemWindows(true);
2673         }
2674     }
2675
2676     // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2677     @SuppressWarnings("deprecation")
2678     private void applyDomainSettings(String url) {
2679         // Reset `navigatingHistory`.
2680         navigatingHistory = false;
2681
2682         // Parse the URL into a URI.
2683         Uri uri = Uri.parse(url);
2684
2685         // Extract the domain from `uri`.
2686         String hostName = uri.getHost();
2687
2688         // Initialize `loadingNewDomainName`.
2689         boolean loadingNewDomainName;
2690
2691         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2692         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2693         //noinspection SimplifiableIfStatement
2694         if ((hostName == null) || (currentDomainName == null)) {
2695             loadingNewDomainName = true;
2696         } else {  // Determine if `hostName` equals `currentDomainName`.
2697             loadingNewDomainName = !hostName.equals(currentDomainName);
2698         }
2699
2700         // 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.
2701         if (loadingNewDomainName) {
2702             // Set the new `hostname` as the `currentDomainName`.
2703             currentDomainName = hostName;
2704
2705             // Reset `ignorePinnedSslCertificate`.
2706             ignorePinnedSslCertificate = false;
2707
2708             // Reset `favoriteIconBitmap` and display it in the `appbar`.
2709             favoriteIconBitmap = favoriteIconDefaultBitmap;
2710             favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2711
2712             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
2713             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2714             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2715
2716             // Get a full cursor from `domainsDatabaseHelper`.
2717             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2718
2719             // Initialize `domainSettingsSet`.
2720             Set<String> domainSettingsSet = new HashSet<>();
2721
2722             // Get the domain name column index.
2723             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2724
2725             // Populate `domainSettingsSet`.
2726             for (int i = 0; i < domainNameCursor.getCount(); i++) {
2727                 // Move `domainsCursor` to the current row.
2728                 domainNameCursor.moveToPosition(i);
2729
2730                 // Store the domain name in `domainSettingsSet`.
2731                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2732             }
2733
2734             // Close `domainNameCursor.
2735             domainNameCursor.close();
2736
2737             // Initialize variables to track if domain settings will be applied and, if so, under which name.
2738             domainSettingsApplied = false;
2739             String domainNameInDatabase = null;
2740
2741             // Check the hostname.
2742             if (domainSettingsSet.contains(hostName)) {
2743                 domainSettingsApplied = true;
2744                 domainNameInDatabase = hostName;
2745             }
2746
2747             // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2748             if (hostName != null) {
2749                 while (hostName.contains(".") && !domainSettingsApplied) {  // Stop checking if we run out of  `.` or if we already know that `domainSettingsApplied` is `true`.
2750                     if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
2751                         domainSettingsApplied = true;
2752                         domainNameInDatabase = "*." + hostName;
2753                     }
2754
2755                     // Strip out the lowest subdomain of `host`.
2756                     hostName = hostName.substring(hostName.indexOf(".") + 1);
2757                 }
2758             }
2759
2760             // Get a handle for the shared preference.  `this` references the current context.
2761             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2762
2763             // Store the general preference information.
2764             String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2765             String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2766             String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2767             nightMode = sharedPreferences.getBoolean("night_mode", false);
2768
2769             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
2770                 // Get a cursor for the current host and move it to the first position.
2771                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2772                 currentHostDomainSettingsCursor.moveToFirst();
2773
2774                 // Get the settings from the cursor.
2775                 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2776                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2777                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2778                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2779                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2780                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2781                 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2782                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2783                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2784                 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
2785                 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2786                 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2787                 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2788                 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2789                 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2790                 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2791                 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2792
2793                 // Set `nightMode` according to `nightModeInt`.  If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
2794                 switch (nightModeInt) {
2795                     case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
2796                         nightMode = true;
2797                         break;
2798
2799                     case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
2800                         nightMode = false;
2801                         break;
2802                 }
2803
2804                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2805                 if (nightMode) {
2806                     javaScriptEnabled = true;
2807                 }
2808
2809                 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2810                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2811                     pinnedDomainSslStartDate = null;
2812                 } else {
2813                     pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2814                 }
2815
2816                 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2817                 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2818                     pinnedDomainSslEndDate = null;
2819                 } else {
2820                     pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2821                 }
2822
2823                 // Close `currentHostDomainSettingsCursor`.
2824                 currentHostDomainSettingsCursor.close();
2825
2826                 // Apply the domain settings.
2827                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2828                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2829                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2830                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2831
2832                 // Apply the font size.
2833                 if (fontSize == 0) {  // Apply the default font size.
2834                     mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2835                 } else {  // Apply the specified font size.
2836                     mainWebView.getSettings().setTextZoom(fontSize);
2837                 }
2838
2839                 // Set third-party cookies status if API >= 21.
2840                 if (Build.VERSION.SDK_INT >= 21) {
2841                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2842                 }
2843
2844                 // 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>
2845                 if (!urlIsLoading) {
2846                     switch (userAgentString) {
2847                         case "System default user agent":
2848                             // Set the user agent according to the system default.
2849                             switch (defaultUserAgentString) {
2850                                 case "WebView default user agent":
2851                                     // Set the user agent to `""`, which uses the default value.
2852                                     mainWebView.getSettings().setUserAgentString("");
2853                                     break;
2854
2855                                 case "Custom user agent":
2856                                     // Set the custom user agent.
2857                                     mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2858                                     break;
2859
2860                                 default:
2861                                     // Use the selected user agent.
2862                                     mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2863                             }
2864                             break;
2865
2866                         case "WebView default user agent":
2867                             // Set the user agent to `""`, which uses the default value.
2868                             mainWebView.getSettings().setUserAgentString("");
2869                             break;
2870
2871                         default:
2872                             // Use the selected user agent.
2873                             mainWebView.getSettings().setUserAgentString(userAgentString);
2874                     }
2875                 }
2876
2877                 // 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.
2878                 if (darkTheme) {
2879                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2880                 } else {
2881                     urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2882                 }
2883             } else {  // The URL we are loading does not have custom domain settings.  Load the defaults.
2884                 // Store the values from `sharedPreferences` in variables.
2885                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2886                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2887                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2888                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2889                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2890
2891                 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2892                 if (nightMode) {
2893                     javaScriptEnabled = true;
2894                 }
2895
2896                 // Apply the default settings.
2897                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2898                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2899                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2900                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2901                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2902
2903                 // Reset the pinned SSL certificate information.
2904                 domainSettingsDatabaseId = -1;
2905                 pinnedDomainSslCertificate = false;
2906                 pinnedDomainSslIssuedToCNameString = "";
2907                 pinnedDomainSslIssuedToONameString = "";
2908                 pinnedDomainSslIssuedToUNameString = "";
2909                 pinnedDomainSslIssuedByCNameString = "";
2910                 pinnedDomainSslIssuedByONameString = "";
2911                 pinnedDomainSslIssuedByUNameString = "";
2912                 pinnedDomainSslStartDate = null;
2913                 pinnedDomainSslEndDate = null;
2914
2915                 // Set third-party cookies status if API >= 21.
2916                 if (Build.VERSION.SDK_INT >= 21) {
2917                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2918                 }
2919
2920                 // 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><