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