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