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