]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Ghost the sections of the URL that are not the FQDN. Closes https://redmine.stoutner...
[PrivacyBrowserAndroid.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.scrollTo(0, 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 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         // Get handles for the menu items.
1086         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1087         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1088         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1089         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1090         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1091         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1092         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1093         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1094         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1095
1096         // Set the status of the menu item checkboxes.
1097         toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1098         toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1099         toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1100         toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1101         displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1102
1103         // Enable third-party cookies if first-party cookies are enabled.
1104         toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1105
1106         // Enable DOM Storage if JavaScript is enabled.
1107         toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1108
1109         // Enable Clear Cookies if there are any.
1110         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1111
1112         // Enable Clear Form Data is there is any.
1113         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1114         clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1115
1116         // Initialize font size variables.
1117         int fontSize = mainWebView.getSettings().getTextZoom();
1118         String fontSizeTitle;
1119         MenuItem selectedFontSizeMenuItem;
1120
1121         // Prepare the font size title and current size menu item.
1122         switch (fontSize) {
1123             case 25:
1124                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1125                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1126                 break;
1127
1128             case 50:
1129                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1130                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1131                 break;
1132
1133             case 75:
1134                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1135                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1136                 break;
1137
1138             case 100:
1139                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1140                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1141                 break;
1142
1143             case 125:
1144                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1145                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1146                 break;
1147
1148             case 150:
1149                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1150                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1151                 break;
1152
1153             case 175:
1154                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1155                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1156                 break;
1157
1158             case 200:
1159                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1160                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1161                 break;
1162
1163             default:
1164                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1165                 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1166                 break;
1167         }
1168
1169         // Set the font size title and select the current size menu item.
1170         fontSizeMenuItem.setTitle(fontSizeTitle);
1171         selectedFontSizeMenuItem.setChecked(true);
1172
1173         // Only show `Refresh` if `swipeToRefresh` is disabled.
1174         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1175
1176         // Run all the other default commands.
1177         super.onPrepareOptionsMenu(menu);
1178
1179         // `return true` displays the menu.
1180         return true;
1181     }
1182
1183     @Override
1184     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1185     @SuppressLint("SetJavaScriptEnabled")
1186     // removeAllCookies is deprecated, but it is required for API < 21.
1187     @SuppressWarnings("deprecation")
1188     public boolean onOptionsItemSelected(MenuItem menuItem) {
1189         int menuItemId = menuItem.getItemId();
1190
1191         // Set the commands that relate to the menu entries.
1192         switch (menuItemId) {
1193             case R.id.toggle_javascript:
1194                 // Switch the status of javaScriptEnabled.
1195                 javaScriptEnabled = !javaScriptEnabled;
1196
1197                 // Apply the new JavaScript status.
1198                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1199
1200                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1201                 updatePrivacyIcons(true);
1202
1203                 // Display a `Snackbar`.
1204                 if (javaScriptEnabled) {  // JavaScrip is enabled.
1205                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1206                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
1207                     Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1208                 } else {  // Privacy mode.
1209                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1210                 }
1211
1212                 // Reload the WebView.
1213                 mainWebView.reload();
1214                 return true;
1215
1216             case R.id.toggle_first_party_cookies:
1217                 // Switch the status of firstPartyCookiesEnabled.
1218                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1219
1220                 // Update the menu checkbox.
1221                 menuItem.setChecked(firstPartyCookiesEnabled);
1222
1223                 // Apply the new cookie status.
1224                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1225
1226                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1227                 updatePrivacyIcons(true);
1228
1229                 // Display a `Snackbar`.
1230                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1231                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1232                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
1233                     Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1234                 } else {  // Privacy mode.
1235                     Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1236                 }
1237
1238                 // Reload the WebView.
1239                 mainWebView.reload();
1240                 return true;
1241
1242             case R.id.toggle_third_party_cookies:
1243                 if (Build.VERSION.SDK_INT >= 21) {
1244                     // Switch the status of thirdPartyCookiesEnabled.
1245                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1246
1247                     // Update the menu checkbox.
1248                     menuItem.setChecked(thirdPartyCookiesEnabled);
1249
1250                     // Apply the new cookie status.
1251                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1252
1253                     // Display a `Snackbar`.
1254                     if (thirdPartyCookiesEnabled) {
1255                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1256                     } else {
1257                         Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1258                     }
1259
1260                     // Reload the WebView.
1261                     mainWebView.reload();
1262                 } // Else do nothing because SDK < 21.
1263                 return true;
1264
1265             case R.id.toggle_dom_storage:
1266                 // Switch the status of domStorageEnabled.
1267                 domStorageEnabled = !domStorageEnabled;
1268
1269                 // Update the menu checkbox.
1270                 menuItem.setChecked(domStorageEnabled);
1271
1272                 // Apply the new DOM Storage status.
1273                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1274
1275                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1276                 updatePrivacyIcons(true);
1277
1278                 // Display a `Snackbar`.
1279                 if (domStorageEnabled) {
1280                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1281                 } else {
1282                     Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1283                 }
1284
1285                 // Reload the WebView.
1286                 mainWebView.reload();
1287                 return true;
1288
1289             case R.id.toggle_save_form_data:
1290                 // Switch the status of saveFormDataEnabled.
1291                 saveFormDataEnabled = !saveFormDataEnabled;
1292
1293                 // Update the menu checkbox.
1294                 menuItem.setChecked(saveFormDataEnabled);
1295
1296                 // Apply the new form data status.
1297                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1298
1299                 // Display a `Snackbar`.
1300                 if (saveFormDataEnabled) {
1301                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1302                 } else {
1303                     Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1304                 }
1305
1306                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1307                 updatePrivacyIcons(true);
1308
1309                 // Reload the WebView.
1310                 mainWebView.reload();
1311                 return true;
1312
1313             case R.id.clear_cookies:
1314                 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1315                         .setAction(R.string.undo, new View.OnClickListener() {
1316                             @Override
1317                             public void onClick(View v) {
1318                                 // Do nothing because everything will be handled by `onDismissed()` below.
1319                             }
1320                         })
1321                         .addCallback(new Snackbar.Callback() {
1322                             @Override
1323                             public void onDismissed(Snackbar snackbar, int event) {
1324                                 switch (event) {
1325                                     // The user pushed the `Undo` button.
1326                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1327                                         // Do nothing.
1328                                         break;
1329
1330                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1331                                     default:
1332                                         // `cookieManager.removeAllCookie()` varies by SDK.
1333                                         if (Build.VERSION.SDK_INT < 21) {
1334                                             cookieManager.removeAllCookie();
1335                                         } else {
1336                                             // `null` indicates no callback.
1337                                             cookieManager.removeAllCookies(null);
1338                                         }
1339                                 }
1340                             }
1341                         })
1342                         .show();
1343                 return true;
1344
1345             case R.id.clear_dom_storage:
1346                 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1347                         .setAction(R.string.undo, new View.OnClickListener() {
1348                             @Override
1349                             public void onClick(View v) {
1350                                 // Do nothing because everything will be handled by `onDismissed()` below.
1351                             }
1352                         })
1353                         .addCallback(new Snackbar.Callback() {
1354                             @Override
1355                             public void onDismissed(Snackbar snackbar, int event) {
1356                                 switch (event) {
1357                                     // The user pushed the `Undo` button.
1358                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1359                                         // Do nothing.
1360                                         break;
1361
1362                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1363                                     default:
1364                                         // Delete the DOM Storage.
1365                                         WebStorage webStorage = WebStorage.getInstance();
1366                                         webStorage.deleteAllData();
1367                                 }
1368                             }
1369                         })
1370                         .show();
1371                 return true;
1372
1373             case R.id.clear_form_data:
1374                 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1375                         .setAction(R.string.undo, new View.OnClickListener() {
1376                             @Override
1377                             public void onClick(View v) {
1378                                 // Do nothing because everything will be handled by `onDismissed()` below.
1379                             }
1380                         })
1381                         .addCallback(new Snackbar.Callback() {
1382                             @Override
1383                             public void onDismissed(Snackbar snackbar, int event) {
1384                                 switch (event) {
1385                                     // The user pushed the `Undo` button.
1386                                     case Snackbar.Callback.DISMISS_EVENT_ACTION:
1387                                         // Do nothing.
1388                                         break;
1389
1390                                     // The `Snackbar` was dismissed without the `Undo` button being pushed.
1391                                     default:
1392                                         // Delete the form data.
1393                                         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1394                                         mainWebViewDatabase.clearFormData();
1395                                 }
1396                             }
1397                         })
1398                         .show();
1399                 return true;
1400
1401             case R.id.font_size_twenty_five_percent:
1402                 mainWebView.getSettings().setTextZoom(25);
1403                 return true;
1404
1405             case R.id.font_size_fifty_percent:
1406                 mainWebView.getSettings().setTextZoom(50);
1407                 return true;
1408
1409             case R.id.font_size_seventy_five_percent:
1410                 mainWebView.getSettings().setTextZoom(75);
1411                 return true;
1412
1413             case R.id.font_size_one_hundred_percent:
1414                 mainWebView.getSettings().setTextZoom(100);
1415                 return true;
1416
1417             case R.id.font_size_one_hundred_twenty_five_percent:
1418                 mainWebView.getSettings().setTextZoom(125);
1419                 return true;
1420
1421             case R.id.font_size_one_hundred_fifty_percent:
1422                 mainWebView.getSettings().setTextZoom(150);
1423                 return true;
1424
1425             case R.id.font_size_one_hundred_seventy_five_percent:
1426                 mainWebView.getSettings().setTextZoom(175);
1427                 return true;
1428
1429             case R.id.font_size_two_hundred_percent:
1430                 mainWebView.getSettings().setTextZoom(200);
1431                 return true;
1432
1433             case R.id.display_images:
1434                 if (mainWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1435                     mainWebView.getSettings().setLoadsImagesAutomatically(false);
1436                     mainWebView.reload();
1437                 } else {  // Images are not currently loaded automatically.
1438                     mainWebView.getSettings().setLoadsImagesAutomatically(true);
1439                 }
1440
1441                 // Set `onTheFlyDisplayImagesSet`.
1442                 onTheFlyDisplayImagesSet = true;
1443                 return true;
1444
1445             case R.id.share:
1446                 // Setup the share string.
1447                 String shareString;
1448                 if (webViewTitle != null) {
1449                     shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1450                 } else {
1451                     shareString = urlTextBox.getText().toString();
1452                 }
1453
1454                 // Create the share intent.
1455                 Intent shareIntent = new Intent();
1456                 shareIntent.setAction(Intent.ACTION_SEND);
1457                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1458                 shareIntent.setType("text/plain");
1459
1460                 // Make it so.
1461                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1462                 return true;
1463
1464             case R.id.find_on_page:
1465                 // Hide the URL app bar.
1466                 supportAppBar.setVisibility(View.GONE);
1467
1468                 // Show the Find on Page `RelativeLayout`.
1469                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1470
1471                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
1472                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1473                 findOnPageEditText.postDelayed(new Runnable()
1474                 {
1475                     @Override
1476                     public void run()
1477                     {
1478                         // Set the focus on `findOnPageEditText`.
1479                         findOnPageEditText.requestFocus();
1480
1481                         // Display the keyboard.
1482                         inputMethodManager.showSoftInput(findOnPageEditText, 0);
1483                     }
1484                 }, 200);
1485                 return true;
1486
1487             case R.id.print:
1488                 // Get a `PrintManager` instance.
1489                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1490
1491                 // Convert `mainWebView` to `printDocumentAdapter`.
1492                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1493
1494                 // Print the document.  The print attributes are `null`.
1495                 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1496                 return true;
1497
1498             case R.id.add_to_homescreen:
1499                 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1500                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1501                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1502
1503                 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1504                 return true;
1505
1506             case R.id.refresh:
1507                 mainWebView.reload();
1508                 return true;
1509
1510             default:
1511                 // Don't consume the event.
1512                 return super.onOptionsItemSelected(menuItem);
1513         }
1514     }
1515
1516     // removeAllCookies is deprecated, but it is required for API < 21.
1517     @SuppressWarnings("deprecation")
1518     @Override
1519     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1520         int menuItemId = menuItem.getItemId();
1521
1522         switch (menuItemId) {
1523             case R.id.home:
1524                 loadUrl(homepage);
1525                 break;
1526
1527             case R.id.back:
1528                 if (mainWebView.canGoBack()) {
1529                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1530                     navigatingHistory = true;
1531
1532                     // Load the previous website in the history.
1533                     mainWebView.goBack();
1534                 }
1535                 break;
1536
1537             case R.id.forward:
1538                 if (mainWebView.canGoForward()) {
1539                     // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1540                     navigatingHistory = true;
1541
1542                     // Load the next website in the history.
1543                     mainWebView.goForward();
1544                 }
1545                 break;
1546
1547             case R.id.history:
1548                 // Get the `WebBackForwardList`.
1549                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1550
1551                 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
1552                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1553                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1554                 break;
1555
1556             case R.id.bookmarks:
1557                 // Launch BookmarksActivity.
1558                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1559                 startActivity(bookmarksIntent);
1560                 break;
1561
1562             case R.id.downloads:
1563                 // Launch the system Download Manager.
1564                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1565
1566                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1567                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1568
1569                 startActivity(downloadManagerIntent);
1570                 break;
1571
1572             case R.id.settings:
1573                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1574                 currentDomainName = "";
1575
1576                 // Launch `SettingsActivity`.
1577                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1578                 startActivity(settingsIntent);
1579                 break;
1580
1581             case R.id.domains:
1582                 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1583                 currentDomainName = "";
1584
1585                 // Launch `DomainsActivity`.
1586                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1587                 startActivity(domainsIntent);
1588                 break;
1589
1590             case R.id.guide:
1591                 // Launch `GuideActivity`.
1592                 Intent guideIntent = new Intent(this, GuideActivity.class);
1593                 startActivity(guideIntent);
1594                 break;
1595
1596             case R.id.about:
1597                 // Launch `AboutActivity`.
1598                 Intent aboutIntent = new Intent(this, AboutActivity.class);
1599                 startActivity(aboutIntent);
1600                 break;
1601
1602             case R.id.clearAndExit:
1603                 // Get a handle for `sharedPreferences`.  `this` references the current context.
1604                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1605
1606                 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1607
1608                 // Clear cookies.
1609                 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1610                     // The command to remove cookies changed slightly in API 21.
1611                     if (Build.VERSION.SDK_INT >= 21) {
1612                         cookieManager.removeAllCookies(null);
1613                     } else {
1614                         cookieManager.removeAllCookie();
1615                     }
1616
1617                     // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1618                     try {
1619                         // We have to use two commands because `Runtime.exec()` does not like `*`.
1620                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1621                         privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1622                     } catch (IOException e) {
1623                         // Do nothing if an error is thrown.
1624                     }
1625                 }
1626
1627                 // Clear DOM storage.
1628                 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1629                     // Ask `WebStorage` to clear the DOM storage.
1630                     WebStorage webStorage = WebStorage.getInstance();
1631                     webStorage.deleteAllData();
1632
1633                     // Manually delete the DOM storage directory, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1634                     try {
1635                         // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1636                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1637                     } catch (IOException e) {
1638                         // Do nothing if an error is thrown.
1639                     }
1640                 }
1641
1642                 // Clear form data.
1643                 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1644                     WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1645                     webViewDatabase.clearFormData();
1646
1647                     // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1648                     try {
1649                         // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1650                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1651                         privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1652                     } catch (IOException e) {
1653                         // Do nothing if an error is thrown.
1654                     }
1655                 }
1656
1657                 // Clear the cache.
1658                 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1659                     // `true` includes disk files.
1660                     mainWebView.clearCache(true);
1661
1662                     // Manually delete the cache directories.
1663                     try {
1664                         // Delete the main cache directory.
1665                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1666
1667                         // 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.
1668                         privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1669                     } catch (IOException e) {
1670                         // Do nothing if an error is thrown.
1671                     }
1672                 }
1673
1674                 // Clear SSL certificate preferences.
1675                 mainWebView.clearSslPreferences();
1676
1677                 // Clear the back/forward history.
1678                 mainWebView.clearHistory();
1679
1680                 // Clear `formattedUrlString`.
1681                 formattedUrlString = null;
1682
1683                 // Clear `customHeaders`.
1684                 customHeaders.clear();
1685
1686                 // Detach all views from `mainWebViewRelativeLayout`.
1687                 mainWebViewRelativeLayout.removeAllViews();
1688
1689                 // Destroy the internal state of `mainWebView`.
1690                 mainWebView.destroy();
1691
1692                 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1693                 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1694                 if (clearEverything) {
1695                     try {
1696                         privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1697                     } catch (IOException e) {
1698                         // Do nothing if an error is thrown.
1699                     }
1700                 }
1701
1702                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1703                 if (Build.VERSION.SDK_INT >= 21) {
1704                     finishAndRemoveTask();
1705                 } else {
1706                     finish();
1707                 }
1708
1709                 // Remove the terminated program from RAM.  The status code is `0`.
1710                 System.exit(0);
1711                 break;
1712         }
1713
1714         // Close the navigation drawer.
1715         drawerLayout.closeDrawer(GravityCompat.START);
1716         return true;
1717     }
1718
1719     @Override
1720     public void onPostCreate(Bundle savedInstanceState) {
1721         super.onPostCreate(savedInstanceState);
1722
1723         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1724         drawerToggle.syncState();
1725     }
1726
1727     @Override
1728     public void onConfigurationChanged(Configuration newConfig) {
1729         super.onConfigurationChanged(newConfig);
1730
1731         // Reload the ad for the free flavor if we are not in full screen mode.
1732         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1733             // Reload the ad.
1734             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1735
1736             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1737             adView = findViewById(R.id.adview);
1738         }
1739
1740         // `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
1741         // ActivityCompat.invalidateOptionsMenu(this);
1742     }
1743
1744     @Override
1745     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1746         // Store the `HitTestResult`.
1747         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1748
1749         // Create strings.
1750         final String imageUrl;
1751         final String linkUrl;
1752
1753         // Get a handle for the `ClipboardManager`.
1754         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1755
1756         switch (hitTestResult.getType()) {
1757             // `SRC_ANCHOR_TYPE` is a link.
1758             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1759                 // Get the target URL.
1760                 linkUrl = hitTestResult.getExtra();
1761
1762                 // Set the target URL as the title of the `ContextMenu`.
1763                 menu.setHeaderTitle(linkUrl);
1764
1765                 // Add a `Load URL` entry.
1766                 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1767                     @Override
1768                     public boolean onMenuItemClick(MenuItem item) {
1769                         loadUrl(linkUrl);
1770                         return false;
1771                     }
1772                 });
1773
1774                 // Add a `Copy URL` entry.
1775                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1776                     @Override
1777                     public boolean onMenuItemClick(MenuItem item) {
1778                         // Save the link URL in a `ClipData`.
1779                         ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1780
1781                         // Set the `ClipData` as the clipboard's primary clip.
1782                         clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1783                         return false;
1784                     }
1785                 });
1786
1787                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1788                 menu.add(R.string.cancel);
1789                 break;
1790
1791             case WebView.HitTestResult.EMAIL_TYPE:
1792                 // Get the target URL.
1793                 linkUrl = hitTestResult.getExtra();
1794
1795                 // Set the target URL as the title of the `ContextMenu`.
1796                 menu.setHeaderTitle(linkUrl);
1797
1798                 // Add a `Write Email` entry.
1799                 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1800                     @Override
1801                     public boolean onMenuItemClick(MenuItem item) {
1802                         // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1803                         Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1804
1805                         // Parse the url and set it as the data for the `Intent`.
1806                         emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1807
1808                         // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1809                         emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1810
1811                         // Make it so.
1812                         startActivity(emailIntent);
1813                         return false;
1814                     }
1815                 });
1816
1817                 // Add a `Copy Email Address` entry.
1818                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1819                     @Override
1820                     public boolean onMenuItemClick(MenuItem item) {
1821                         // Save the email address in a `ClipData`.
1822                         ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1823
1824                         // Set the `ClipData` as the clipboard's primary clip.
1825                         clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1826                         return false;
1827                     }
1828                 });
1829
1830                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1831                 menu.add(R.string.cancel);
1832                 break;
1833
1834             // `IMAGE_TYPE` is an image.
1835             case WebView.HitTestResult.IMAGE_TYPE:
1836                 // Get the image URL.
1837                 imageUrl = hitTestResult.getExtra();
1838
1839                 // Set the image URL as the title of the `ContextMenu`.
1840                 menu.setHeaderTitle(imageUrl);
1841
1842                 // Add a `View Image` entry.
1843                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1844                     @Override
1845                     public boolean onMenuItemClick(MenuItem item) {
1846                         loadUrl(imageUrl);
1847                         return false;
1848                     }
1849                 });
1850
1851                 // Add a `Download Image` entry.
1852                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1853                     @Override
1854                     public boolean onMenuItemClick(MenuItem item) {
1855                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1856                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1857                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1858                         return false;
1859                     }
1860                 });
1861
1862                 // Add a `Copy URL` entry.
1863                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1864                     @Override
1865                     public boolean onMenuItemClick(MenuItem item) {
1866                         // Save the image URL in a `ClipData`.
1867                         ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1868
1869                         // Set the `ClipData` as the clipboard's primary clip.
1870                         clipboardManager.setPrimaryClip(srcImageTypeClipData);
1871                         return false;
1872                     }
1873                 });
1874
1875                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1876                 menu.add(R.string.cancel);
1877                 break;
1878
1879
1880             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1881             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1882                 // Get the image URL.
1883                 imageUrl = hitTestResult.getExtra();
1884
1885                 // Set the image URL as the title of the `ContextMenu`.
1886                 menu.setHeaderTitle(imageUrl);
1887
1888                 // Add a `View Image` entry.
1889                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1890                     @Override
1891                     public boolean onMenuItemClick(MenuItem item) {
1892                         loadUrl(imageUrl);
1893                         return false;
1894                     }
1895                 });
1896
1897                 // Add a `Download Image` entry.
1898                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1899                     @Override
1900                     public boolean onMenuItemClick(MenuItem item) {
1901                         // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1902                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1903                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1904                         return false;
1905                     }
1906                 });
1907
1908                 // Add a `Copy URL` entry.
1909                 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1910                     @Override
1911                     public boolean onMenuItemClick(MenuItem item) {
1912                         // Save the image URL in a `ClipData`.
1913                         ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1914
1915                         // Set the `ClipData` as the clipboard's primary clip.
1916                         clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1917                         return false;
1918                     }
1919                 });
1920
1921                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1922                 menu.add(R.string.cancel);
1923                 break;
1924         }
1925     }
1926
1927     @Override
1928     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1929         // Get shortcutNameEditText from the alert dialog.
1930         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1931
1932         // Create the bookmark shortcut based on formattedUrlString.
1933         Intent bookmarkShortcut = new Intent();
1934         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1935         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1936
1937         // Place the bookmark shortcut on the home screen.
1938         Intent placeBookmarkShortcut = new Intent();
1939         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1940         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1941         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1942         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1943         sendBroadcast(placeBookmarkShortcut);
1944     }
1945
1946     @Override
1947     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1948         // Download the image if it has an HTTP or HTTPS URI.
1949         if (imageUrl.startsWith("http")) {
1950             // Get a handle for the system `DOWNLOAD_SERVICE`.
1951             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1952
1953             // Parse `imageUrl`.
1954             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1955
1956             // Pass cookies to download manager if cookies are enabled.  This is required to download images from websites that require a login.
1957             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
1958             if (firstPartyCookiesEnabled) {
1959                 // Get the cookies for `imageUrl`.
1960                 String cookies = cookieManager.getCookie(imageUrl);
1961
1962                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
1963                 downloadRequest.addRequestHeader("Cookie", cookies);
1964             }
1965
1966             // Get the file name from `dialogFragment`.
1967             EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1968             String imageName = downloadImageNameEditText.getText().toString();
1969
1970             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1971             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1972                 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1973             } else { // Only set the title using `imageName`.
1974                 downloadRequest.setTitle(imageName);
1975             }
1976
1977             // Allow `MediaScanner` to index the download if it is a media file.
1978             downloadRequest.allowScanningByMediaScanner();
1979
1980             // Add the URL as the description for the download.
1981             downloadRequest.setDescription(imageUrl);
1982
1983             // Show the download notification after the download is completed.
1984             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1985
1986             // Initiate the download.
1987             downloadManager.enqueue(downloadRequest);
1988         } else {  // The image is not an HTTP or HTTPS URI.
1989             Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1990         }
1991     }
1992
1993     @Override
1994     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1995         // Download the file if it has an HTTP or HTTPS URI.
1996         if (downloadUrl.startsWith("http")) {
1997
1998             // Get a handle for the system `DOWNLOAD_SERVICE`.
1999             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2000
2001             // Parse `downloadUrl`.
2002             DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2003
2004             // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
2005             // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2006             if (firstPartyCookiesEnabled) {
2007                 // Get the cookies for `downloadUrl`.
2008                 String cookies = cookieManager.getCookie(downloadUrl);
2009
2010                 // Add the cookies to `downloadRequest`.  In the HTTP request header, cookies are named `Cookie`.
2011                 downloadRequest.addRequestHeader("Cookie", cookies);
2012             }
2013
2014             // Get the file name from `dialogFragment`.
2015             EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2016             String fileName = downloadFileNameEditText.getText().toString();
2017
2018             // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2019             if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2020                 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2021             } else { // Only set the title using `fileName`.
2022                 downloadRequest.setTitle(fileName);
2023             }
2024
2025             // Allow `MediaScanner` to index the download if it is a media file.
2026             downloadRequest.allowScanningByMediaScanner();
2027
2028             // Add the URL as the description for the download.
2029             downloadRequest.setDescription(downloadUrl);
2030
2031             // Show the download notification after the download is completed.
2032             downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2033
2034             // Initiate the download.
2035             downloadManager.enqueue(downloadRequest);
2036         } else {  // The download is not an HTTP or HTTPS URI.
2037             Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2038         }
2039     }
2040
2041     public void viewSslCertificate(View view) {
2042         // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2043         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2044         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2045     }
2046
2047     @Override
2048     public void onSslErrorCancel() {
2049         sslErrorHandler.cancel();
2050     }
2051
2052     @Override
2053     public void onSslErrorProceed() {
2054         sslErrorHandler.proceed();
2055     }
2056
2057     @Override
2058     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2059         // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2060         navigatingHistory = true;
2061
2062         // Load the history entry.
2063         mainWebView.goBackOrForward(moveBackOrForwardSteps);
2064     }
2065
2066     @Override
2067     public void onClearHistory() {
2068         // Clear the history.
2069         mainWebView.clearHistory();
2070     }
2071
2072     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2073     @Override
2074     public void onBackPressed() {
2075         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2076         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2077             drawerLayout.closeDrawer(GravityCompat.START);
2078         } else {
2079             // Load the previous URL if available.
2080             if (mainWebView.canGoBack()) {
2081                 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2082                 navigatingHistory = true;
2083
2084                 // Go back.
2085                 mainWebView.goBack();
2086             } else {
2087                 // Pass `onBackPressed()` to the system.
2088                 super.onBackPressed();
2089             }
2090         }
2091     }
2092
2093     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2094         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
2095         String unformattedUrlString = urlTextBox.getText().toString().trim();
2096
2097         // Check to see if `unformattedUrlString` is a valid URL.  Otherwise, convert it into a search.
2098         if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2099             // Add `http://` at the beginning if it is missing.  Otherwise the app will segfault.
2100             if (!unformattedUrlString.startsWith("http")) {
2101                 unformattedUrlString = "http://" + unformattedUrlString;
2102             }
2103
2104             // Initialize `unformattedUrl`.
2105             URL unformattedUrl = null;
2106
2107             // 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.
2108             try {
2109                 unformattedUrl = new URL(unformattedUrlString);
2110             } catch (MalformedURLException e) {
2111                 e.printStackTrace();
2112             }
2113
2114             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2115             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2116             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2117             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2118             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2119             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2120
2121             // Build the URI.
2122             Uri.Builder formattedUri = new Uri.Builder();
2123             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2124
2125             // Decode `formattedUri` as a `String` in `UTF-8`.
2126             formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2127         } else {
2128             // Sanitize the search input and convert it to a search.
2129             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2130
2131             // Add the base search URL.
2132             formattedUrlString = searchURL + encodedUrlString;
2133         }
2134
2135         loadUrl(formattedUrlString);
2136
2137         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2138         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2139     }
2140
2141
2142     private void loadUrl(String url) {
2143         // Apply any custom domain settings.
2144         applyDomainSettings(url);
2145
2146         // Load the URL.
2147         mainWebView.loadUrl(url, customHeaders);
2148     }
2149
2150     public void findPreviousOnPage(View view) {
2151         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
2152         mainWebView.findNext(false);
2153     }
2154
2155     public void findNextOnPage(View view) {
2156         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2157         mainWebView.findNext(true);
2158     }
2159
2160     public void closeFindOnPage(View view) {
2161         // Delete the contents of `find_on_page_edittext`.
2162         findOnPageEditText.setText(null);
2163
2164         // Clear the highlighted phrases.
2165         mainWebView.clearMatches();
2166
2167         // Hide the Find on Page `RelativeLayout`.
2168         findOnPageLinearLayout.setVisibility(View.GONE);
2169
2170         // Show the URL app bar.
2171         supportAppBar.setVisibility(View.VISIBLE);
2172
2173         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
2174         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2175     }
2176
2177     private void applyAppSettings() {
2178         // Get a handle for `sharedPreferences`.  `this` references the current context.
2179         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2180
2181         // Store the values from `sharedPreferences` in variables.
2182         String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2183         String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2184         String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2185         String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2186         String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2187         String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2188         adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2189         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2190         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2191         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2192         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2193         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2194         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2195         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2196         displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2197
2198         // Set the homepage, search, and proxy options.
2199         if (proxyThroughOrbot) {  // Set the Tor options.
2200             // Set `torHomepageString` as `homepage`.
2201             homepage = torHomepageString;
2202
2203             // If formattedUrlString is null assign the homepage to it.
2204             if (formattedUrlString == null) {
2205                 formattedUrlString = homepage;
2206             }
2207
2208             // Set the search URL.
2209             if (torSearchString.equals("Custom URL")) {  // Get the custom URL string.
2210                 searchURL = torSearchCustomURLString;
2211             } else {  // Use the string from the pre-built list.
2212                 searchURL = torSearchString;
2213             }
2214
2215             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
2216             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2217
2218             // Display a message to the user if we are waiting on Orbot.
2219             if (!orbotStatus.equals("ON")) {
2220                 // Set `waitingForOrbot`.
2221                 waitingForOrbot = true;
2222
2223                 // Load a waiting page.  `null` specifies no encoding, which defaults to ASCII.
2224                 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2225             }
2226         } else {  // Set the non-Tor options.
2227             // Set `homepageString` as `homepage`.
2228             homepage = homepageString;
2229
2230             // If formattedUrlString is null assign the homepage to it.
2231             if (formattedUrlString == null) {
2232                 formattedUrlString = homepage;
2233             }
2234
2235             // Set the search URL.
2236             if (searchString.equals("Custom URL")) {  // Get the custom URL string.
2237                 searchURL = searchCustomURLString;
2238             } else {  // Use the string from the pre-built list.
2239                 searchURL = searchString;
2240             }
2241
2242             // Reset the proxy to default.  The host is `""` and the port is `"0"`.
2243             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2244
2245             // Reset `waitingForOrbot.
2246             waitingForOrbot = false;
2247         }
2248
2249         // Set swipe to refresh.
2250         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2251
2252         // Set Do Not Track status.
2253         if (doNotTrackEnabled) {
2254             customHeaders.put("DNT", "1");
2255         } else {
2256             customHeaders.remove("DNT");
2257         }
2258
2259         // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2260         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2261             if (hideSystemBarsOnFullscreen) {  // Hide everything.
2262                 // Remove the translucent navigation setting if it is currently flagged.
2263                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2264
2265                 // Remove the translucent status bar overlay.
2266                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2267
2268                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2269                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2270
2271                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2272                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2273                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2274                  */
2275                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2276             } else {  // Hide everything except the status and navigation bars.
2277                 // Add the translucent status flag if it is unset.
2278                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2279
2280                 if (translucentNavigationBarOnFullscreen) {
2281                     // Set the navigation bar to be translucent.
2282                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2283                 } else {
2284                     // Set the navigation bar to be black.
2285                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2286                 }
2287             }
2288         } else {  // Switch to normal viewing mode.
2289             // Reset `inFullScreenBrowsingMode` to `false`.
2290             inFullScreenBrowsingMode = false;
2291
2292             // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2293             if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2294                 appBar.show();
2295             }
2296
2297             // Show the `BannerAd` in the free flavor.
2298             if (BuildConfig.FLAVOR.contentEquals("free")) {
2299                 // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
2300                 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2301
2302                 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2303                 adView = findViewById(R.id.adview);
2304             }
2305
2306             // Remove the translucent navigation bar flag if it is set.
2307             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2308
2309             // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2310             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2311
2312             // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2313             rootCoordinatorLayout.setSystemUiVisibility(0);
2314
2315             // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2316             rootCoordinatorLayout.setFitsSystemWindows(true);
2317         }
2318     }
2319
2320     // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2321     @SuppressWarnings("deprecation")
2322     private void applyDomainSettings(String url) {
2323         // Reset `navigatingHistory`.
2324         navigatingHistory = false;
2325
2326         // Parse the URL into a URI.
2327         Uri uri = Uri.parse(url);
2328
2329         // Extract the domain from `uri`.
2330         String hostName = uri.getHost();
2331
2332         // Initialize `loadingNewDomainName`.
2333         boolean loadingNewDomainName;
2334
2335         // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2336         // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2337         //noinspection SimplifiableIfStatement
2338         if ((hostName == null) || (currentDomainName == null)) {
2339             loadingNewDomainName = true;
2340         } else {  // Determine if `hostName` equals `currentDomainName`.
2341             loadingNewDomainName = !hostName.equals(currentDomainName);
2342         }
2343
2344         // 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.
2345         if (loadingNewDomainName) {
2346             // Set the new `hostname` as the `currentDomainName`.
2347             currentDomainName = hostName;
2348
2349             // Reset `favoriteIconBitmap` and display it in the `appbar`.
2350             favoriteIconBitmap = favoriteIconDefaultBitmap;
2351             favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2352
2353             // Initialize the database handler.  `this` specifies the context.  The two `nulls` do not specify the database name or a `CursorFactory`.
2354             // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2355             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2356
2357             // Get a full cursor from `domainsDatabaseHelper`.
2358             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2359
2360             // Initialize `domainSettingsSet`.
2361             Set<String> domainSettingsSet = new HashSet<>();
2362
2363             // Get the domain name column index.
2364             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2365
2366             // Populate `domainSettingsSet`.
2367             for (int i = 0; i < domainNameCursor.getCount(); i++) {
2368                 // Move `domainsCursor` to the current row.
2369                 domainNameCursor.moveToPosition(i);
2370
2371                 // Store the domain name in `domainSettingsSet`.
2372                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2373             }
2374
2375             // Close `domainNameCursor.
2376             domainNameCursor.close();
2377
2378             // Initialize variables to track if domain settings will be applied and, if so, under which name.
2379             domainSettingsApplied = false;
2380             String domainNameInDatabase = null;
2381
2382             // Check the hostname.
2383             if (domainSettingsSet.contains(hostName)) {
2384                 domainSettingsApplied = true;
2385                 domainNameInDatabase = hostName;
2386             }
2387
2388             // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2389             if (hostName != null) {
2390                 while (hostName.contains(".") && !domainSettingsApplied) {  // Stop checking if we run out of  `.` or if we already know that `domainSettingsApplied` is `true`.
2391                     if (domainSettingsSet.contains("*." + hostName)) {  // Check the host name prepended by `*.`.
2392                         domainSettingsApplied = true;
2393                         domainNameInDatabase = "*." + hostName;
2394                     }
2395
2396                     // Strip out the lowest subdomain of `host`.
2397                     hostName = hostName.substring(hostName.indexOf(".") + 1);
2398                 }
2399             }
2400
2401             // Get a handle for the shared preference.  `this` references the current context.
2402             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2403
2404             if (domainSettingsApplied) {  // The url we are loading has custom domain settings.
2405                 // Get a cursor for the current host and move it to the first position.
2406                 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2407                 currentHostDomainSettingsCursor.moveToFirst();
2408
2409                 // Get the settings from the cursor.
2410                 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2411                 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2412                 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2413                 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2414                 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2415                 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2416                 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2417                 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2418
2419                 // Close `currentHostDomainSettingsCursor`.
2420                 currentHostDomainSettingsCursor.close();
2421
2422                 // Apply the domain settings.
2423                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2424                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2425                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2426                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2427                 mainWebView.getSettings().setTextZoom(fontSize);
2428
2429                 // Set third-party cookies status if API >= 21.
2430                 if (Build.VERSION.SDK_INT >= 21) {
2431                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2432                 }
2433
2434                 // Set the user agent.
2435                 if (userAgentString.equals("WebView default user agent")) {
2436                     // Set the user agent to `""`, which uses the default value.
2437                     mainWebView.getSettings().setUserAgentString("");
2438                 } else {
2439                     // Use the selected user agent.
2440                     mainWebView.getSettings().setUserAgentString(userAgentString);
2441                 }
2442
2443                 // 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.
2444                 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_green));
2445             } else {  // The URL we are loading does not have custom domain settings.  Load the defaults.
2446                 // Store the values from `sharedPreferences` in variables.
2447                 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2448                 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2449                 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2450                 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2451                 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2452                 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2453                 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2454                 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2455
2456                 // Apply the default settings.
2457                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2458                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2459                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2460                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2461                 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2462
2463                 // Set third-party cookies status if API >= 21.
2464                 if (Build.VERSION.SDK_INT >= 21) {
2465                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2466                 }
2467
2468                 // Set the default user agent.
2469                 switch (userAgentString) {
2470                     case "WebView default user agent":
2471                         // Set the user agent to `""`, which uses the default value.
2472                         mainWebView.getSettings().setUserAgentString("");
2473                         break;
2474
2475                     case "Custom user agent":
2476                         // Set the custom user agent.
2477                         mainWebView.getSettings().setUserAgentString(customUserAgentString);
2478                         break;
2479
2480                     default:
2481                         // Use the selected user agent.
2482                         mainWebView.getSettings().setUserAgentString(userAgentString);
2483                         break;
2484                 }
2485
2486                 // Set a transparent background on `urlTextBox`.  We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2487                 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.url_bar_background_transparent));
2488             }
2489
2490             // Close `domainsDatabaseHelper`.
2491             domainsDatabaseHelper.close();
2492
2493             // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode.  `true` indicates that custom domain settings are applied.
2494             onTheFlyDisplayImagesSet = false;
2495             setDisplayWebpageImages();
2496
2497             // Update the privacy icons, but only if `mainMenu` has already been populated.
2498             if (mainMenu != null) {
2499                 updatePrivacyIcons(true);
2500             }
2501         }
2502     }
2503
2504     private void setDisplayWebpageImages() {
2505         if (!onTheFlyDisplayImagesSet) {
2506             if (domainSettingsApplied) {  // Custom domain settings are applied.
2507                 switch (displayWebpageImagesInt) {
2508                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2509                         mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2510                         break;
2511
2512                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2513                         mainWebView.getSettings().setLoadsImagesAutomatically(true);
2514                         break;
2515
2516                     case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2517                         mainWebView.getSettings().setLoadsImagesAutomatically(false);
2518                         break;
2519                 }
2520             } else {  // Default settings are applied.
2521                 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2522             }
2523         }
2524     }
2525
2526     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2527         // Get handles for the icons.
2528         MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2529         MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2530         MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2531         MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2532
2533         // Update `privacyIcon`.
2534         if (javaScriptEnabled) {  // JavaScript is enabled.
2535             privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2536         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
2537             privacyIconMenuItem.setIcon(R.drawable.warning);
2538         } else {  // All the dangerous features are disabled.
2539             privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2540         }
2541
2542         // Update `firstPartyCookiesIcon`.
2543         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
2544             firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2545         } else {  // First-party cookies are disabled.
2546             firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled);
2547         }
2548
2549         // Update `domStorageIcon`.
2550         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
2551             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2552         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
2553             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled);
2554         } else {  // JavaScript is disabled, so DOM storage is ghosted.
2555             domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted);
2556         }
2557
2558         // Update `formDataIcon`.
2559         if (saveFormDataEnabled) {  // Form data is enabled.
2560             formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2561         } else {  // Form data is disabled.
2562             formDataIconMenuItem.setIcon(R.drawable.form_data_disabled);
2563         }
2564
2565         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.  `this` references the current activity.
2566         if (runInvalidateOptionsMenu) {
2567             ActivityCompat.invalidateOptionsMenu(this);
2568         }
2569     }
2570
2571     private void highlightUrlText() {
2572         String urlString = urlTextBox.getText().toString();
2573
2574         if (urlString.startsWith("http://")) {  // Highlight connections that are not encrypted.
2575             urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2576             urlTextBox.getText().setSpan(boldStyleSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2577         } else if (urlString.startsWith("https://")) {  // Highlight connections that are encrypted.
2578             urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2579         }
2580
2581         // Get the index of the `/` immediately after the domain name.
2582         int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2583
2584         // De-emphasize the text after the domain name.
2585         if (endOfDomainName > 0) {
2586             urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2587         }
2588     }
2589 }