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