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