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