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