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