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