1 package com.stoutner.privacybrowser;
3 import android.annotation.SuppressLint;
4 import android.app.Activity;
5 import android.content.Intent;
6 import android.graphics.Bitmap;
7 import android.net.Uri;
8 import android.os.Bundle;
9 import android.support.v4.widget.SwipeRefreshLayout;
10 import android.support.v7.app.ActionBar;
11 import android.support.v7.app.AppCompatActivity;
12 import android.util.Patterns;
13 import android.view.KeyEvent;
14 import android.view.Menu;
15 import android.view.MenuItem;
16 import android.view.View;
17 import android.view.ViewTreeObserver;
18 import android.view.Window;
19 import android.view.inputmethod.InputMethodManager;
20 import android.webkit.WebChromeClient;
21 import android.webkit.WebView;
22 import android.webkit.WebViewClient;
23 import android.widget.EditText;
24 import android.widget.ImageView;
25 import android.widget.ProgressBar;
26 import java.io.UnsupportedEncodingException;
27 import java.net.MalformedURLException;
29 import java.net.URLEncoder;
31 public class Webview extends AppCompatActivity {
33 static String formattedUrlString;
34 static WebView mainWebView;
35 static ProgressBar progressBar;
36 static SwipeRefreshLayout swipeToRefresh;
37 static EditText urlTextBox;
38 static ImageView favoriteIcon;
39 static final String homepage = "https://www.duckduckgo.com";
41 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
42 @SuppressLint("SetJavaScriptEnabled")
45 protected void onCreate(Bundle savedInstanceState) {
46 super.onCreate(savedInstanceState);
47 setContentView(R.layout.activity_webview);
49 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayoutContainer);
50 mainWebView = (WebView) findViewById(R.id.mainWebView);
52 final ActionBar actionBar = getSupportActionBar();
53 if (actionBar != null) {
54 // Remove the title from the action bar.
55 actionBar.setDisplayShowTitleEnabled(false);
57 // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
58 actionBar.setCustomView(R.layout.app_bar);
59 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
61 // Initialize the variables for favoriteIcon, urlTextBox, and progressBar
62 favoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
63 urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
64 progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
66 // TODO actionBar.setHideOnContentScrollEnabled(true);
69 // Implement swipe down to refresh.
70 swipeToRefresh.setColorSchemeColors(0xFF0097FF);
71 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
73 public void onRefresh() {
74 mainWebView.loadUrl(formattedUrlString);
78 // Only enable swipeToRefresh if is mainWebView is scrolled to the top.
79 mainWebView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
81 public void onScrollChanged() {
82 if (mainWebView.getScrollY() == 0) {
83 swipeToRefresh.setEnabled(true);
85 swipeToRefresh.setEnabled(false);
90 mainWebView.setWebViewClient(new WebViewClient() {
92 // setWebViewClient makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
93 // Save the URL to formattedUrlString and update urlTextBox before loading mainWebView.
95 public boolean shouldOverrideUrlLoading(WebView view, String url) {
96 mainWebView.loadUrl(url);
100 // Update the URL in urlTextBox when the page starts to load.
102 public void onPageStarted(WebView view, String url, Bitmap favicon) {
103 urlTextBox.setText(url);
106 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
108 public void onPageFinished(WebView view, String url) {
109 formattedUrlString = url;
110 urlTextBox.setText(formattedUrlString);
114 mainWebView.setWebChromeClient(new WebChromeClient() {
116 // Update the progress bar when a page is loading.
118 public void onProgressChanged(WebView view, int progress) {
119 progressBar.setProgress(progress);
120 if (progress < 100) {
121 progressBar.setVisibility(View.VISIBLE);
123 progressBar.setVisibility(View.GONE);
125 // Stop the refreshing indicator if it is running.
126 swipeToRefresh.setRefreshing(false);
130 // Set the favorite icon when it changes.
132 public void onReceivedIcon(WebView view, Bitmap icon) {
133 favoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
137 // Set the "go" button on the keyboard to load the URL.
138 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
139 public boolean onKey(View v, int keyCode, KeyEvent event) {
141 // If the event is a key-down event on the "enter" button, load the URL.
142 if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
143 (keyCode == KeyEvent.KEYCODE_ENTER)) {
144 // Load the URL into the mainWebView and consume the event.
146 loadUrlFromTextBox(mainWebView);
147 } catch (UnsupportedEncodingException e) {
150 // If the enter key was pressed, consume the event.
153 // If any other key was pressed, do not consume the event.
158 // Allow pinch to zoom.
159 mainWebView.getSettings().setBuiltInZoomControls(true);
161 // Hide zoom controls.
162 mainWebView.getSettings().setDisplayZoomControls(false);
164 // Enable JavaScript.
165 mainWebView.getSettings().setJavaScriptEnabled(true);
167 // Enable DOM Storage.
168 mainWebView.getSettings().setDomStorageEnabled(true);
170 // Get the intent information that started the app.
171 final Intent intent = getIntent();
173 if (intent.getData() != null) {
174 // Get the intent data and convert it to a string.
175 final Uri intentUriData = intent.getData();
176 formattedUrlString = intentUriData.toString();
179 // If formattedUrlString is null assign the homepage to it.
180 if (formattedUrlString == null) {
181 formattedUrlString = homepage;
184 // Load the initial website.
185 mainWebView.loadUrl(formattedUrlString);
189 public boolean onCreateOptionsMenu(Menu menu) {
190 // Inflate the menu; this adds items to the action bar if it is present.
191 getMenuInflater().inflate(R.menu.menu_webview, menu);
196 public boolean onOptionsItemSelected(MenuItem menuItem) {
197 int menuItemId = menuItem.getItemId();
199 // Sets the commands that relate to the menu entries.
200 switch (menuItemId) {
202 mainWebView.loadUrl(homepage);
206 mainWebView.goBack();
210 mainWebView.goForward();
214 return super.onOptionsItemSelected(menuItem);
217 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
219 public void onBackPressed() {
220 if (mainWebView.canGoBack()) {
221 mainWebView.goBack();
223 super.onBackPressed();
227 public void loadUrlFromTextBox(View view) throws UnsupportedEncodingException {
228 // Get the text from urlTextInput and convert it to a string.
229 String unformattedUrlString = urlTextBox.getText().toString();
230 URL unformattedUrl = null;
231 Uri.Builder formattedUri = new Uri.Builder();
233 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
234 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
236 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
237 if (!unformattedUrlString.startsWith("http")) {
238 unformattedUrlString = "http://" + unformattedUrlString;
241 // 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.
243 unformattedUrl = new URL(unformattedUrlString);
244 } catch (MalformedURLException e) {
248 // The ternary operator (? :) makes sure that unformattedUrl.get() does not cause a null pointer exception.
249 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
250 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
251 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
252 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
253 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
255 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
256 formattedUrlString = formattedUri.build().toString();
259 // Sanitize the search input.
260 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
261 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
264 mainWebView.loadUrl(formattedUrlString);
266 // Hides the keyboard so we can see the webpage.
267 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
268 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);