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.Intent;
27 import android.content.SharedPreferences;
28 import android.graphics.Bitmap;
29 import android.net.Uri;
30 import android.os.Build;
31 import android.os.Bundle;
32 import android.preference.PreferenceManager;
33 import android.support.v4.app.DialogFragment;
34 import android.support.v4.widget.SwipeRefreshLayout;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.support.v7.widget.Toolbar;
39 import android.util.Patterns;
40 import android.view.KeyEvent;
41 import android.view.Menu;
42 import android.view.MenuItem;
43 import android.view.View;
44 import android.view.inputmethod.InputMethodManager;
45 import android.webkit.CookieManager;
46 import android.webkit.DownloadListener;
47 import android.webkit.WebChromeClient;
48 import android.webkit.WebStorage;
49 import android.webkit.WebView;
50 import android.webkit.WebViewClient;
51 import android.widget.EditText;
52 import android.widget.FrameLayout;
53 import android.widget.ImageView;
54 import android.widget.ProgressBar;
55 import android.widget.Toast;
56 import java.io.UnsupportedEncodingException;
57 import java.net.MalformedURLException;
59 import java.net.URLEncoder;
61 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
62 public class MainWebViewActivity extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
63 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
64 public static Bitmap favoriteIcon;
65 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
66 public static WebView mainWebView;
68 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
69 private Menu mainMenu;
70 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
71 private String formattedUrlString;
72 // homepage is used in onCreate() and onOptionsItemSelected().
73 private String homepage;
74 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
75 private boolean javaScriptEnabled;
76 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
77 private boolean domStorageEnabled;
79 /* saveFormDataEnabled does nothing until database storage is implemented.
80 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
81 private boolean saveFormDataEnabled;
84 // cookieManager is used in onCreate() and onOptionsItemSelected().
85 private CookieManager cookieManager;
86 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
87 private boolean cookiesEnabled;
89 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
90 private EditText urlTextBox;
93 // 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.
94 @SuppressLint("SetJavaScriptEnabled")
95 protected void onCreate(Bundle savedInstanceState) {
96 super.onCreate(savedInstanceState);
97 setContentView(R.layout.activity_webview);
99 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
100 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
101 setSupportActionBar(supportAppBar);
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 // Implement swipe to refresh
109 final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
110 swipeToRefresh.setColorSchemeResources(R.color.blue);
111 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
113 public void onRefresh() {
114 mainWebView.reload();
118 mainWebView = (WebView) findViewById(R.id.mainWebView);
120 if (appBar != null) {
121 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
122 appBar.setCustomView(R.layout.url_bar);
123 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
125 // Set the "go" button on the keyboard to load the URL in urlTextBox.
126 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
127 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
128 public boolean onKey(View v, int keyCode, KeyEvent event) {
129 // If the event is a key-down event on the "enter" button, load the URL.
130 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
131 // Load the URL into the mainWebView and consume the event.
133 loadUrlFromTextBox();
134 } catch (UnsupportedEncodingException e) {
137 // If the enter key was pressed, consume the event.
140 // If any other key was pressed, do not consume the event.
147 mainWebView.setWebViewClient(new WebViewClient() {
148 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
150 public boolean shouldOverrideUrlLoading(WebView view, String url) {
151 mainWebView.loadUrl(url);
155 /* These errors do not provide any useful information and clutter the screen.
156 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
157 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_SHORT).show();
161 // Update the URL in urlTextBox when the page starts to load.
163 public void onPageStarted(WebView view, String url, Bitmap favicon) {
164 urlTextBox.setText(url);
167 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
169 public void onPageFinished(WebView view, String url) {
170 formattedUrlString = url;
171 urlTextBox.setText(formattedUrlString);
175 mainWebView.setWebChromeClient(new WebChromeClient() {
176 // Update the progress bar when a page is loading.
178 public void onProgressChanged(WebView view, int progress) {
179 // Make sure that appBar is not null.
180 if (appBar != null) {
181 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
182 progressBar.setProgress(progress);
183 if (progress < 100) {
184 progressBar.setVisibility(View.VISIBLE);
186 progressBar.setVisibility(View.GONE);
188 //Stop the SwipeToRefresh indicator if it is running
189 swipeToRefresh.setRefreshing(false);
194 // Set the favorite icon when it changes.
196 public void onReceivedIcon(WebView view, Bitmap icon) {
197 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
200 // Place the favorite icon in the appBar if it is not null.
201 if (appBar != null) {
202 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
203 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
207 // Enter full screen video
209 public void onShowCustomView(View view, CustomViewCallback callback) {
210 if (appBar != null) {
214 fullScreenVideoFrameLayout.addView(view);
215 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
217 mainWebView.setVisibility(View.GONE);
219 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
220 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
221 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
224 // Set the one flag supported by API >= 14.
225 if (Build.VERSION.SDK_INT >= 14) {
226 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
229 // Set the two flags that are supported by API >= 16.
230 if (Build.VERSION.SDK_INT >= 16) {
231 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
234 // Set all three flags that are supported by API >= 19.
235 if (Build.VERSION.SDK_INT >= 19) {
236 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
240 // Exit full screen video
241 public void onHideCustomView() {
242 if (appBar != null) {
246 mainWebView.setVisibility(View.VISIBLE);
248 fullScreenVideoFrameLayout.removeAllViews();
249 fullScreenVideoFrameLayout.setVisibility(View.GONE);
253 // Allow the downloading of files.
254 mainWebView.setDownloadListener(new DownloadListener() {
255 // Launch the Android download manager when a link leads to a download.
257 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
258 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
259 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
261 // Add the URL as the description for the download.
262 requestUri.setDescription(url);
264 // Show the download notification after the download is completed if the API is 11 or greater.
265 if (Build.VERSION.SDK_INT >= 11) {
266 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
269 downloadManager.enqueue(requestUri);
270 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
274 // Allow pinch to zoom.
275 mainWebView.getSettings().setBuiltInZoomControls(true);
277 // Hide zoom controls if the API is 11 or greater.
278 if (Build.VERSION.SDK_INT >= 11) {
279 mainWebView.getSettings().setDisplayZoomControls(false);
282 // Initialize the default preference values the first time the program is run.
283 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
285 // Get the shared preference values.
286 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
288 // Set JavaScript initial status.
289 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
290 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
292 // Set DOM storage initial status.
293 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
294 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
296 /* Save Form Data does nothing until database storage is implemented.
297 // Set Save Form Data initial status.
298 saveFormDataEnabled = true;
299 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
302 // Set cookies initial status.
303 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
304 cookieManager = CookieManager.getInstance();
305 cookieManager.setAcceptCookie(cookiesEnabled);
307 // Set hompage initial status.
308 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
310 // Get the intent information that started the app.
311 final Intent intent = getIntent();
313 if (intent.getData() != null) {
314 // Get the intent data and convert it to a string.
315 final Uri intentUriData = intent.getData();
316 formattedUrlString = intentUriData.toString();
319 // If formattedUrlString is null assign the homepage to it.
320 if (formattedUrlString == null) {
321 formattedUrlString = homepage;
324 // Load the initial website.
325 mainWebView.loadUrl(formattedUrlString);
329 protected void onNewIntent(Intent intent) {
330 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
333 if (intent.getData() != null) {
334 // Get the intent data and convert it to a string.
335 final Uri intentUriData = intent.getData();
336 formattedUrlString = intentUriData.toString();
340 mainWebView.loadUrl(formattedUrlString);
342 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
343 mainWebView.requestFocus();
347 public boolean onCreateOptionsMenu(Menu menu) {
348 // Inflate the menu; this adds items to the action bar if it is present.
349 getMenuInflater().inflate(R.menu.menu_webview, menu);
351 // Set mainMenu so it can be used by onOptionsItemSelected.
354 // Get MenuItems for checkable menu items.
355 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
356 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
357 /* toggleSaveFormData does nothing until database storage is implemented.
358 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
360 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
362 // Set the initial icon for toggleJavaScript
363 if (javaScriptEnabled) {
364 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
366 if (domStorageEnabled || cookiesEnabled) {
367 toggleJavaScript.setIcon(R.drawable.warning);
369 toggleJavaScript.setIcon(R.drawable.privacy_mode);
373 // Set the initial status of the menu item checkboxes.
374 toggleDomStorage.setChecked(domStorageEnabled);
375 /* toggleSaveFormData does nothing until database storage is implemented.
376 toggleSaveFormData.setChecked(saveFormDataEnabled);
378 toggleCookies.setChecked(cookiesEnabled);
384 public boolean onPrepareOptionsMenu(Menu menu) {
385 // Enable Clear Cookies if there are any.
386 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
387 clearCookies.setEnabled(cookieManager.hasCookies());
389 // Enable Back if canGoBack().
390 MenuItem back = menu.findItem(R.id.back);
391 back.setEnabled(mainWebView.canGoBack());
393 // Enable forward if canGoForward().
394 MenuItem forward = menu.findItem(R.id.forward);
395 forward.setEnabled(mainWebView.canGoForward());
397 // Run all the other default commands.
398 super.onPrepareOptionsMenu(menu);
400 // return true displays the menu.
405 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
407 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
408 @SuppressLint("SetJavaScriptEnabled")
409 // removeAllCookies is deprecated, but it is required for API < 21.
410 @SuppressWarnings("deprecation")
411 public boolean onOptionsItemSelected(MenuItem menuItem) {
412 int menuItemId = menuItem.getItemId();
414 // Some options need to update the drawable for toggleJavaScript.
415 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
417 // Set the commands that relate to the menu entries.
418 switch (menuItemId) {
419 case R.id.toggleJavaScript:
420 if (javaScriptEnabled) {
421 javaScriptEnabled = false;
422 mainWebView.getSettings().setJavaScriptEnabled(false);
423 mainWebView.reload();
425 // Update the toggleJavaScript icon and display a toast message.
426 if (domStorageEnabled || cookiesEnabled) {
427 menuItem.setIcon(R.drawable.warning);
428 if (domStorageEnabled && cookiesEnabled) {
429 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
431 if (domStorageEnabled) {
432 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
434 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
438 menuItem.setIcon(R.drawable.privacy_mode);
439 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
442 javaScriptEnabled = true;
443 menuItem.setIcon(R.drawable.javascript_enabled);
444 mainWebView.getSettings().setJavaScriptEnabled(true);
445 mainWebView.reload();
446 Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
450 case R.id.toggleDomStorage:
451 if (domStorageEnabled) {
452 domStorageEnabled = false;
453 menuItem.setChecked(false);
454 mainWebView.getSettings().setDomStorageEnabled(false);
455 mainWebView.reload();
457 // Update the toggleJavaScript icon and display a toast message if appropriate.
458 if (!javaScriptEnabled && !cookiesEnabled) {
459 toggleJavaScript.setIcon(R.drawable.privacy_mode);
460 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
462 if (cookiesEnabled) {
463 toggleJavaScript.setIcon(R.drawable.warning);
464 Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
465 } // Else Do nothing because JavaScript is enabled.
468 domStorageEnabled = true;
469 menuItem.setChecked(true);
470 mainWebView.getSettings().setDomStorageEnabled(true);
471 mainWebView.reload();
473 // Update the toggleJavaScript icon if appropriate.
474 if (!javaScriptEnabled) {
475 toggleJavaScript.setIcon(R.drawable.warning);
476 } // Else Do nothing because JavaScript is enabled.
478 Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
482 /* toggleSaveFormData does nothing until database storage is implemented.
483 case R.id.toggleSaveFormData:
484 if (saveFormDataEnabled) {
485 saveFormDataEnabled = false;
486 menuItem.setChecked(false);
487 mainWebView.getSettings().setSaveFormData(false);
488 mainWebView.reload();
490 saveFormDataEnabled = true;
491 menuItem.setChecked(true);
492 mainWebView.getSettings().setSaveFormData(true);
493 mainWebView.reload();
498 case R.id.toggleCookies:
499 if (cookiesEnabled) {
500 cookiesEnabled = false;
501 menuItem.setChecked(false);
502 cookieManager.setAcceptCookie(false);
503 mainWebView.reload();
505 // Update the toggleJavaScript icon and display a toast message if appropriate.
506 if (!javaScriptEnabled && !domStorageEnabled) {
507 toggleJavaScript.setIcon(R.drawable.privacy_mode);
508 Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
510 if (domStorageEnabled) {
511 toggleJavaScript.setIcon(R.drawable.warning);
512 Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
513 } // Else Do nothing because JavaScript is enabled.
516 cookiesEnabled = true;
517 menuItem.setChecked(true);
518 cookieManager.setAcceptCookie(true);
519 mainWebView.reload();
521 // Update the toggleJavaScript icon if appropriate.
522 if (!javaScriptEnabled) {
523 toggleJavaScript.setIcon(R.drawable.warning);
524 } // Else Do nothing because JavaScript is enabled.
526 Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
530 case R.id.clearDomStorage:
531 WebStorage webStorage = WebStorage.getInstance();
532 webStorage.deleteAllData();
533 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
536 case R.id.clearCookies:
537 if (Build.VERSION.SDK_INT < 21) {
538 cookieManager.removeAllCookie();
540 cookieManager.removeAllCookies(null);
542 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
545 case R.id.addToHomescreen:
546 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
547 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
548 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
550 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
554 // Launch the system Download Manager.
555 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
557 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
558 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
560 startActivity(downloadManangerIntent);
564 mainWebView.loadUrl(homepage);
568 mainWebView.goBack();
572 mainWebView.goForward();
576 Intent shareIntent = new Intent();
577 shareIntent.setAction(Intent.ACTION_SEND);
578 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
579 shareIntent.setType("text/plain");
580 startActivity(Intent.createChooser(shareIntent, "Share URL"));
584 // Launch SettingsActivity.
585 Intent intent = new Intent(this, SettingsActivity.class);
586 startActivity(intent);
590 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
591 AppCompatDialogFragment aboutDialog = new AboutDialog();
592 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
595 case R.id.clearAndExit:
596 // Clear DOM storage.
597 WebStorage domStorage = WebStorage.getInstance();
598 domStorage.deleteAllData();
600 // Clear cookies. The commands changed slightly in API 21.
601 if (Build.VERSION.SDK_INT >= 21) {
602 cookieManager.removeAllCookies(null);
604 cookieManager.removeAllCookie();
607 // Destroy the internal state of the webview.
608 mainWebView.destroy();
610 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
611 if (Build.VERSION.SDK_INT >= 21) {
612 finishAndRemoveTask();
619 return super.onOptionsItemSelected(menuItem);
624 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
625 // Do nothing because the user selected "Cancel".
629 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
630 // Get shortcutNameEditText from the alert dialog.
631 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
633 // Create the bookmark shortcut based on formattedUrlString.
634 Intent bookmarkShortcut = new Intent();
635 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
636 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
638 // Place the bookmark shortcut on the home screen.
639 Intent placeBookmarkShortcut = new Intent();
640 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
641 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
642 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
643 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
644 sendBroadcast(placeBookmarkShortcut);
647 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
649 public void onBackPressed() {
650 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
652 if (mainWebView.canGoBack()) {
653 mainWebView.goBack();
655 super.onBackPressed();
659 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
660 // Get the text from urlTextBox and convert it to a string.
661 String unformattedUrlString = urlTextBox.getText().toString();
662 URL unformattedUrl = null;
663 Uri.Builder formattedUri = new Uri.Builder();
665 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
666 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
667 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
668 if (!unformattedUrlString.startsWith("http")) {
669 unformattedUrlString = "http://" + unformattedUrlString;
672 // 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.
674 unformattedUrl = new URL(unformattedUrlString);
675 } catch (MalformedURLException e) {
679 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
680 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
681 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
682 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
683 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
684 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
686 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
687 formattedUrlString = formattedUri.build().toString();
689 // Sanitize the search input and convert it to a DuckDuckGo search.
690 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
692 // Use the correct search URL based on javaScriptEnabled.
693 if (javaScriptEnabled) {
694 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
696 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
700 mainWebView.loadUrl(formattedUrlString);
702 // Hides the keyboard so we can see the webpage.
703 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
704 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);