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