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