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.app.Activity;
24 import android.app.DownloadManager;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.graphics.Bitmap;
28 import android.net.Uri;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.preference.PreferenceManager;
32 import android.support.design.widget.Snackbar;
33 import android.support.v4.app.DialogFragment;
34 import android.support.v4.widget.DrawerLayout;
35 import android.support.v4.widget.SwipeRefreshLayout;
36 import android.support.v7.app.ActionBar;
37 import android.support.v7.app.ActionBarDrawerToggle;
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;
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 MainWebViewActivity 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 // DrawerTottle is use in onCrate() and onPostCreate().
71 private ActionBarDrawerToggle drawerToggle;
72 // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
73 private Menu mainMenu;
74 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
75 private String formattedUrlString;
76 // homepage is used in onCreate() and onOptionsItemSelected().
77 private String homepage;
78 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
79 private boolean javaScriptEnabled;
80 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
81 private boolean domStorageEnabled;
83 /* saveFormDataEnabled does nothing until database storage is implemented.
84 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
85 private boolean saveFormDataEnabled;
88 // cookieManager is used in onCreate() and onOptionsItemSelected().
89 private CookieManager cookieManager;
90 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
91 private boolean cookiesEnabled;
93 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
94 private EditText urlTextBox;
97 // 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.
98 @SuppressLint("SetJavaScriptEnabled")
99 protected void onCreate(Bundle savedInstanceState) {
100 super.onCreate(savedInstanceState);
101 setContentView(R.layout.coordinator_layout);
103 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
104 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
105 setSupportActionBar(supportAppBar);
107 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
109 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
110 final ActionBar appBar = getSupportActionBar();
112 // Setup AdView for the free flavor.
113 final View adView = findViewById(R.id.adView);
115 // Implement swipe to refresh
116 final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
117 swipeToRefresh.setColorSchemeResources(R.color.blue);
118 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
120 public void onRefresh() {
121 mainWebView.reload();
125 mainWebView = (WebView) findViewById(R.id.mainWebView);
127 if (appBar != null) {
128 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
129 appBar.setCustomView(R.layout.url_bar);
130 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
132 // Set the "go" button on the keyboard to load the URL in urlTextBox.
133 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
134 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
135 public boolean onKey(View v, int keyCode, KeyEvent event) {
136 // If the event is a key-down event on the "enter" button, load the URL.
137 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
138 // Load the URL into the mainWebView and consume the event.
140 loadUrlFromTextBox();
141 } catch (UnsupportedEncodingException e) {
144 // If the enter key was pressed, consume the event.
147 // If any other key was pressed, do not consume the event.
154 DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
155 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
157 mainWebView.setWebViewClient(new WebViewClient() {
158 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
160 public boolean shouldOverrideUrlLoading(WebView view, String url) {
161 mainWebView.loadUrl(url);
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;
176 // Only update urlTextBox if the user is not typing in it.
177 if (!urlTextBox.hasFocus()) {
178 urlTextBox.setText(formattedUrlString);
183 mainWebView.setWebChromeClient(new WebChromeClient() {
184 // Update the progress bar when a page is loading.
186 public void onProgressChanged(WebView view, int progress) {
187 // Make sure that appBar is not null.
188 if (appBar != null) {
189 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
190 progressBar.setProgress(progress);
191 if (progress < 100) {
192 progressBar.setVisibility(View.VISIBLE);
194 progressBar.setVisibility(View.GONE);
196 //Stop the SwipeToRefresh indicator if it is running
197 swipeToRefresh.setRefreshing(false);
202 // Set the favorite icon when it changes.
204 public void onReceivedIcon(WebView view, Bitmap icon) {
205 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
208 // Place the favorite icon in the appBar if it is not null.
209 if (appBar != null) {
210 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
211 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
215 // Enter full screen video
217 public void onShowCustomView(View view, CustomViewCallback callback) {
218 if (appBar != null) {
222 // Show the fullScreenVideoFrameLayout.
223 fullScreenVideoFrameLayout.addView(view);
224 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
226 // Hide the mainWebView.
227 mainWebView.setVisibility(View.GONE);
229 // Hide the ad if this is the free flavor.
230 BannerAd.hideAd(adView);
232 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
233 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
234 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
237 // Set the one flag supported by API >= 14.
238 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
240 // Set the two flags that are supported by API >= 16.
241 if (Build.VERSION.SDK_INT >= 16) {
242 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
245 // Set all three flags that are supported by API >= 19.
246 if (Build.VERSION.SDK_INT >= 19) {
247 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
251 // Exit full screen video
252 public void onHideCustomView() {
253 if (appBar != null) {
257 // Show the mainWebView.
258 mainWebView.setVisibility(View.VISIBLE);
260 // Show the ad if this is the free flavor.
261 BannerAd.showAd(adView);
263 // Hide the fullScreenVideoFrameLayout.
264 fullScreenVideoFrameLayout.removeAllViews();
265 fullScreenVideoFrameLayout.setVisibility(View.GONE);
269 // Allow the downloading of files.
270 mainWebView.setDownloadListener(new DownloadListener() {
271 // Launch the Android download manager when a link leads to a download.
273 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
274 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
275 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
277 // Add the URL as the description for the download.
278 requestUri.setDescription(url);
280 // Show the download notification after the download is completed.
281 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
283 // Initiate the download and display a Snackbar.
284 downloadManager.enqueue(requestUri);
285 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
289 // Allow pinch to zoom.
290 mainWebView.getSettings().setBuiltInZoomControls(true);
292 // Hide zoom controls.
293 mainWebView.getSettings().setDisplayZoomControls(false);
295 // Initialize the default preference values the first time the program is run.
296 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
298 // Get the shared preference values.
299 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
301 // Set JavaScript initial status.
302 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
303 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
305 // Set DOM storage initial status.
306 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
307 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
309 /* Save Form Data does nothing until database storage is implemented.
310 // Set Save Form Data initial status.
311 saveFormDataEnabled = true;
312 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
315 // Set cookies initial status.
316 cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
317 cookieManager = CookieManager.getInstance();
318 cookieManager.setAcceptCookie(cookiesEnabled);
320 // Set homepage initial status.
321 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
323 // Get the intent information that started the app.
324 final Intent intent = getIntent();
326 if (intent.getData() != null) {
327 // Get the intent data and convert it to a string.
328 final Uri intentUriData = intent.getData();
329 formattedUrlString = intentUriData.toString();
332 // If formattedUrlString is null assign the homepage to it.
333 if (formattedUrlString == null) {
334 formattedUrlString = homepage;
337 // Load the initial website.
338 mainWebView.loadUrl(formattedUrlString);
340 // Load the ad if this is the free flavor.
341 BannerAd.requestAd(adView);
345 protected void onNewIntent(Intent intent) {
346 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
349 if (intent.getData() != null) {
350 // Get the intent data and convert it to a string.
351 final Uri intentUriData = intent.getData();
352 formattedUrlString = intentUriData.toString();
356 mainWebView.loadUrl(formattedUrlString);
358 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
359 mainWebView.requestFocus();
363 public boolean onCreateOptionsMenu(Menu menu) {
364 // Inflate the menu; this adds items to the action bar if it is present.
365 getMenuInflater().inflate(R.menu.menu_webview, menu);
367 // Set mainMenu so it can be used by onOptionsItemSelected.
370 // Get MenuItems for checkable menu items.
371 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
372 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
373 /* toggleSaveFormData does nothing until database storage is implemented.
374 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
376 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
378 // Set the initial icon for toggleJavaScript
379 if (javaScriptEnabled) {
380 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
382 if (domStorageEnabled || cookiesEnabled) {
383 toggleJavaScript.setIcon(R.drawable.warning);
385 toggleJavaScript.setIcon(R.drawable.privacy_mode);
389 // Set the initial status of the menu item checkboxes.
390 toggleDomStorage.setChecked(domStorageEnabled);
391 /* toggleSaveFormData does nothing until database storage is implemented.
392 toggleSaveFormData.setChecked(saveFormDataEnabled);
394 toggleCookies.setChecked(cookiesEnabled);
400 public boolean onPrepareOptionsMenu(Menu menu) {
401 // Enable Clear Cookies if there are any.
402 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
403 clearCookies.setEnabled(cookieManager.hasCookies());
405 // Enable Back if canGoBack().
406 MenuItem back = menu.findItem(R.id.back);
407 back.setEnabled(mainWebView.canGoBack());
409 // Enable forward if canGoForward().
410 MenuItem forward = menu.findItem(R.id.forward);
411 forward.setEnabled(mainWebView.canGoForward());
413 // Run all the other default commands.
414 super.onPrepareOptionsMenu(menu);
416 // return true displays the menu.
421 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
422 @SuppressLint("SetJavaScriptEnabled")
423 // removeAllCookies is deprecated, but it is required for API < 21.
424 @SuppressWarnings("deprecation")
425 public boolean onOptionsItemSelected(MenuItem menuItem) {
426 int menuItemId = menuItem.getItemId();
428 // Some options need to update the drawable for toggleJavaScript.
429 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
431 // Set the commands that relate to the menu entries.
432 switch (menuItemId) {
433 case R.id.toggleJavaScript:
434 if (javaScriptEnabled) {
435 javaScriptEnabled = false;
436 mainWebView.getSettings().setJavaScriptEnabled(false);
437 mainWebView.reload();
439 // Update the toggleJavaScript icon and display a snackbar.
440 if (domStorageEnabled || cookiesEnabled) {
441 menuItem.setIcon(R.drawable.warning);
442 if (domStorageEnabled && cookiesEnabled) {
443 Snackbar.make(findViewById(R.id.mainWebView), R.string.both_still_enabled, Snackbar.LENGTH_SHORT).show();
445 if (domStorageEnabled) {
446 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_still_enabled, Snackbar.LENGTH_SHORT).show();
448 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
452 menuItem.setIcon(R.drawable.privacy_mode);
453 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
456 javaScriptEnabled = true;
457 menuItem.setIcon(R.drawable.javascript_enabled);
458 mainWebView.getSettings().setJavaScriptEnabled(true);
459 mainWebView.reload();
460 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
464 case R.id.toggleDomStorage:
465 if (domStorageEnabled) {
466 domStorageEnabled = false;
467 menuItem.setChecked(false);
468 mainWebView.getSettings().setDomStorageEnabled(false);
469 mainWebView.reload();
471 // Update the toggleJavaScript icon and display a snackbar if appropriate.
472 if (!javaScriptEnabled && !cookiesEnabled) {
473 toggleJavaScript.setIcon(R.drawable.privacy_mode);
474 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
476 if (cookiesEnabled) {
477 toggleJavaScript.setIcon(R.drawable.warning);
478 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
479 } // Else Do nothing because JavaScript is enabled.
482 domStorageEnabled = true;
483 menuItem.setChecked(true);
484 mainWebView.getSettings().setDomStorageEnabled(true);
485 mainWebView.reload();
487 // Update the toggleJavaScript icon if appropriate.
488 if (!javaScriptEnabled) {
489 toggleJavaScript.setIcon(R.drawable.warning);
490 } // Else Do nothing because JavaScript is enabled.
492 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
496 /* toggleSaveFormData does nothing until database storage is implemented.
497 case R.id.toggleSaveFormData:
498 if (saveFormDataEnabled) {
499 saveFormDataEnabled = false;
500 menuItem.setChecked(false);
501 mainWebView.getSettings().setSaveFormData(false);
502 mainWebView.reload();
504 saveFormDataEnabled = true;
505 menuItem.setChecked(true);
506 mainWebView.getSettings().setSaveFormData(true);
507 mainWebView.reload();
512 case R.id.toggleCookies:
513 if (cookiesEnabled) {
514 cookiesEnabled = false;
515 menuItem.setChecked(false);
516 cookieManager.setAcceptCookie(false);
517 mainWebView.reload();
519 // Update the toggleJavaScript icon and display a snackbar if appropriate.
520 if (!javaScriptEnabled && !domStorageEnabled) {
521 toggleJavaScript.setIcon(R.drawable.privacy_mode);
522 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
524 if (domStorageEnabled) {
525 toggleJavaScript.setIcon(R.drawable.warning);
526 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
527 } // Else Do nothing because JavaScript is enabled.
530 cookiesEnabled = true;
531 menuItem.setChecked(true);
532 cookieManager.setAcceptCookie(true);
533 mainWebView.reload();
535 // Update the toggleJavaScript icon if appropriate.
536 if (!javaScriptEnabled) {
537 toggleJavaScript.setIcon(R.drawable.warning);
538 } // Else Do nothing because JavaScript is enabled.
540 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
544 case R.id.clearDomStorage:
545 WebStorage webStorage = WebStorage.getInstance();
546 webStorage.deleteAllData();
547 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
550 case R.id.clearCookies:
551 if (Build.VERSION.SDK_INT < 21) {
552 cookieManager.removeAllCookie();
554 cookieManager.removeAllCookies(null);
556 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
559 case R.id.addToHomescreen:
560 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
561 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
562 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
564 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
568 // Launch the system Download Manager.
569 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
571 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
572 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
574 startActivity(downloadManagerIntent);
578 mainWebView.loadUrl(homepage);
582 mainWebView.goBack();
586 mainWebView.goForward();
590 Intent shareIntent = new Intent();
591 shareIntent.setAction(Intent.ACTION_SEND);
592 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
593 shareIntent.setType("text/plain");
594 startActivity(Intent.createChooser(shareIntent, "Share URL"));
598 // Launch SettingsActivity.
599 Intent intent = new Intent(this, SettingsActivity.class);
600 startActivity(intent);
604 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
605 AppCompatDialogFragment aboutDialog = new AboutDialog();
606 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
609 case R.id.clearAndExit:
610 // Clear DOM storage.
611 WebStorage domStorage = WebStorage.getInstance();
612 domStorage.deleteAllData();
614 // Clear cookies. The commands changed slightly in API 21.
615 if (Build.VERSION.SDK_INT >= 21) {
616 cookieManager.removeAllCookies(null);
618 cookieManager.removeAllCookie();
621 // Destroy the internal state of the webview.
622 mainWebView.destroy();
624 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
625 if (Build.VERSION.SDK_INT >= 21) {
626 finishAndRemoveTask();
633 return super.onOptionsItemSelected(menuItem);
638 public void onPostCreate(Bundle savedInstanceState) {
639 super.onPostCreate(savedInstanceState);
641 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
642 drawerToggle.syncState();
646 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
647 // Do nothing because the user selected "Cancel".
651 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
652 // Get shortcutNameEditText from the alert dialog.
653 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
655 // Create the bookmark shortcut based on formattedUrlString.
656 Intent bookmarkShortcut = new Intent();
657 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
658 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
660 // Place the bookmark shortcut on the home screen.
661 Intent placeBookmarkShortcut = new Intent();
662 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
663 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
664 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
665 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
666 sendBroadcast(placeBookmarkShortcut);
669 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
671 public void onBackPressed() {
672 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
674 if (mainWebView.canGoBack()) {
675 mainWebView.goBack();
677 super.onBackPressed();
681 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
682 // Get the text from urlTextBox and convert it to a string.
683 String unformattedUrlString = urlTextBox.getText().toString();
684 URL unformattedUrl = null;
685 Uri.Builder formattedUri = new Uri.Builder();
687 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
688 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
689 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
690 if (!unformattedUrlString.startsWith("http")) {
691 unformattedUrlString = "http://" + unformattedUrlString;
694 // 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.
696 unformattedUrl = new URL(unformattedUrlString);
697 } catch (MalformedURLException e) {
701 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
702 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
703 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
704 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
705 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
706 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
708 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
709 formattedUrlString = formattedUri.build().toString();
711 // Sanitize the search input and convert it to a DuckDuckGo search.
712 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
714 // Use the correct search URL based on javaScriptEnabled.
715 if (javaScriptEnabled) {
716 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
718 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
722 mainWebView.loadUrl(formattedUrlString);
724 // Hides the keyboard so we can see the webpage.
725 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
726 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);