2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/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;
57 import java.io.UnsupportedEncodingException;
58 import java.net.MalformedURLException;
60 import java.net.URLEncoder;
62 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
63 public class MainWebViewActivity extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
64 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
65 public static Bitmap favoriteIcon;
66 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
67 public static WebView mainWebView;
69 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
70 private Menu mainMenu;
71 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
72 private String formattedUrlString;
73 // homepage is used in onCreate() and onOptionsItemSelected().
74 private String homepage;
75 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
76 private boolean javaScriptEnabled;
77 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
78 private boolean domStorageEnabled;
80 /* saveFormDataEnabled does nothing until database storage is implemented.
81 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
82 private boolean saveFormDataEnabled;
85 // cookieManager is used in onCreate() and onOptionsItemSelected().
86 private CookieManager cookieManager;
87 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
88 private boolean cookiesEnabled;
90 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
91 private EditText urlTextBox;
94 // 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.
95 @SuppressLint("SetJavaScriptEnabled")
96 protected void onCreate(Bundle savedInstanceState) {
97 super.onCreate(savedInstanceState);
98 setContentView(R.layout.activity_webview);
100 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
101 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
102 setSupportActionBar(supportAppBar);
104 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
105 final Activity mainWebViewActivity = this;
106 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
107 final ActionBar appBar = getSupportActionBar();
109 // Setup AdView for the free flavor.
110 final View adView = findViewById(R.id.adView);
112 // Implement swipe to refresh
113 final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
114 swipeToRefresh.setColorSchemeResources(R.color.blue);
115 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
117 public void onRefresh() {
118 mainWebView.reload();
122 mainWebView = (WebView) findViewById(R.id.mainWebView);
124 if (appBar != null) {
125 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
126 appBar.setCustomView(R.layout.url_bar);
127 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
129 // Set the "go" button on the keyboard to load the URL in urlTextBox.
130 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
131 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
132 public boolean onKey(View v, int keyCode, KeyEvent event) {
133 // If the event is a key-down event on the "enter" button, load the URL.
134 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
135 // Load the URL into the mainWebView and consume the event.
137 loadUrlFromTextBox();
138 } catch (UnsupportedEncodingException e) {
141 // If the enter key was pressed, consume the event.
144 // If any other key was pressed, do not consume the event.
151 mainWebView.setWebViewClient(new WebViewClient() {
152 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
154 public boolean shouldOverrideUrlLoading(WebView view, String url) {
155 mainWebView.loadUrl(url);
159 /* These errors do not provide any useful information and clutter the screen.
160 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
161 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_SHORT).show();
165 // Update the URL in urlTextBox when the page starts to load.
167 public void onPageStarted(WebView view, String url, Bitmap favicon) {
168 urlTextBox.setText(url);
171 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
173 public void onPageFinished(WebView view, String url) {
174 formattedUrlString = url;
175 urlTextBox.setText(formattedUrlString);
179 mainWebView.setWebChromeClient(new WebChromeClient() {
180 // Update the progress bar when a page is loading.
182 public void onProgressChanged(WebView view, int progress) {
183 // Make sure that appBar is not null.
184 if (appBar != null) {
185 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
186 progressBar.setProgress(progress);
187 if (progress < 100) {
188 progressBar.setVisibility(View.VISIBLE);
190 progressBar.setVisibility(View.GONE);
192 //Stop the SwipeToRefresh indicator if it is running
193 swipeToRefresh.setRefreshing(false);
198 // Set the favorite icon when it changes.
200 public void onReceivedIcon(WebView view, Bitmap icon) {
201 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
204 // Place the favorite icon in the appBar if it is not null.
205 if (appBar != null) {
206 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
207 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
211 // Enter full screen video
213 public void onShowCustomView(View view, CustomViewCallback callback) {
214 if (appBar != null) {
218 // Show the fullScreenVideoFrameLayout.
219 fullScreenVideoFrameLayout.addView(view);
220 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
222 // Hide the mainWebView.
223 mainWebView.setVisibility(View.GONE);
225 // Hide the ad if this is the free flavor.
226 BannerAd.hideAd(adView);
228 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
229 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
230 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
233 // Set the one flag supported by API >= 14.
234 if (Build.VERSION.SDK_INT >= 14) {
235 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
238 // Set the two flags that are supported by API >= 16.
239 if (Build.VERSION.SDK_INT >= 16) {
240 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
243 // Set all three flags that are supported by API >= 19.
244 if (Build.VERSION.SDK_INT >= 19) {
245 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
249 // Exit full screen video
250 public void onHideCustomView() {
251 if (appBar != null) {
255 // Show the mainWebView.
256 mainWebView.setVisibility(View.VISIBLE);
258 // Show the ad if this is the free flavor.
259 BannerAd.showAd(adView);
261 // Hide the fullScreenVideoFrameLayout.
262 fullScreenVideoFrameLayout.removeAllViews();
263 fullScreenVideoFrameLayout.setVisibility(View.GONE);
267 // Allow the downloading of files.
268 mainWebView.setDownloadListener(new DownloadListener() {
269 // Launch the Android download manager when a link leads to a download.
271 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
272 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
273 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
275 // Add the URL as the description for the download.
276 requestUri.setDescription(url);
278 // Show the download notification after the download is completed if the API is 11 or greater.
279 if (Build.VERSION.SDK_INT >= 11) {
280 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
283 downloadManager.enqueue(requestUri);
284 Toast.makeText(mainWebViewActivity, R.string.download_started, Toast.LENGTH_SHORT).show();
288 // Allow pinch to zoom.
289 mainWebView.getSettings().setBuiltInZoomControls(true);
291 // Hide zoom controls if the API is 11 or greater.
292 if (Build.VERSION.SDK_INT >= 11) {
293 mainWebView.getSettings().setDisplayZoomControls(false);
296 // Initialize the default preference values the first time the program is run.
297 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
299 // Get the shared preference values.
300 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
302 // Set JavaScript initial status.
303 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
304 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
306 // Set DOM storage initial status.
307 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
308 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
310 /* Save Form Data does nothing until database storage is implemented.
311 // Set Save Form Data initial status.
312 saveFormDataEnabled = true;
313 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
316 // Set cookies initial status.
317 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
318 cookieManager = CookieManager.getInstance();
319 cookieManager.setAcceptCookie(cookiesEnabled);
321 // Set homepage initial status.
322 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
324 // Get the intent information that started the app.
325 final Intent intent = getIntent();
327 if (intent.getData() != null) {
328 // Get the intent data and convert it to a string.
329 final Uri intentUriData = intent.getData();
330 formattedUrlString = intentUriData.toString();
333 // If formattedUrlString is null assign the homepage to it.
334 if (formattedUrlString == null) {
335 formattedUrlString = homepage;
338 // Load the initial website.
339 mainWebView.loadUrl(formattedUrlString);
341 // Load the ad if this is the free flavor.
342 BannerAd.requestAd(adView);
346 protected void onNewIntent(Intent intent) {
347 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
350 if (intent.getData() != null) {
351 // Get the intent data and convert it to a string.
352 final Uri intentUriData = intent.getData();
353 formattedUrlString = intentUriData.toString();
357 mainWebView.loadUrl(formattedUrlString);
359 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
360 mainWebView.requestFocus();
364 public boolean onCreateOptionsMenu(Menu menu) {
365 // Inflate the menu; this adds items to the action bar if it is present.
366 getMenuInflater().inflate(R.menu.menu_webview, menu);
368 // Set mainMenu so it can be used by onOptionsItemSelected.
371 // Get MenuItems for checkable menu items.
372 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
373 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
374 /* toggleSaveFormData does nothing until database storage is implemented.
375 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
377 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
379 // Set the initial icon for toggleJavaScript
380 if (javaScriptEnabled) {
381 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
383 if (domStorageEnabled || cookiesEnabled) {
384 toggleJavaScript.setIcon(R.drawable.warning);
386 toggleJavaScript.setIcon(R.drawable.privacy_mode);
390 // Set the initial status of the menu item checkboxes.
391 toggleDomStorage.setChecked(domStorageEnabled);
392 /* toggleSaveFormData does nothing until database storage is implemented.
393 toggleSaveFormData.setChecked(saveFormDataEnabled);
395 toggleCookies.setChecked(cookiesEnabled);
401 public boolean onPrepareOptionsMenu(Menu menu) {
402 // Enable Clear Cookies if there are any.
403 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
404 clearCookies.setEnabled(cookieManager.hasCookies());
406 // Enable Back if canGoBack().
407 MenuItem back = menu.findItem(R.id.back);
408 back.setEnabled(mainWebView.canGoBack());
410 // Enable forward if canGoForward().
411 MenuItem forward = menu.findItem(R.id.forward);
412 forward.setEnabled(mainWebView.canGoForward());
414 // Run all the other default commands.
415 super.onPrepareOptionsMenu(menu);
417 // return true displays the menu.
422 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
424 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
425 @SuppressLint("SetJavaScriptEnabled")
426 // removeAllCookies is deprecated, but it is required for API < 21.
427 @SuppressWarnings("deprecation")
428 public boolean onOptionsItemSelected(MenuItem menuItem) {
429 int menuItemId = menuItem.getItemId();
431 // Some options need to update the drawable for toggleJavaScript.
432 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
434 // Set the commands that relate to the menu entries.
435 switch (menuItemId) {
436 case R.id.toggleJavaScript:
437 if (javaScriptEnabled) {
438 javaScriptEnabled = false;
439 mainWebView.getSettings().setJavaScriptEnabled(false);
440 mainWebView.reload();
442 // Update the toggleJavaScript icon and display a toast message.
443 if (domStorageEnabled || cookiesEnabled) {
444 menuItem.setIcon(R.drawable.warning);
445 if (domStorageEnabled && cookiesEnabled) {
446 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
448 if (domStorageEnabled) {
449 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
451 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
455 menuItem.setIcon(R.drawable.privacy_mode);
456 Toast.makeText(getApplicationContext(), R.string.privacy_mode, Toast.LENGTH_SHORT).show();
459 javaScriptEnabled = true;
460 menuItem.setIcon(R.drawable.javascript_enabled);
461 mainWebView.getSettings().setJavaScriptEnabled(true);
462 mainWebView.reload();
463 Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
467 case R.id.toggleDomStorage:
468 if (domStorageEnabled) {
469 domStorageEnabled = false;
470 menuItem.setChecked(false);
471 mainWebView.getSettings().setDomStorageEnabled(false);
472 mainWebView.reload();
474 // Update the toggleJavaScript icon and display a toast message if appropriate.
475 if (!javaScriptEnabled && !cookiesEnabled) {
476 toggleJavaScript.setIcon(R.drawable.privacy_mode);
477 Toast.makeText(getApplicationContext(), R.string.privacy_mode, Toast.LENGTH_SHORT).show();
479 if (cookiesEnabled) {
480 toggleJavaScript.setIcon(R.drawable.warning);
481 Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
482 } // Else Do nothing because JavaScript is enabled.
485 domStorageEnabled = true;
486 menuItem.setChecked(true);
487 mainWebView.getSettings().setDomStorageEnabled(true);
488 mainWebView.reload();
490 // Update the toggleJavaScript icon if appropriate.
491 if (!javaScriptEnabled) {
492 toggleJavaScript.setIcon(R.drawable.warning);
493 } // Else Do nothing because JavaScript is enabled.
495 Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
499 /* toggleSaveFormData does nothing until database storage is implemented.
500 case R.id.toggleSaveFormData:
501 if (saveFormDataEnabled) {
502 saveFormDataEnabled = false;
503 menuItem.setChecked(false);
504 mainWebView.getSettings().setSaveFormData(false);
505 mainWebView.reload();
507 saveFormDataEnabled = true;
508 menuItem.setChecked(true);
509 mainWebView.getSettings().setSaveFormData(true);
510 mainWebView.reload();
515 case R.id.toggleCookies:
516 if (cookiesEnabled) {
517 cookiesEnabled = false;
518 menuItem.setChecked(false);
519 cookieManager.setAcceptCookie(false);
520 mainWebView.reload();
522 // Update the toggleJavaScript icon and display a toast message if appropriate.
523 if (!javaScriptEnabled && !domStorageEnabled) {
524 toggleJavaScript.setIcon(R.drawable.privacy_mode);
525 Toast.makeText(getApplicationContext(), R.string.privacy_mode, Toast.LENGTH_SHORT).show();
527 if (domStorageEnabled) {
528 toggleJavaScript.setIcon(R.drawable.warning);
529 Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
530 } // Else Do nothing because JavaScript is enabled.
533 cookiesEnabled = true;
534 menuItem.setChecked(true);
535 cookieManager.setAcceptCookie(true);
536 mainWebView.reload();
538 // Update the toggleJavaScript icon if appropriate.
539 if (!javaScriptEnabled) {
540 toggleJavaScript.setIcon(R.drawable.warning);
541 } // Else Do nothing because JavaScript is enabled.
543 Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
547 case R.id.clearDomStorage:
548 WebStorage webStorage = WebStorage.getInstance();
549 webStorage.deleteAllData();
550 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
553 case R.id.clearCookies:
554 if (Build.VERSION.SDK_INT < 21) {
555 cookieManager.removeAllCookie();
557 cookieManager.removeAllCookies(null);
559 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
562 case R.id.addToHomescreen:
563 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
564 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
565 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
567 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
571 // Launch the system Download Manager.
572 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
574 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
575 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
577 startActivity(downloadManagerIntent);
581 mainWebView.loadUrl(homepage);
585 mainWebView.goBack();
589 mainWebView.goForward();
593 Intent shareIntent = new Intent();
594 shareIntent.setAction(Intent.ACTION_SEND);
595 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
596 shareIntent.setType("text/plain");
597 startActivity(Intent.createChooser(shareIntent, "Share URL"));
601 // Launch SettingsActivity.
602 Intent intent = new Intent(this, SettingsActivity.class);
603 startActivity(intent);
607 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
608 AppCompatDialogFragment aboutDialog = new AboutDialog();
609 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
612 case R.id.clearAndExit:
613 // Clear DOM storage.
614 WebStorage domStorage = WebStorage.getInstance();
615 domStorage.deleteAllData();
617 // Clear cookies. The commands changed slightly in API 21.
618 if (Build.VERSION.SDK_INT >= 21) {
619 cookieManager.removeAllCookies(null);
621 cookieManager.removeAllCookie();
624 // Destroy the internal state of the webview.
625 mainWebView.destroy();
627 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
628 if (Build.VERSION.SDK_INT >= 21) {
629 finishAndRemoveTask();
636 return super.onOptionsItemSelected(menuItem);
641 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
642 // Do nothing because the user selected "Cancel".
646 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
647 // Get shortcutNameEditText from the alert dialog.
648 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
650 // Create the bookmark shortcut based on formattedUrlString.
651 Intent bookmarkShortcut = new Intent();
652 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
653 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
655 // Place the bookmark shortcut on the home screen.
656 Intent placeBookmarkShortcut = new Intent();
657 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
658 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
659 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
660 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
661 sendBroadcast(placeBookmarkShortcut);
664 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
666 public void onBackPressed() {
667 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
669 if (mainWebView.canGoBack()) {
670 mainWebView.goBack();
672 super.onBackPressed();
676 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
677 // Get the text from urlTextBox and convert it to a string.
678 String unformattedUrlString = urlTextBox.getText().toString();
679 URL unformattedUrl = null;
680 Uri.Builder formattedUri = new Uri.Builder();
682 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
683 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
684 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
685 if (!unformattedUrlString.startsWith("http")) {
686 unformattedUrlString = "http://" + unformattedUrlString;
689 // 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.
691 unformattedUrl = new URL(unformattedUrlString);
692 } catch (MalformedURLException e) {
696 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
697 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
698 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
699 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
700 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
701 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
703 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
704 formattedUrlString = formattedUri.build().toString();
706 // Sanitize the search input and convert it to a DuckDuckGo search.
707 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
709 // Use the correct search URL based on javaScriptEnabled.
710 if (javaScriptEnabled) {
711 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
713 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
717 mainWebView.loadUrl(formattedUrlString);
719 // Hides the keyboard so we can see the webpage.
720 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
721 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);