]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/Webview.java
70315bf8197f210229b7c7e0a71dfdf89bdae943
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / Webview.java
1 package com.stoutner.privacybrowser;
2
3 import android.annotation.SuppressLint;
4 import android.annotation.TargetApi;
5 import android.app.Activity;
6 import android.app.DownloadManager;
7 import android.content.ClipData;
8 import android.content.ClipboardManager;
9 import android.content.Context;
10 import android.content.Intent;
11 import android.graphics.Bitmap;
12 import android.net.Uri;
13 import android.os.Build;
14 import android.os.Bundle;
15 import android.support.v7.app.ActionBar;
16 import android.support.v7.app.AppCompatActivity;
17 import android.util.Patterns;
18 import android.view.KeyEvent;
19 import android.view.Menu;
20 import android.view.MenuItem;
21 import android.view.View;
22 import android.view.inputmethod.InputMethodManager;
23 import android.webkit.DownloadListener;
24 import android.webkit.WebChromeClient;
25 import android.webkit.WebResourceError;
26 import android.webkit.WebResourceRequest;
27 import android.webkit.WebView;
28 import android.webkit.WebViewClient;
29 import android.widget.EditText;
30 import android.widget.ImageView;
31 import android.widget.ProgressBar;
32 import android.widget.Toast;
33 import java.io.UnsupportedEncodingException;
34 import java.net.MalformedURLException;
35 import java.net.URL;
36 import java.net.URLEncoder;
37
38 public class Webview extends AppCompatActivity {
39
40     private String formattedUrlString;
41     private String homepage = "https://www.duckduckgo.com/";
42
43     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
44     @SuppressLint("SetJavaScriptEnabled")
45
46     @Override
47     protected void onCreate(Bundle savedInstanceState) {
48         super.onCreate(savedInstanceState);
49         setContentView(R.layout.activity_webview);
50
51         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
52         final Activity mainWebViewActivity = this;
53
54         final ActionBar actionBar = getSupportActionBar();
55         if (actionBar != null) {
56             // Remove the title from the action bar.
57             actionBar.setDisplayShowTitleEnabled(false);
58
59             // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
60             actionBar.setCustomView(R.layout.app_bar);
61             actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
62
63             // Set the "go" button on the keyboard to load the URL in urlTextBox.
64             EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
65             urlTextBox.setOnKeyListener(new View.OnKeyListener() {
66                 public boolean onKey(View v, int keyCode, KeyEvent event) {
67                     // If the event is a key-down event on the "enter" button, load the URL.
68                     if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
69                             (keyCode == KeyEvent.KEYCODE_ENTER)) {
70                         // Load the URL into the mainWebView and consume the event.
71                         try {
72                             loadUrlFromTextBox();
73                         } catch (UnsupportedEncodingException e) {
74                             e.printStackTrace();
75                         }
76                         // If the enter key was pressed, consume the event.
77                         return true;
78                     }
79                     // If any other key was pressed, do not consume the event.
80                     return false;
81                 }
82             });
83         }
84
85         mainWebView.setWebViewClient(new WebViewClient() {
86             // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
87             @Override
88             public boolean shouldOverrideUrlLoading(WebView view, String url) {
89                 mainWebView.loadUrl(url);
90                 return true;
91             }
92
93             public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
94                 Toast.makeText(mainWebViewActivity, "Error loading " + request + "   Error: " + error, Toast.LENGTH_LONG).show();
95             }
96
97             // Update the URL in urlTextBox when the page starts to load.
98             @Override
99             public void onPageStarted(WebView view, String url, Bitmap favicon) {
100                 if (actionBar != null) {
101                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
102                     urlTextBox.setText(url);
103                 }
104             }
105
106             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
107             @Override
108             public void onPageFinished(WebView view, String url) {
109                 formattedUrlString = url;
110
111                 if (actionBar != null) {
112                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
113                     urlTextBox.setText(formattedUrlString);
114                 }
115             }
116         });
117
118         mainWebView.setWebChromeClient(new WebChromeClient() {
119             // Update the progress bar when a page is loading.
120             @Override
121             public void onProgressChanged(WebView view, int progress) {
122                 // Make sure that actionBar is not null.
123                 if (actionBar != null) {
124                     ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
125                     progressBar.setProgress(progress);
126                     if (progress < 100) {
127                         progressBar.setVisibility(View.VISIBLE);
128                     } else {
129                         progressBar.setVisibility(View.GONE);
130                     }
131                 }
132             }
133
134             // Set the favorite icon when it changes.
135             @Override
136             public void onReceivedIcon(WebView view, Bitmap icon) {
137                 // Make sure that actionBar is not null.
138                 if (actionBar != null) {
139                     ImageView favoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
140                     favoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
141                 }
142             }
143         });
144
145         mainWebView.setDownloadListener(new DownloadListener() {
146             // Launch the Android download manager when a link leads to a download.
147             @Override
148             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
149                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
150                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
151
152                 // Add the URL as the description for the download.
153                 requestUri.setDescription(url);
154
155                 // Show the download notification after the download is completed if the API is 11 or greater.
156                 if (Build.VERSION.SDK_INT >= 11) {
157                     requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
158                 }
159
160                 downloadManager.enqueue(requestUri);
161                 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
162             }
163         });
164
165         // Allow pinch to zoom.
166         mainWebView.getSettings().setBuiltInZoomControls(true);
167
168         // Hide zoom controls if the API is 11 or greater.
169         if (Build.VERSION.SDK_INT >= 11) {
170             mainWebView.getSettings().setDisplayZoomControls(false);
171         }
172
173         // Enable JavaScript.
174         mainWebView.getSettings().setJavaScriptEnabled(true);
175
176         // Enable DOM Storage.
177         mainWebView.getSettings().setDomStorageEnabled(true);
178
179         // Get the intent information that started the app.
180         final Intent intent = getIntent();
181
182         if (intent.getData() != null) {
183             // Get the intent data and convert it to a string.
184             final Uri intentUriData = intent.getData();
185             formattedUrlString = intentUriData.toString();
186         }
187
188         // If formattedUrlString is null assign the homepage to it.
189         if (formattedUrlString == null) {
190             formattedUrlString = homepage;
191         }
192
193         // Load the initial website.
194         mainWebView.loadUrl(formattedUrlString);
195     }
196
197     @Override
198     public boolean onCreateOptionsMenu(Menu menu) {
199         // Inflate the menu; this adds items to the action bar if it is present.
200         getMenuInflater().inflate(R.menu.menu_webview, menu);
201         return true;
202     }
203
204     // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
205     @Override
206     @TargetApi(11)
207     public boolean onOptionsItemSelected(MenuItem menuItem) {
208         int menuItemId = menuItem.getItemId();
209         ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
210         ActionBar actionBar = getSupportActionBar();
211         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
212
213         // Sets the commands that relate to the menu entries.
214         switch (menuItemId) {
215             case R.id.home:
216                 mainWebView.loadUrl(homepage);
217                 break;
218
219             case R.id.refresh:
220                 mainWebView.loadUrl(formattedUrlString);
221                 break;
222
223             case R.id.back:
224                 mainWebView.goBack();
225                 break;
226
227             case R.id.forward:
228                 mainWebView.goForward();
229                 break;
230
231             case R.id.copyURL:
232                 // Make sure that actionBar is not null.
233                 if (actionBar != null) {
234                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
235                     clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
236                 }
237                 break;
238
239             case R.id.pasteURL:
240                 // Make sure that actionBar is not null.
241                 if (actionBar != null) {
242                     ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
243                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
244                     urlTextBox.setText(clipboardData.coerceToText(this));
245                     try {
246                         loadUrlFromTextBox();
247                     } catch (UnsupportedEncodingException e) {
248                         e.printStackTrace();
249                     }
250                 }
251                 break;
252
253             case R.id.shareURL:
254                 // Make sure that actionBar is not null.
255                 if (actionBar != null) {
256                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
257                     Intent shareIntent = new Intent();
258                     shareIntent.setAction(Intent.ACTION_SEND);
259                     shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
260                     shareIntent.setType("text/plain");
261                     startActivity(Intent.createChooser(shareIntent, "Share URL"));
262                 }
263                 break;
264
265             case R.id.downloads:
266                 // Launch the system Download Manager.
267                 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
268
269                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
270                 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
271
272                 startActivity(downloadManangerIntent);
273         }
274
275         return super.onOptionsItemSelected(menuItem);
276     }
277
278     // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
279     @Override
280     public void onBackPressed() {
281         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
282
283         if (mainWebView.canGoBack()) {
284             mainWebView.goBack();
285         } else {
286             super.onBackPressed();
287         }
288     }
289
290     public void loadUrlFromTextBox() throws UnsupportedEncodingException {
291         // Make sure that actionBar is not null.
292         ActionBar actionBar = getSupportActionBar();
293         if (actionBar != null) {
294             final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
295             EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
296
297             // Get the text from urlTextInput and convert it to a string.
298             String unformattedUrlString = urlTextBox.getText().toString();
299             URL unformattedUrl = null;
300             Uri.Builder formattedUri = new Uri.Builder();
301
302             // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
303             if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
304
305                 // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
306                 if (!unformattedUrlString.startsWith("http")) {
307                     unformattedUrlString = "http://" + unformattedUrlString;
308                 }
309
310                 // 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.
311                 try {
312                     unformattedUrl = new URL(unformattedUrlString);
313                 } catch (MalformedURLException e) {
314                     e.printStackTrace();
315                 }
316
317                 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
318                 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
319                 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
320                 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
321                 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
322                 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
323
324                 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
325                 formattedUrlString = formattedUri.build().toString();
326
327             } else {
328                 // Sanitize the search input and convert it to a DuckDuckGo search.
329                 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
330                 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
331             }
332
333             mainWebView.loadUrl(formattedUrlString);
334
335             // Hides the keyboard so we can see the webpage.
336             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
337             inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
338         }
339     }
340 }