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