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