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