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