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 access the clipboard.
402 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
404 // Some options need to update the drawable for toggleJavaScript.
405 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
407 // Sets the commands that relate to the menu entries.
408 switch (menuItemId) {
409 case R.id.toggleJavaScript:
410 if (javaScriptEnabled) {
411 javaScriptEnabled = false;
412 mainWebView.getSettings().setJavaScriptEnabled(false);
413 mainWebView.reload();
415 // Update the toggleJavaScript icon and display a toast message.
416 if (domStorageEnabled || cookiesEnabled) {
417 menuItem.setIcon(R.drawable.warning);
418 if (domStorageEnabled && cookiesEnabled) {
419 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
421 if (domStorageEnabled) {
422 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
424 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
428 menuItem.setIcon(R.drawable.privacy_mode);
429 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
432 javaScriptEnabled = true;
433 menuItem.setIcon(R.drawable.javascript_enabled);
434 mainWebView.getSettings().setJavaScriptEnabled(true);
435 mainWebView.reload();
436 Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
440 case R.id.toggleDomStorage:
441 if (domStorageEnabled) {
442 domStorageEnabled = false;
443 menuItem.setChecked(false);
444 mainWebView.getSettings().setDomStorageEnabled(false);
445 mainWebView.reload();
447 // Update the toggleJavaScript icon and display a toast message if appropriate.
448 if (!javaScriptEnabled && !cookiesEnabled) {
449 toggleJavaScript.setIcon(R.drawable.privacy_mode);
450 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
452 if (cookiesEnabled) {
453 toggleJavaScript.setIcon(R.drawable.warning);
454 Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
455 } // Else Do nothing because JavaScript is enabled.
458 domStorageEnabled = true;
459 menuItem.setChecked(true);
460 mainWebView.getSettings().setDomStorageEnabled(true);
461 mainWebView.reload();
463 // Update the toggleJavaScript icon if appropriate.
464 if (!javaScriptEnabled) {
465 toggleJavaScript.setIcon(R.drawable.warning);
466 } // Else Do nothing because JavaScript is enabled.
468 Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
472 /* toggleSaveFormData does nothing until database storage is implemented.
473 case R.id.toggleSaveFormData:
474 if (saveFormDataEnabled) {
475 saveFormDataEnabled = false;
476 menuItem.setChecked(false);
477 mainWebView.getSettings().setSaveFormData(false);
478 mainWebView.reload();
480 saveFormDataEnabled = true;
481 menuItem.setChecked(true);
482 mainWebView.getSettings().setSaveFormData(true);
483 mainWebView.reload();
488 case R.id.toggleCookies:
489 if (cookiesEnabled) {
490 cookiesEnabled = false;
491 menuItem.setChecked(false);
492 cookieManager.setAcceptCookie(false);
493 mainWebView.reload();
495 // Update the toggleJavaScript icon and display a toast message if appropriate.
496 if (!javaScriptEnabled && !domStorageEnabled) {
497 toggleJavaScript.setIcon(R.drawable.privacy_mode);
498 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
500 if (domStorageEnabled) {
501 toggleJavaScript.setIcon(R.drawable.warning);
502 Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
503 } // Else Do nothing because JavaScript is enabled.
506 cookiesEnabled = true;
507 menuItem.setChecked(true);
508 cookieManager.setAcceptCookie(true);
509 mainWebView.reload();
511 // Update the toggleJavaScript icon if appropriate.
512 if (!javaScriptEnabled) {
513 toggleJavaScript.setIcon(R.drawable.warning);
514 } // Else Do nothing because JavaScript is enabled.
516 Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
520 case R.id.clearDomStorage:
521 WebStorage webStorage = WebStorage.getInstance();
522 webStorage.deleteAllData();
523 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
526 case R.id.clearCookies:
527 if (Build.VERSION.SDK_INT < 21) {
528 cookieManager.removeAllCookie();
530 cookieManager.removeAllCookies(null);
532 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
536 mainWebView.loadUrl(homepage);
540 mainWebView.reload();
544 mainWebView.goBack();
548 mainWebView.goForward();
552 clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
556 ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
557 urlTextBox.setText(clipboardData.coerceToText(this));
559 loadUrlFromTextBox();
560 } catch (UnsupportedEncodingException e) {
566 Intent shareIntent = new Intent();
567 shareIntent.setAction(Intent.ACTION_SEND);
568 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
569 shareIntent.setType("text/plain");
570 startActivity(Intent.createChooser(shareIntent, "Share URL"));
573 case R.id.addToHomescreen:
574 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
575 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
576 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
578 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
582 // Launch the system Download Manager.
583 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
585 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
586 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
588 startActivity(downloadManangerIntent);
592 // Start the Settings activity.
593 Intent intent = new Intent(this, Settings.class);
594 startActivity(intent);
598 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
599 AppCompatDialogFragment aboutDialog = new AboutDialog();
600 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
603 case R.id.clearAndExit:
604 // Clear DOM storage.
605 WebStorage domStorage = WebStorage.getInstance();
606 domStorage.deleteAllData();
609 if (Build.VERSION.SDK_INT < 21) {
610 cookieManager.removeAllCookie();
612 cookieManager.removeAllCookies(null);
615 // Destroy the internal state of the webview.
616 mainWebView.destroy();
618 // Close Privacy Browser.
623 return super.onOptionsItemSelected(menuItem);
628 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
629 // Do nothing because the user selected "Cancel".
633 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
634 // Get shortcutNameEditText from the alert dialog.
635 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
637 // Create the bookmark shortcut based on formattedUrlString.
638 Intent bookmarkShortcut = new Intent();
639 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
640 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
642 // Place the bookmark shortcut on the home screen.
643 Intent placeBookmarkShortcut = new Intent();
644 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
645 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
646 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
647 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
648 sendBroadcast(placeBookmarkShortcut);
651 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
653 public void onBackPressed() {
654 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
656 if (mainWebView.canGoBack()) {
657 mainWebView.goBack();
659 super.onBackPressed();
663 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
664 // Get the text from urlTextBox and convert it to a string.
665 String unformattedUrlString = urlTextBox.getText().toString();
666 URL unformattedUrl = null;
667 Uri.Builder formattedUri = new Uri.Builder();
669 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
670 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
671 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
672 if (!unformattedUrlString.startsWith("http")) {
673 unformattedUrlString = "http://" + unformattedUrlString;
676 // 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.
678 unformattedUrl = new URL(unformattedUrlString);
679 } catch (MalformedURLException e) {
683 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
684 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
685 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
686 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
687 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
688 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
690 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
691 formattedUrlString = formattedUri.build().toString();
693 // Sanitize the search input and convert it to a DuckDuckGo search.
694 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
696 // Use the correct search URL based on javaScriptEnabled.
697 if (javaScriptEnabled) {
698 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
700 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
704 mainWebView.loadUrl(formattedUrlString);
706 // Hides the keyboard so we can see the webpage.
707 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
708 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);