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