]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/Webview.java
Remove the "Go" button.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / Webview.java
1 package com.stoutner.privacybrowser;
2
3 import android.app.Activity;
4 import android.content.Intent;
5 import android.net.Uri;
6 import android.os.Bundle;
7 import android.support.v4.widget.SwipeRefreshLayout;
8 import android.support.v7.app.AppCompatActivity;
9 import android.util.Patterns;
10 import android.view.KeyEvent;
11 import android.view.Menu;
12 import android.view.MenuItem;
13 import android.view.View;
14 import android.view.ViewTreeObserver;
15 import android.view.inputmethod.InputMethodManager;
16 import android.webkit.WebChromeClient;
17 import android.webkit.WebView;
18 import android.webkit.WebViewClient;
19 import android.widget.EditText;
20 import android.widget.ProgressBar;
21 import java.io.UnsupportedEncodingException;
22 import java.net.MalformedURLException;
23 import java.net.URL;
24 import java.net.URLEncoder;
25
26 public class Webview extends AppCompatActivity {
27
28     static String formattedUrlString;
29     static WebView mainWebView;
30     static ProgressBar progressBar;
31     static SwipeRefreshLayout swipeToRefresh;
32     static EditText urlTextBox;
33     static final String homepage = "https://www.duckduckgo.com";
34
35     @Override
36     protected void onCreate(Bundle savedInstanceState) {
37         super.onCreate(savedInstanceState);
38         setContentView(R.layout.activity_webview);
39
40         urlTextBox = (EditText) findViewById(R.id.urlTextBox);
41         swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayoutContainer);
42         mainWebView = (WebView) findViewById(R.id.mainWebView);
43         progressBar = (ProgressBar) findViewById(R.id.progressBar);
44
45         // Implement swipe down to refresh.
46         swipeToRefresh.setColorSchemeColors(0xFF0097FF);
47         swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
48             @Override
49             public void onRefresh() {
50                 mainWebView.loadUrl(formattedUrlString);
51             }
52         });
53
54         // Only enable swipeToRefresh if is mainWebView is scrolled to the top.
55         mainWebView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
56             @Override
57             public void onScrollChanged() {
58                 if (mainWebView.getScrollY() == 0) {
59                     swipeToRefresh.setEnabled(true);
60                 } else {
61                     swipeToRefresh.setEnabled(false);
62                 }
63             }
64         });
65
66         // setWebViewClient makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
67         // Save the URL to formattedUrlString and update urlTextBox before loading mainWebView.
68         mainWebView.setWebViewClient(new WebViewClient() {
69             public boolean shouldOverrideUrlLoading(WebView view, String url) {
70                 formattedUrlString = url;
71                 urlTextBox.setText(formattedUrlString);
72                 mainWebView.loadUrl(formattedUrlString);
73                 return true;
74             }
75         });
76
77         // Update the progress bar when a page is loading.
78         mainWebView.setWebChromeClient(new WebChromeClient() {
79             public void onProgressChanged(WebView view, int progress) {
80                 progressBar.setProgress(progress);
81                 if (progress < 100) {
82                     progressBar.setVisibility(View.VISIBLE);
83                 } else {
84                     progressBar.setVisibility(View.GONE);
85
86                     // Stop the refreshing indicator if it is running.
87                     swipeToRefresh.setRefreshing(false);
88
89                     // Update the URL in urlTextBox.  It is necessary to do this after the page finishes loading to get the final URL, which can change during load.
90                     formattedUrlString = mainWebView.getUrl();
91                     urlTextBox.setText(formattedUrlString);
92                 }
93             }
94         });
95
96         // Allow pinch to zoom.
97         mainWebView.getSettings().setBuiltInZoomControls(true);
98
99         // Hide zoom controls.
100         mainWebView.getSettings().setDisplayZoomControls(false);
101
102         // Enable JavaScript.
103         mainWebView.getSettings().setJavaScriptEnabled(true);
104
105         // Enable DOM Storage.
106         mainWebView.getSettings().setDomStorageEnabled(true);
107
108         // Get the intent information that started the app.
109         final Intent intent = getIntent();
110
111         if (intent.getData() != null) {
112             // Get the intent data and convert it to a string.
113             final Uri intentUriData = intent.getData();
114             Webview.formattedUrlString = intentUriData.toString();
115         }
116
117         // If formattedUrlString is null assign the homepage to it.
118         if (formattedUrlString == null) {
119             formattedUrlString = homepage;
120         }
121
122         // Place the formattedUrlString in the address bar and load the website.
123         urlTextBox.setText(formattedUrlString);
124         mainWebView.loadUrl(formattedUrlString);
125
126         // Set the "go" button on the keyboard to load the URL.
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
130                 if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
131                         (keyCode == KeyEvent.KEYCODE_ENTER)) {
132                     // Load the URL into the mainWebView and consume the event.
133                     try {
134                         loadUrlFromTextBox(mainWebView);
135                     } catch (UnsupportedEncodingException e) {
136                         e.printStackTrace();
137                     }
138                     return true;
139                 }
140                 // Do not consume the event.
141                 return false;
142             }
143         });
144
145     }
146
147     @Override
148     public boolean onCreateOptionsMenu(Menu menu) {
149         // Inflate the menu; this adds items to the action bar if it is present.
150         getMenuInflater().inflate(R.menu.menu_webview, menu);
151         return true;
152     }
153
154     @Override
155     public boolean onOptionsItemSelected(MenuItem menuItem) {
156         int menuItemId = menuItem.getItemId();
157
158         // Sets the commands that relate to the menu entries.
159         switch (menuItemId) {
160             case R.id.home:
161                 formattedUrlString = homepage;
162                 urlTextBox.setText(formattedUrlString);
163                 mainWebView.loadUrl(formattedUrlString);
164                 break;
165
166             case R.id.back:
167                 mainWebView.goBack();
168
169                 // Update the URL in urlTextBox with the URL we are intending to load.  Because this can be altered during load, the final URL is loaded after the progress bar reaches 100%
170                 formattedUrlString = mainWebView.getOriginalUrl();
171                 urlTextBox.setText(formattedUrlString);
172                 break;
173
174             case R.id.forward:
175                 mainWebView.goForward();
176
177                 // Update the URL in urlTextBox with the URL we are intending to load.  Because this can be altered during load, the final URL is loaded after the progress bar reaches 100%
178                 formattedUrlString = mainWebView.getOriginalUrl();
179                 urlTextBox.setText(formattedUrlString);
180                 break;
181         }
182
183         return super.onOptionsItemSelected(menuItem);
184     }
185
186     // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
187     @Override
188     public void onBackPressed() {
189         if (mainWebView.canGoBack()) {
190             mainWebView.goBack();
191
192             // Update the URL in urlTextBox with the URL we are intending to load.  Because this can be altered during load, the final URL is loaded after the progress bar reaches 100%
193             formattedUrlString = mainWebView.getOriginalUrl();
194             urlTextBox.setText(formattedUrlString);
195         } else {
196             super.onBackPressed();
197         }
198     }
199
200     public void loadUrlFromTextBox(View view) throws UnsupportedEncodingException {
201         // Get the text from urlTextInput and convert it to a string.
202         String unformattedUrlString = urlTextBox.getText().toString();
203         URL unformattedUrl = null;
204         Uri.Builder formattedUri = new Uri.Builder();
205         String scheme;
206
207         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
208         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
209
210             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
211             if (!unformattedUrlString.startsWith("http")) {
212                 unformattedUrlString = "http://" + unformattedUrlString;
213             }
214
215             // 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.
216             try {
217                 unformattedUrl = new URL(unformattedUrlString);
218             } catch (MalformedURLException e) {
219                 e.printStackTrace();
220             }
221
222             if (unformattedUrl.getProtocol() != null) {
223                 scheme = unformattedUrl.getProtocol();
224             } else {
225                 scheme = "http";
226             }
227
228             final String authority = unformattedUrl.getAuthority();
229             final String path = unformattedUrl.getPath();
230             final String query = unformattedUrl.getQuery();
231             final String fragment = unformattedUrl.getRef();
232
233             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
234             formattedUrlString = formattedUri.build().toString();
235
236         } else {
237             // Sanitize the search input.
238             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
239             formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
240         }
241
242         // Place formattedUrlString back in the address bar and load the website.
243         urlTextBox.setText(formattedUrlString);
244         mainWebView.loadUrl(formattedUrlString);
245
246         // Hides the keyboard so we can see the webpage.
247         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
248         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
249     }
250 }