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