2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser.
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.
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.
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/>.
20 package com.stoutner.privacybrowser;
22 import android.annotation.SuppressLint;
23 import android.annotation.TargetApi;
24 import android.app.Activity;
25 import android.app.DownloadManager;
26 import android.content.ClipData;
27 import android.content.ClipboardManager;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.SharedPreferences;
31 import android.graphics.Bitmap;
32 import android.net.Uri;
33 import android.os.Build;
34 import android.os.Bundle;
35 import android.preference.PreferenceManager;
36 import android.support.v4.app.DialogFragment;
37 import android.support.v7.app.ActionBar;
38 import android.support.v7.app.AppCompatActivity;
39 import android.support.v7.app.AppCompatDialogFragment;
40 import android.support.v7.widget.Toolbar;
41 import android.util.Patterns;
42 import android.view.KeyEvent;
43 import android.view.Menu;
44 import android.view.MenuItem;
45 import android.view.View;
46 import android.view.inputmethod.InputMethodManager;
47 import android.webkit.CookieManager;
48 import android.webkit.DownloadListener;
49 import android.webkit.WebChromeClient;
50 import android.webkit.WebStorage;
51 import android.webkit.WebView;
52 import android.webkit.WebViewClient;
53 import android.widget.EditText;
54 import android.widget.FrameLayout;
55 import android.widget.ImageView;
56 import android.widget.ProgressBar;
57 import android.widget.Toast;
58 import java.io.UnsupportedEncodingException;
59 import java.net.MalformedURLException;
61 import java.net.URLEncoder;
63 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
64 public class MainWebView extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
65 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
66 public static Bitmap favoriteIcon;
67 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
68 public static WebView mainWebView;
70 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
71 private Menu mainMenu;
72 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
73 private String formattedUrlString;
74 // homepage is used in onCreate() and onOptionsItemSelected().
75 private String homepage;
76 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
77 private boolean javaScriptEnabled;
78 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
79 private boolean domStorageEnabled;
81 /* saveFormDataEnabled does nothing until database storage is implemented.
82 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
83 private boolean saveFormDataEnabled;
86 // cookieManager is used in onCreate() and onOptionsItemSelected().
87 private CookieManager cookieManager;
88 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
89 private boolean cookiesEnabled;
91 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
92 private EditText urlTextBox;
95 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
96 @SuppressLint("SetJavaScriptEnabled")
97 protected void onCreate(Bundle savedInstanceState) {
98 super.onCreate(savedInstanceState);
99 setContentView(R.layout.activity_webview);
100 Toolbar toolbar = (Toolbar) findViewById(R.id.appBar);
101 setSupportActionBar(toolbar);
103 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
104 final Activity mainWebViewActivity = this;
105 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
106 final ActionBar appBar = getSupportActionBar();
108 mainWebView = (WebView) findViewById(R.id.mainWebView);
110 if (appBar != null) {
111 // Remove the title from the app bar.
112 appBar.setDisplayShowTitleEnabled(false);
114 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
115 appBar.setCustomView(R.layout.url_bar);
116 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
118 // Set the "go" button on the keyboard to load the URL in urlTextBox.
119 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
120 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
121 public boolean onKey(View v, int keyCode, KeyEvent event) {
122 // If the event is a key-down event on the "enter" button, load the URL.
123 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
124 // Load the URL into the mainWebView and consume the event.
126 loadUrlFromTextBox();
127 } catch (UnsupportedEncodingException e) {
130 // If the enter key was pressed, consume the event.
133 // If any other key was pressed, do not consume the event.
140 mainWebView.setWebViewClient(new WebViewClient() {
141 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
143 public boolean shouldOverrideUrlLoading(WebView view, String url) {
144 mainWebView.loadUrl(url);
148 /* These errors do not provide any useful information and clutter the screen.
149 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
150 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_SHORT).show();
154 // Update the URL in urlTextBox when the page starts to load.
156 public void onPageStarted(WebView view, String url, Bitmap favicon) {
157 urlTextBox.setText(url);
160 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
162 public void onPageFinished(WebView view, String url) {
163 formattedUrlString = url;
164 urlTextBox.setText(formattedUrlString);
168 mainWebView.setWebChromeClient(new WebChromeClient() {
169 // Update the progress bar when a page is loading.
171 public void onProgressChanged(WebView view, int progress) {
172 // Make sure that appBar is not null.
173 if (appBar != null) {
174 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
175 progressBar.setProgress(progress);
176 if (progress < 100) {
177 progressBar.setVisibility(View.VISIBLE);
179 progressBar.setVisibility(View.GONE);
184 // Set the favorite icon when it changes.
186 public void onReceivedIcon(WebView view, Bitmap icon) {
187 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
190 // Place the favorite icon in the appBar if it is not null.
191 if (appBar != null) {
192 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
193 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
197 // Enter full screen video
199 public void onShowCustomView(View view, CustomViewCallback callback) {
200 if (appBar != null) {
204 fullScreenVideoFrameLayout.addView(view);
205 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
207 mainWebView.setVisibility(View.GONE);
209 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
210 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
211 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
214 // Set the one flag supported by API >= 14.
215 if (Build.VERSION.SDK_INT >= 14) {
216 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
219 // Set the two flags that are supported by API >= 16.
220 if (Build.VERSION.SDK_INT >= 16) {
221 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
224 // Set all three flags that are supported by API >= 19.
225 if (Build.VERSION.SDK_INT >= 19) {
226 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
230 // Exit full screen video
231 public void onHideCustomView() {
232 if (appBar != null) {
236 mainWebView.setVisibility(View.VISIBLE);
238 fullScreenVideoFrameLayout.removeAllViews();
239 fullScreenVideoFrameLayout.setVisibility(View.GONE);
243 // Allow the downloading of files.
244 mainWebView.setDownloadListener(new DownloadListener() {
245 // Launch the Android download manager when a link leads to a download.
247 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
248 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
249 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
251 // Add the URL as the description for the download.
252 requestUri.setDescription(url);
254 // Show the download notification after the download is completed if the API is 11 or greater.
255 if (Build.VERSION.SDK_INT >= 11) {
256 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
259 downloadManager.enqueue(requestUri);
260 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
264 // Allow pinch to zoom.
265 mainWebView.getSettings().setBuiltInZoomControls(true);
267 // Hide zoom controls if the API is 11 or greater.
268 if (Build.VERSION.SDK_INT >= 11) {
269 mainWebView.getSettings().setDisplayZoomControls(false);
272 // Initialize the default preference values the first time the program is run.
273 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
275 // Get the shared preference values.
276 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
278 // Set JavaScript initial status.
279 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
280 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
282 // Set DOM storage initial status.
283 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
284 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
286 /* Save Form Data does nothing until database storage is implemented.
287 // Set Save Form Data initial status.
288 saveFormDataEnabled = true;
289 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
292 // Set cookies initial status.
293 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
294 cookieManager = CookieManager.getInstance();
295 cookieManager.setAcceptCookie(cookiesEnabled);
297 // Set hompage initial status.
298 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
300 // Get the intent information that started the app.
301 final Intent intent = getIntent();
303 if (intent.getData() != null) {
304 // Get the intent data and convert it to a string.
305 final Uri intentUriData = intent.getData();
306 formattedUrlString = intentUriData.toString();
309 // If formattedUrlString is null assign the homepage to it.
310 if (formattedUrlString == null) {
311 formattedUrlString = homepage;
314 // Load the initial website.
315 mainWebView.loadUrl(formattedUrlString);
319 protected void onNewIntent(Intent intent) {
320 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
323 if (intent.getData() != null) {
324 // Get the intent data and convert it to a string.
325 final Uri intentUriData = intent.getData();
326 formattedUrlString = intentUriData.toString();
330 mainWebView.loadUrl(formattedUrlString);
334 public boolean onCreateOptionsMenu(Menu menu) {
335 // Inflate the menu; this adds items to the action bar if it is present.
336 getMenuInflater().inflate(R.menu.menu_webview, menu);
338 // Set mainMenu so it can be used by onOptionsItemSelected.
341 // Get MenuItems for checkable menu items.
342 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
343 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
344 /* toggleSaveFormData does nothing until database storage is implemented.
345 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
347 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
349 // Set the initial icon for toggleJavaScript
350 if (javaScriptEnabled) {
351 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
353 if (domStorageEnabled || cookiesEnabled) {
354 toggleJavaScript.setIcon(R.drawable.warning);
356 toggleJavaScript.setIcon(R.drawable.privacy_mode);
360 // Set the initial status of the menu item checkboxes.
361 toggleDomStorage.setChecked(domStorageEnabled);
362 /* toggleSaveFormData does nothing until database storage is implemented.
363 toggleSaveFormData.setChecked(saveFormDataEnabled);
365 toggleCookies.setChecked(cookiesEnabled);
371 public boolean onPrepareOptionsMenu(Menu menu) {
372 // Enable Clear Cookies if there are any.
373 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
374 clearCookies.setEnabled(cookieManager.hasCookies());
376 // Enable Back if canGoBack().
377 MenuItem back = menu.findItem(R.id.back);
378 back.setEnabled(mainWebView.canGoBack());
380 // Enable forward if canGoForward().
381 MenuItem forward = menu.findItem(R.id.forward);
382 forward.setEnabled(mainWebView.canGoForward());
384 // Run all the other default commands.
385 super.onPrepareOptionsMenu(menu);
387 // return true displays the menu.
392 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
394 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
395 @SuppressLint("SetJavaScriptEnabled")
396 // removeAllCookies is deprecated, but it is required for API < 21.
397 @SuppressWarnings("deprecation")
398 public boolean onOptionsItemSelected(MenuItem menuItem) {
399 int menuItemId = menuItem.getItemId();
401 // Some options need to update the drawable for toggleJavaScript.
402 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
404 // Set the commands that relate to the menu entries.
405 switch (menuItemId) {
406 case R.id.toggleJavaScript:
407 if (javaScriptEnabled) {
408 javaScriptEnabled = false;
409 mainWebView.getSettings().setJavaScriptEnabled(false);
410 mainWebView.reload();
412 // Update the toggleJavaScript icon and display a toast message.
413 if (domStorageEnabled || cookiesEnabled) {
414 menuItem.setIcon(R.drawable.warning);
415 if (domStorageEnabled && cookiesEnabled) {
416 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
418 if (domStorageEnabled) {
419 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
421 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
425 menuItem.setIcon(R.drawable.privacy_mode);
426 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
429 javaScriptEnabled = true;
430 menuItem.setIcon(R.drawable.javascript_enabled);
431 mainWebView.getSettings().setJavaScriptEnabled(true);
432 mainWebView.reload();
433 Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
437 case R.id.toggleDomStorage:
438 if (domStorageEnabled) {
439 domStorageEnabled = false;
440 menuItem.setChecked(false);
441 mainWebView.getSettings().setDomStorageEnabled(false);
442 mainWebView.reload();
444 // Update the toggleJavaScript icon and display a toast message if appropriate.
445 if (!javaScriptEnabled && !cookiesEnabled) {
446 toggleJavaScript.setIcon(R.drawable.privacy_mode);
447 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
449 if (cookiesEnabled) {
450 toggleJavaScript.setIcon(R.drawable.warning);
451 Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
452 } // Else Do nothing because JavaScript is enabled.
455 domStorageEnabled = true;
456 menuItem.setChecked(true);
457 mainWebView.getSettings().setDomStorageEnabled(true);
458 mainWebView.reload();
460 // Update the toggleJavaScript icon if appropriate.
461 if (!javaScriptEnabled) {
462 toggleJavaScript.setIcon(R.drawable.warning);
463 } // Else Do nothing because JavaScript is enabled.
465 Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
469 /* toggleSaveFormData does nothing until database storage is implemented.
470 case R.id.toggleSaveFormData:
471 if (saveFormDataEnabled) {
472 saveFormDataEnabled = false;
473 menuItem.setChecked(false);
474 mainWebView.getSettings().setSaveFormData(false);
475 mainWebView.reload();
477 saveFormDataEnabled = true;
478 menuItem.setChecked(true);
479 mainWebView.getSettings().setSaveFormData(true);
480 mainWebView.reload();
485 case R.id.toggleCookies:
486 if (cookiesEnabled) {
487 cookiesEnabled = false;
488 menuItem.setChecked(false);
489 cookieManager.setAcceptCookie(false);
490 mainWebView.reload();
492 // Update the toggleJavaScript icon and display a toast message if appropriate.
493 if (!javaScriptEnabled && !domStorageEnabled) {
494 toggleJavaScript.setIcon(R.drawable.privacy_mode);
495 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
497 if (domStorageEnabled) {
498 toggleJavaScript.setIcon(R.drawable.warning);
499 Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
500 } // Else Do nothing because JavaScript is enabled.
503 cookiesEnabled = true;
504 menuItem.setChecked(true);
505 cookieManager.setAcceptCookie(true);
506 mainWebView.reload();
508 // Update the toggleJavaScript icon if appropriate.
509 if (!javaScriptEnabled) {
510 toggleJavaScript.setIcon(R.drawable.warning);
511 } // Else Do nothing because JavaScript is enabled.
513 Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
517 case R.id.clearDomStorage:
518 WebStorage webStorage = WebStorage.getInstance();
519 webStorage.deleteAllData();
520 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
523 case R.id.clearCookies:
524 if (Build.VERSION.SDK_INT < 21) {
525 cookieManager.removeAllCookie();
527 cookieManager.removeAllCookies(null);
529 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
532 case R.id.addToHomescreen:
533 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
534 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
535 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
537 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
541 // Launch the system Download Manager.
542 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
544 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
545 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
547 startActivity(downloadManangerIntent);
551 mainWebView.loadUrl(homepage);
555 mainWebView.reload();
559 mainWebView.goBack();
563 mainWebView.goForward();
567 Intent shareIntent = new Intent();
568 shareIntent.setAction(Intent.ACTION_SEND);
569 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
570 shareIntent.setType("text/plain");
571 startActivity(Intent.createChooser(shareIntent, "Share URL"));
575 // Start the Settings activity.
576 Intent intent = new Intent(this, Settings.class);
577 startActivity(intent);
581 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
582 AppCompatDialogFragment aboutDialog = new AboutDialog();
583 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
586 case R.id.clearAndExit:
587 // Clear DOM storage.
588 WebStorage domStorage = WebStorage.getInstance();
589 domStorage.deleteAllData();
592 if (Build.VERSION.SDK_INT < 21) {
593 cookieManager.removeAllCookie();
595 cookieManager.removeAllCookies(null);
598 // Destroy the internal state of the webview.
599 mainWebView.destroy();
601 // Close Privacy Browser.
606 return super.onOptionsItemSelected(menuItem);
611 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
612 // Do nothing because the user selected "Cancel".
616 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
617 // Get shortcutNameEditText from the alert dialog.
618 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
620 // Create the bookmark shortcut based on formattedUrlString.
621 Intent bookmarkShortcut = new Intent();
622 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
623 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
625 // Place the bookmark shortcut on the home screen.
626 Intent placeBookmarkShortcut = new Intent();
627 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
628 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
629 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
630 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
631 sendBroadcast(placeBookmarkShortcut);
634 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
636 public void onBackPressed() {
637 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
639 if (mainWebView.canGoBack()) {
640 mainWebView.goBack();
642 super.onBackPressed();
646 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
647 // Get the text from urlTextBox and convert it to a string.
648 String unformattedUrlString = urlTextBox.getText().toString();
649 URL unformattedUrl = null;
650 Uri.Builder formattedUri = new Uri.Builder();
652 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
653 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
654 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
655 if (!unformattedUrlString.startsWith("http")) {
656 unformattedUrlString = "http://" + unformattedUrlString;
659 // 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.
661 unformattedUrl = new URL(unformattedUrlString);
662 } catch (MalformedURLException e) {
666 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
667 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
668 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
669 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
670 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
671 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
673 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
674 formattedUrlString = formattedUri.build().toString();
676 // Sanitize the search input and convert it to a DuckDuckGo search.
677 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
679 // Use the correct search URL based on javaScriptEnabled.
680 if (javaScriptEnabled) {
681 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
683 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
687 mainWebView.loadUrl(formattedUrlString);
689 // Hides the keyboard so we can see the webpage.
690 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
691 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);