]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebViewActivity.java
Add a DNT option and turn it on by default. Fixes https://redmine.stoutner.com/issues/30
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / MainWebViewActivity.java
1 /**
2  * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser;
21
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.app.DialogFragment;
25 import android.app.DownloadManager;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.net.Uri;
33 import android.net.http.SslError;
34 import android.os.Build;
35 import android.os.Bundle;
36 import android.preference.PreferenceManager;
37 import android.support.design.widget.NavigationView;
38 import android.support.design.widget.Snackbar;
39 import android.support.v4.app.ActivityCompat;
40 import android.support.v4.content.ContextCompat;
41 import android.support.v4.view.GravityCompat;
42 import android.support.v4.widget.DrawerLayout;
43 import android.support.v4.widget.SwipeRefreshLayout;
44 import android.support.v7.app.ActionBar;
45 import android.support.v7.app.ActionBarDrawerToggle;
46 import android.support.v7.app.AppCompatActivity;
47 import android.support.v7.widget.Toolbar;
48 import android.util.Patterns;
49 import android.view.KeyEvent;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.View;
53 import android.view.inputmethod.InputMethodManager;
54 import android.webkit.CookieManager;
55 import android.webkit.DownloadListener;
56 import android.webkit.SslErrorHandler;
57 import android.webkit.WebChromeClient;
58 import android.webkit.WebStorage;
59 import android.webkit.WebView;
60 import android.webkit.WebViewClient;
61 import android.webkit.WebViewDatabase;
62 import android.widget.EditText;
63 import android.widget.FrameLayout;
64 import android.widget.ImageView;
65 import android.widget.ProgressBar;
66
67 import java.io.UnsupportedEncodingException;
68 import java.net.MalformedURLException;
69 import java.net.URL;
70 import java.net.URLEncoder;
71 import java.util.HashMap;
72 import java.util.Map;
73
74 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
75 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener, SslCertificateError.SslCertificateErrorListener {
76     // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
77     // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
78     public static Bitmap favoriteIcon;
79
80     // `privacyBrowserActivity` is public static so it can be accessed from `SettingsFragment`.
81     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`,
82     public static Activity privacyBrowserActivity;
83
84     // `mainWebView` is public static so it can be accessed from `SettingsFragment`.
85     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, and `loadUrlFromTextBox()`.
86     public static WebView mainWebView;
87
88     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
89     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
90     public static String formattedUrlString;
91
92     // `mainMenu` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreateOptionsMenu()` and `onOptionsItemSelected()`.
93     public static Menu mainMenu;
94
95     // `cookieManager` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
96     public static CookieManager cookieManager;
97
98     // `javaScriptEnabled` is public static so it can be accessed from `SettingsFragment`.
99     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
100     public static boolean javaScriptEnabled;
101
102     // `firstPartyCookiesEnabled` is public static so it can be accessed from `SettingsFragment`.
103     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
104     public static boolean firstPartyCookiesEnabled;
105
106     // `thirdPartyCookiesEnables` is public static so it can be accessed from `SettingsFragment`.
107     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
108     public static boolean thirdPartyCookiesEnabled;
109
110     // `domStorageEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
111     public static boolean domStorageEnabled;
112
113     // `saveFormDataEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
114     public static boolean saveFormDataEnabled;
115
116     // `javaScriptDisabledSearchURL` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `loadURLFromTextBox()`.
117     public static String javaScriptDisabledSearchURL;
118
119     // `javaScriptEnabledSearchURL` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `loadURLFromTextBox()`.
120     public static String javaScriptEnabledSearchURL;
121
122     // `homepage` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `onOptionsItemSelected()`.
123     public static String homepage;
124
125     // `swipeToRefresh` is public static so it can be accessed from SettingsFragment.  It is also used in onCreate().
126     public static SwipeRefreshLayout swipeToRefresh;
127
128     // `swipeToRefreshEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`.
129     public static boolean swipeToRefreshEnabled;
130
131     // `customHeader` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
132     public static Map<String, String> customHeaders = new HashMap<String, String>();
133
134
135
136     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
137     private ActionBarDrawerToggle drawerToggle;
138
139     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
140     private DrawerLayout drawerLayout;
141
142     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
143     private EditText urlTextBox;
144
145     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
146     private View adView;
147
148     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
149     private SslErrorHandler sslErrorHandler;
150
151     // `sharedPreferences` is used in `onCreate()` and `onCreateOptionsMenu()`.
152     SharedPreferences sharedPreferences;
153
154     @Override
155     // 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.
156     @SuppressLint("SetJavaScriptEnabled")
157     protected void onCreate(Bundle savedInstanceState) {
158         super.onCreate(savedInstanceState);
159         setContentView(R.layout.main_coordinatorlayout);
160
161         // We need a handle for the activity, which is accessed from `SettingsFragment` and fed into `updatePrivacyIcons()`.
162         privacyBrowserActivity = this;
163
164         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
165         Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
166         setSupportActionBar(supportAppBar);
167         final ActionBar appBar = getSupportActionBar();
168
169         // This is needed to get rid of the Android Studio warning that appBar might be null.
170         assert appBar != null;
171
172         // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
173         appBar.setCustomView(R.layout.url_bar);
174         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
175
176         // Set the "go" button on the keyboard to load the URL in urlTextBox.
177         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
178         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
179             public boolean onKey(View v, int keyCode, KeyEvent event) {
180                 // If the event is a key-down event on the "enter" button, load the URL.
181                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
182                     // Load the URL into the mainWebView and consume the event.
183                     try {
184                         loadUrlFromTextBox();
185                     } catch (UnsupportedEncodingException e) {
186                         e.printStackTrace();
187                     }
188                     // If the enter key was pressed, consume the event.
189                     return true;
190                 } else {
191                     // If any other key was pressed, do not consume the event.
192                     return false;
193                 }
194             }
195         });
196
197         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
198
199         // Implement swipe to refresh
200         swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
201         assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
202         swipeToRefresh.setColorSchemeResources(R.color.blue);
203         swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
204             @Override
205             public void onRefresh() {
206                 mainWebView.reload();
207             }
208         });
209
210         mainWebView = (WebView) findViewById(R.id.mainWebView);
211
212         // Create the navigation drawer.
213         drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
214         // The DrawerTitle identifies the drawer in accessibility mode.
215         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
216
217         // Listen for touches on the navigation menu.
218         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
219         assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
220         navigationView.setNavigationItemSelectedListener(this);
221
222         // drawerToggle creates the hamburger icon at the start of the AppBar.
223         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
224
225         mainWebView.setWebViewClient(new WebViewClient() {
226             // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
227             @Override
228             public boolean shouldOverrideUrlLoading(WebView view, String url) {
229                 // Use an external email program if the link begins with "mailto:".
230                 if (url.startsWith("mailto:")) {
231                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
232                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
233
234                     // Parse the url and set it as the data for the `Intent`.
235                     emailIntent.setData(Uri.parse(url));
236
237                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
238                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
239
240                     // Make it so.
241                     startActivity(emailIntent);
242                     return true;
243                 } else {  // Load the URL in Privacy Browser.
244                     mainWebView.loadUrl(url, customHeaders);
245                     return true;
246                 }
247             }
248
249             // Update the URL in urlTextBox when the page starts to load.
250             @Override
251             public void onPageStarted(WebView view, String url, Bitmap favicon) {
252                 urlTextBox.setText(url);
253             }
254
255             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
256             @Override
257             public void onPageFinished(WebView view, String url) {
258                 formattedUrlString = url;
259
260                 // Only update urlTextBox if the user is not typing in it.
261                 if (!urlTextBox.hasFocus()) {
262                     urlTextBox.setText(formattedUrlString);
263                 }
264             }
265
266             // Handle SSL Certificate errors.
267             @Override
268             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
269                 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
270                 sslErrorHandler = handler;
271
272                 // Display the SSL error `AlertDialog`.
273                 DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
274                 sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
275             }
276         });
277
278         mainWebView.setWebChromeClient(new WebChromeClient() {
279             // Update the progress bar when a page is loading.
280             @Override
281             public void onProgressChanged(WebView view, int progress) {
282                 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
283                 progressBar.setProgress(progress);
284                 if (progress < 100) {
285                     progressBar.setVisibility(View.VISIBLE);
286                 } else {
287                     progressBar.setVisibility(View.GONE);
288
289                     //Stop the SwipeToRefresh indicator if it is running
290                     swipeToRefresh.setRefreshing(false);
291                 }
292             }
293
294             // Set the favorite icon when it changes.
295             @Override
296             public void onReceivedIcon(WebView view, Bitmap icon) {
297                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
298                 favoriteIcon = icon;
299
300                 // Place the favorite icon in the appBar.
301                 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
302                 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
303             }
304
305             // Enter full screen video
306             @Override
307             public void onShowCustomView(View view, CustomViewCallback callback) {
308                 appBar.hide();
309
310                 // Show the fullScreenVideoFrameLayout.
311                 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
312                 fullScreenVideoFrameLayout.addView(view);
313                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
314
315                 // Hide the mainWebView.
316                 mainWebView.setVisibility(View.GONE);
317
318                 // Hide the ad if this is the free flavor.
319                 BannerAd.hideAd(adView);
320
321                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
322                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
323                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
324                  */
325                 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
326             }
327
328             // Exit full screen video
329             public void onHideCustomView() {
330                 appBar.show();
331
332                 // Show the mainWebView.
333                 mainWebView.setVisibility(View.VISIBLE);
334
335                 // Show the ad if this is the free flavor.
336                 BannerAd.showAd(adView);
337
338                 // Hide the fullScreenVideoFrameLayout.
339                 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
340                 fullScreenVideoFrameLayout.removeAllViews();
341                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
342             }
343         });
344
345         // Allow the downloading of files.
346         mainWebView.setDownloadListener(new DownloadListener() {
347             // Launch the Android download manager when a link leads to a download.
348             @Override
349             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
350                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
351                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
352
353                 // Add the URL as the description for the download.
354                 requestUri.setDescription(url);
355
356                 // Show the download notification after the download is completed.
357                 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
358
359                 // Initiate the download and display a Snackbar.
360                 downloadManager.enqueue(requestUri);
361                 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
362             }
363         });
364
365         // Allow pinch to zoom.
366         mainWebView.getSettings().setBuiltInZoomControls(true);
367
368         // Hide zoom controls.
369         mainWebView.getSettings().setDisplayZoomControls(false);
370
371
372         // Initialize the default preference values the first time the program is run.
373         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
374
375         // Get the shared preference values.
376         sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
377
378         // Set JavaScript initial status.  The default value is false.
379         javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
380         mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
381
382         // Initialize cookieManager.
383         cookieManager = CookieManager.getInstance();
384
385         // Set cookies initial status.  The default value is false.
386         firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
387         cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
388
389         // Set third-party cookies initial status if API >= 21.  The default value is false.
390         if (Build.VERSION.SDK_INT >= 21) {
391             thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
392             cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
393         }
394
395         // Set DOM storage initial status.  The default value is false.
396         domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
397         mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
398
399         // Set the saved form data initial status.  The default is false.
400         saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
401         mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
402
403         // Set the user agent initial status.
404         String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
405         switch (userAgentString) {
406             case "Default user agent":
407                 // Do nothing.
408                 break;
409
410             case "Custom user agent":
411                 // Set the custom user agent on mainWebView,  The default is "PrivacyBrowser/1.0".
412                 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
413                 break;
414
415             default:
416                 // Set the selected user agent on mainWebView.  The default is "PrivacyBrowser/1.0".
417                 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
418                 break;
419         }
420
421         // Set the initial string for JavaScript disabled search.
422         if (sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
423             // Get the custom URL string.  The default is "".
424             javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
425         } else {
426             // Use the string from javascript_disabled_search.
427             javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
428         }
429
430         // Set the initial string for JavaScript enabled search.
431         if (sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
432             // Get the custom URL string.  The default is "".
433             javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
434         } else {
435             // Use the string from javascript_enabled_search.
436             javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
437         }
438
439
440         // Set the homepage initial status.  The default value is `https://www.duckduckgo.com`.
441         homepage = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
442
443         // Set the font size initial status.  the default value is `100`.
444         String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
445         mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
446
447         // Set the swipe to refresh initial status.  The default is `true`.
448         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", true);
449         swipeToRefresh.setEnabled(swipeToRefreshEnabled);
450
451
452         // 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).
453         customHeaders.put("X-Requested-With", "");
454
455         // Set Do Not Track.  The default is true.
456         if (sharedPreferences.getBoolean("do_not_track", true)) {
457             customHeaders.put("DNT", "1");
458         }
459
460
461         // Get the intent information that started the app.
462         final Intent intent = getIntent();
463
464         if (intent.getData() != null) {
465             // Get the intent data and convert it to a string.
466             final Uri intentUriData = intent.getData();
467             formattedUrlString = intentUriData.toString();
468         }
469
470         // If formattedUrlString is null assign the homepage to it.
471         if (formattedUrlString == null) {
472             formattedUrlString = homepage;
473         }
474
475         // Load the initial website.
476         mainWebView.loadUrl(formattedUrlString, customHeaders);
477
478         // If the favorite icon is null, load the default.
479         if (favoriteIcon == null) {
480             // We have to use `ContextCompat` until API >= 21.
481             Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
482             BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
483             favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
484         }
485
486         // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
487         adView = findViewById(R.id.adView);
488         BannerAd.requestAd(adView);
489     }
490
491
492     @Override
493     protected void onNewIntent(Intent intent) {
494         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
495         setIntent(intent);
496
497         if (intent.getData() != null) {
498             // Get the intent data and convert it to a string.
499             final Uri intentUriData = intent.getData();
500             formattedUrlString = intentUriData.toString();
501         }
502
503         // Close the navigation drawer if it is open.
504         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
505             drawerLayout.closeDrawer(GravityCompat.START);
506         }
507
508         // Load the website.
509         mainWebView.loadUrl(formattedUrlString, customHeaders);
510
511         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
512         mainWebView.requestFocus();
513     }
514
515     @Override
516     public boolean onCreateOptionsMenu(Menu menu) {
517         // Inflate the menu; this adds items to the action bar if it is present.
518         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
519
520         // Set mainMenu so it can be used by onOptionsItemSelected.
521         mainMenu = menu;
522
523         // Set the initial status of the privacy icon.
524         updatePrivacyIcons(privacyBrowserActivity);
525
526         // Get handles for the menu items.
527         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
528         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
529         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
530         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
531
532         // Set the initial status of the menu item checkboxes.
533         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
534         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
535         toggleDomStorage.setChecked(domStorageEnabled);
536         toggleSaveFormData.setChecked(saveFormDataEnabled);
537
538         // Set the status of the additional app bar icons.  The default is `false`.
539         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
540             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
541             toggleThirdPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
542             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
543             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
544         } else { //Do not display the additional icons.
545             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
546             toggleThirdPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
547             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
548             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
549         }
550
551         return true;
552     }
553
554     @Override
555     public boolean onPrepareOptionsMenu(Menu menu) {
556         // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
557         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
558         if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
559             toggleThirdPartyCookies.setEnabled(true);
560         } else {
561             toggleThirdPartyCookies.setEnabled(false);
562         }
563
564         // Enable DOM Storage if JavaScript is enabled.
565         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
566         toggleDomStorage.setEnabled(javaScriptEnabled);
567
568         // Enable Clear Cookies if there are any.
569         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
570         clearCookies.setEnabled(cookieManager.hasCookies());
571
572         // Enable Clear Form Data is there is any.
573         MenuItem clearFormData = menu.findItem(R.id.clearFormData);
574         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
575         clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
576
577         // Initialize font size variables.
578         int fontSize = mainWebView.getSettings().getTextZoom();
579         String fontSizeTitle;
580         MenuItem selectedFontSizeMenuItem;
581
582         // Prepare the font size title and current size menu item.
583         switch (fontSize) {
584             case 50:
585                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
586                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
587                 break;
588
589             case 75:
590                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
591                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
592                 break;
593
594             case 100:
595                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
596                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
597                 break;
598
599             case 125:
600                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
601                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
602                 break;
603
604             case 150:
605                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
606                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
607                 break;
608
609             case 175:
610                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
611                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
612                 break;
613
614             case 200:
615                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
616                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
617                 break;
618
619             default:
620                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
621                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
622                 break;
623         }
624
625         // Set the font size title and select the current size menu item.
626         MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
627         fontSizeMenuItem.setTitle(fontSizeTitle);
628         selectedFontSizeMenuItem.setChecked(true);
629
630         // Only show `Refresh` if `swipeToRefresh` is disabled.
631         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
632         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
633
634         // Run all the other default commands.
635         super.onPrepareOptionsMenu(menu);
636
637         // `return true` displays the menu.
638         return true;
639     }
640
641     @Override
642     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
643     @SuppressLint("SetJavaScriptEnabled")
644     // removeAllCookies is deprecated, but it is required for API < 21.
645     @SuppressWarnings("deprecation")
646     public boolean onOptionsItemSelected(MenuItem menuItem) {
647         int menuItemId = menuItem.getItemId();
648
649         // Set the commands that relate to the menu entries.
650         switch (menuItemId) {
651             case R.id.toggleJavaScript:
652                 // Switch the status of javaScriptEnabled.
653                 javaScriptEnabled = !javaScriptEnabled;
654
655                 // Apply the new JavaScript status.
656                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
657
658                 // Update the privacy icon.
659                 updatePrivacyIcons(privacyBrowserActivity);
660
661                 // Display a `Snackbar`.
662                 if (javaScriptEnabled) {
663                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
664                 } else {
665                     if (firstPartyCookiesEnabled) {
666                         Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
667                     } else {
668                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
669                     }
670                 }
671
672                 // Reload the WebView.
673                 mainWebView.reload();
674                 return true;
675
676             case R.id.toggleFirstPartyCookies:
677                 // Switch the status of firstPartyCookiesEnabled.
678                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
679
680                 // Update the menu checkbox.
681                 menuItem.setChecked(firstPartyCookiesEnabled);
682
683                 // Apply the new cookie status.
684                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
685
686                 // Update the privacy icon.
687                 updatePrivacyIcons(privacyBrowserActivity);
688
689                 // Display a `Snackbar`.
690                 if (firstPartyCookiesEnabled) {
691                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
692                 } else {
693                     if (javaScriptEnabled) {
694                         Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
695                     } else {
696                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
697                     }
698                 }
699
700                 // Reload the WebView.
701                 mainWebView.reload();
702                 return true;
703
704             case R.id.toggleThirdPartyCookies:
705                 if (Build.VERSION.SDK_INT >= 21) {
706                     // Switch the status of thirdPartyCookiesEnabled.
707                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
708
709                     // Update the menu checkbox.
710                     menuItem.setChecked(thirdPartyCookiesEnabled);
711
712                     // Apply the new cookie status.
713                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
714
715                     // Display a `Snackbar`.
716                     if (thirdPartyCookiesEnabled) {
717                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
718                     } else {
719                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
720                     }
721
722                     // Reload the WebView.
723                     mainWebView.reload();
724                 } // Else do nothing because SDK < 21.
725                 return true;
726
727             case R.id.toggleDomStorage:
728                 // Switch the status of domStorageEnabled.
729                 domStorageEnabled = !domStorageEnabled;
730
731                 // Update the menu checkbox.
732                 menuItem.setChecked(domStorageEnabled);
733
734                 // Apply the new DOM Storage status.
735                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
736
737                 // Display a `Snackbar`.
738                 if (domStorageEnabled) {
739                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
740                 } else {
741                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
742                 }
743
744                 // Reload the WebView.
745                 mainWebView.reload();
746                 return true;
747
748             case R.id.toggleSaveFormData:
749                 // Switch the status of saveFormDataEnabled.
750                 saveFormDataEnabled = !saveFormDataEnabled;
751
752                 // Update the menu checkbox.
753                 menuItem.setChecked(saveFormDataEnabled);
754
755                 // Apply the new form data status.
756                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
757
758                 // Display a `Snackbar`.
759                 if (saveFormDataEnabled) {
760                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
761                 } else {
762                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
763                 }
764
765                 // Reload the WebView.
766                 mainWebView.reload();
767                 return true;
768
769             case R.id.clearCookies:
770                 if (Build.VERSION.SDK_INT < 21) {
771                     cookieManager.removeAllCookie();
772                 } else {
773                     cookieManager.removeAllCookies(null);
774                 }
775                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
776                 return true;
777
778             case R.id.clearDomStorage:
779                 WebStorage webStorage = WebStorage.getInstance();
780                 webStorage.deleteAllData();
781                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
782                 return true;
783
784             case R.id.clearFormData:
785                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
786                 mainWebViewDatabase.clearFormData();
787                 mainWebView.reload();
788                 return true;
789
790             case R.id.fontSizeFiftyPercent:
791                 mainWebView.getSettings().setTextZoom(50);
792                 return true;
793
794             case R.id.fontSizeSeventyFivePercent:
795                 mainWebView.getSettings().setTextZoom(75);
796                 return true;
797
798             case R.id.fontSizeOneHundredPercent:
799                 mainWebView.getSettings().setTextZoom(100);
800                 return true;
801
802             case R.id.fontSizeOneHundredTwentyFivePercent:
803                 mainWebView.getSettings().setTextZoom(125);
804                 return true;
805
806             case R.id.fontSizeOneHundredFiftyPercent:
807                 mainWebView.getSettings().setTextZoom(150);
808                 return true;
809
810             case R.id.fontSizeOneHundredSeventyFivePercent:
811                 mainWebView.getSettings().setTextZoom(175);
812                 return true;
813
814             case R.id.fontSizeTwoHundredPercent:
815                 mainWebView.getSettings().setTextZoom(200);
816                 return true;
817
818             case R.id.share:
819                 Intent shareIntent = new Intent();
820                 shareIntent.setAction(Intent.ACTION_SEND);
821                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
822                 shareIntent.setType("text/plain");
823                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
824                 return true;
825
826             case R.id.addToHomescreen:
827                 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
828                 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
829                 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
830
831                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
832                 return true;
833
834             case R.id.refresh:
835                 mainWebView.reload();
836                 return true;
837
838             default:
839                 // Don't consume the event.
840                 return super.onOptionsItemSelected(menuItem);
841         }
842     }
843
844     @Override
845     // removeAllCookies is deprecated, but it is required for API < 21.
846     @SuppressWarnings("deprecation")
847     public boolean onNavigationItemSelected(MenuItem menuItem) {
848         int menuItemId = menuItem.getItemId();
849
850         switch (menuItemId) {
851             case R.id.home:
852                 mainWebView.loadUrl(homepage, customHeaders);
853                 break;
854
855             case R.id.back:
856                 if (mainWebView.canGoBack()) {
857                     mainWebView.goBack();
858                 }
859                 break;
860
861             case R.id.forward:
862                 if (mainWebView.canGoForward()) {
863                     mainWebView.goForward();
864                 }
865                 break;
866
867             case R.id.bookmarks:
868                 // Launch BookmarksActivity.
869                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
870                 startActivity(bookmarksIntent);
871                 break;
872
873             case R.id.downloads:
874                 // Launch the system Download Manager.
875                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
876
877                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
878                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
879
880                 startActivity(downloadManagerIntent);
881                 break;
882
883             case R.id.settings:
884                 // Launch `SettingsActivity`.
885                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
886                 startActivity(settingsIntent);
887                 break;
888
889             case R.id.guide:
890                 // Launch `GuideActivity`.
891                 Intent guideIntent = new Intent(this, GuideActivity.class);
892                 startActivity(guideIntent);
893                 break;
894
895             case R.id.about:
896                 // Launch `AboutActivity`.
897                 Intent aboutIntent = new Intent(this, AboutActivity.class);
898                 startActivity(aboutIntent);
899                 break;
900
901             case R.id.clearAndExit:
902                 // Clear cookies.  The commands changed slightly in API 21.
903                 if (Build.VERSION.SDK_INT >= 21) {
904                     cookieManager.removeAllCookies(null);
905                 } else {
906                     cookieManager.removeAllCookie();
907                 }
908
909                 // Clear DOM storage.
910                 WebStorage domStorage = WebStorage.getInstance();
911                 domStorage.deleteAllData();
912
913                 // Clear form data.
914                 WebViewDatabase formData = WebViewDatabase.getInstance(this);
915                 formData.clearFormData();
916
917                 // Clear cache.  The argument of "true" includes disk files.
918                 mainWebView.clearCache(true);
919
920                 // Clear the back/forward history.
921                 mainWebView.clearHistory();
922
923                 // Clear any SSL certificate preferences.
924                 MainWebViewActivity.mainWebView.clearSslPreferences();
925
926                 // Clear `formattedUrlString`.
927                 formattedUrlString = null;
928
929                 // Clear `customHeaders`.
930                 customHeaders.clear();
931
932                 // Destroy the internal state of the webview.
933                 mainWebView.destroy();
934
935                 // Close Privacy Browser.  finishAndRemoveTask also removes Privacy Browser from the recent app list.
936                 if (Build.VERSION.SDK_INT >= 21) {
937                     finishAndRemoveTask();
938                 } else {
939                     finish();
940                 }
941                 break;
942
943             default:
944                 break;
945         }
946
947         // Close the navigation drawer.
948         drawerLayout.closeDrawer(GravityCompat.START);
949         return true;
950     }
951
952     @Override
953     public void onPostCreate(Bundle savedInstanceState) {
954         super.onPostCreate(savedInstanceState);
955
956         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
957         drawerToggle.syncState();
958     }
959
960     @Override
961     public void onConfigurationChanged(Configuration newConfig) {
962         super.onConfigurationChanged(newConfig);
963
964         // Reload the ad if this is the free flavor.
965         BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
966
967         // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
968         adView = findViewById(R.id.adView);
969
970         // `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
971         invalidateOptionsMenu();
972     }
973
974     @Override
975     public void onCancelCreateHomeScreenShortcut(DialogFragment dialogFragment) {
976         // Do nothing because the user selected "Cancel".
977     }
978
979     @Override
980     public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
981         // Get shortcutNameEditText from the alert dialog.
982         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
983
984         // Create the bookmark shortcut based on formattedUrlString.
985         Intent bookmarkShortcut = new Intent();
986         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
987         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
988
989         // Place the bookmark shortcut on the home screen.
990         Intent placeBookmarkShortcut = new Intent();
991         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
992         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
993         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
994         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
995         sendBroadcast(placeBookmarkShortcut);
996     }
997
998     public void viewSslCertificate(View view) {
999         // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1000         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1001         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1002     }
1003
1004     @Override
1005     public void onSslErrorCancel() {
1006         sslErrorHandler.cancel();
1007     }
1008
1009     @Override
1010     public void onSslErrorProceed() {
1011         sslErrorHandler.proceed();
1012     }
1013
1014     // Override onBackPressed to handle the navigation drawer and mainWebView.
1015     @Override
1016     public void onBackPressed() {
1017         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
1018
1019         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1020         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1021             drawerLayout.closeDrawer(GravityCompat.START);
1022         } else {
1023             // Load the previous URL if available.
1024             assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
1025             if (mainWebView.canGoBack()) {
1026                 mainWebView.goBack();
1027             } else {
1028                 // Pass onBackPressed to the system.
1029                 super.onBackPressed();
1030             }
1031         }
1032     }
1033
1034     @Override
1035     public void onPause() {
1036         // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
1037         BannerAd.pauseAd(adView);
1038
1039         super.onPause();
1040     }
1041
1042     @Override
1043     public void onResume() {
1044         super.onResume();
1045
1046         // We need to resume the adView for the free flavor.
1047         BannerAd.resumeAd(adView);
1048     }
1049
1050     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1051         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
1052         String unformattedUrlString = urlTextBox.getText().toString().trim();
1053
1054         URL unformattedUrl = null;
1055         Uri.Builder formattedUri = new Uri.Builder();
1056
1057         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
1058         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1059             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
1060             if (!unformattedUrlString.startsWith("http")) {
1061                 unformattedUrlString = "http://" + unformattedUrlString;
1062             }
1063
1064             // 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.
1065             try {
1066                 unformattedUrl = new URL(unformattedUrlString);
1067             } catch (MalformedURLException e) {
1068                 e.printStackTrace();
1069             }
1070
1071             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1072             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1073             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1074             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1075             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1076             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1077
1078             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1079             formattedUrlString = formattedUri.build().toString();
1080         } else {
1081             // Sanitize the search input and convert it to a DuckDuckGo search.
1082             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1083
1084             // Use the correct search URL based on javaScriptEnabled.
1085             if (javaScriptEnabled) {
1086                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1087             } else { // JavaScript is disabled.
1088                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1089             }
1090         }
1091
1092         mainWebView.loadUrl(formattedUrlString, customHeaders);
1093
1094         // Hides the keyboard so we can see the webpage.
1095         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1096         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1097     }
1098
1099     public static void updatePrivacyIcons(Activity activity) {
1100         // Get handles for the icons.
1101         MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1102         MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1103         MenuItem thirdPartyCookiesIcon = mainMenu.findItem(R.id.toggleThirdPartyCookies);
1104         MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1105         MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1106
1107         // Update `privacyIcon`.
1108         if (javaScriptEnabled) {
1109             // `JavaScript` is enabled.
1110             privacyIcon.setIcon(R.drawable.javascript_enabled);
1111         } else {
1112             if (firstPartyCookiesEnabled) {
1113                 // `JavaScript` is disabled but cookies are enabled.
1114                 privacyIcon.setIcon(R.drawable.warning);
1115             } else {
1116                 // All the dangerous features are disabled.
1117                 privacyIcon.setIcon(R.drawable.privacy_mode);
1118             }
1119         }
1120
1121         // Update `firstPartyCookiesIcon`.
1122         if (firstPartyCookiesEnabled) {
1123             // First-party cookies are enabled.
1124             firstPartyCookiesIcon.setIcon(R.drawable.cookies_warning);
1125         } else {
1126             // First-party cookies are disabled.
1127             firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1128         }
1129
1130         // Update `thirdPartyCookiesIcon`.
1131         if (firstPartyCookiesEnabled) {
1132             if (thirdPartyCookiesEnabled) {
1133                 //  Third-party cookies are enabled.  Bad!
1134                 thirdPartyCookiesIcon.setIcon(R.drawable.cookies_critical);
1135             } else {
1136                 // Third-party cookies are disabled.
1137                 thirdPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1138             }
1139         } else {
1140             // First-party cookies are disabled, so third-party cookies are ghosted.
1141             thirdPartyCookiesIcon.setIcon(R.drawable.cookies_ghosted);
1142         }
1143
1144         // Update `domStorageIcon`.
1145         if (javaScriptEnabled) {
1146             if (domStorageEnabled) {
1147                 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1148             } else {
1149                 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1150             }
1151         } else {
1152             domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1153         }
1154
1155         // Update `formDataIcon`.
1156         if (saveFormDataEnabled) {
1157             formDataIcon.setIcon(R.drawable.form_data_enabled);
1158         } else {
1159             formDataIcon.setIcon(R.drawable.form_data_disabled);
1160         }
1161
1162         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
1163         ActivityCompat.invalidateOptionsMenu(activity);
1164     }
1165 }