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