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