]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/Webview.java
Add copyright and GPLv3+ licensing information. Create an About AlertDialog.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / Webview.java
1 /**
2  * Copyright 2015 Soren Stoutner
3  *
4  * This file is part of Privacy Browser.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser;
21
22 import android.annotation.SuppressLint;
23 import android.annotation.TargetApi;
24 import android.app.Activity;
25 import android.app.DownloadManager;
26 import android.content.ClipData;
27 import android.content.ClipboardManager;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.graphics.Bitmap;
31 import android.net.Uri;
32 import android.os.Build;
33 import android.os.Bundle;
34 import android.support.v4.app.DialogFragment;
35 import android.support.v7.app.ActionBar;
36 import android.support.v7.app.AppCompatActivity;
37 import android.support.v7.app.AppCompatDialogFragment;
38 import android.util.Patterns;
39 import android.view.KeyEvent;
40 import android.view.Menu;
41 import android.view.MenuItem;
42 import android.view.View;
43 import android.view.inputmethod.InputMethodManager;
44 import android.webkit.DownloadListener;
45 import android.webkit.WebChromeClient;
46 import android.webkit.WebResourceError;
47 import android.webkit.WebResourceRequest;
48 import android.webkit.WebView;
49 import android.webkit.WebViewClient;
50 import android.widget.EditText;
51 import android.widget.FrameLayout;
52 import android.widget.ImageView;
53 import android.widget.ProgressBar;
54 import android.widget.Toast;
55 import java.io.UnsupportedEncodingException;
56 import java.net.MalformedURLException;
57 import java.net.URL;
58 import java.net.URLEncoder;
59
60 public class Webview extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
61     // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
62     public static Bitmap favoriteIcon;
63
64     private String formattedUrlString;
65     private String homepage = "https://www.duckduckgo.com/";
66
67     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
68     @SuppressLint("SetJavaScriptEnabled")
69
70     @Override
71     protected void onCreate(Bundle savedInstanceState) {
72         super.onCreate(savedInstanceState);
73         setContentView(R.layout.activity_webview);
74
75         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
76         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
77         final Activity mainWebViewActivity = this;
78
79         final ActionBar actionBar = getSupportActionBar();
80         if (actionBar != null) {
81             // Remove the title from the action bar.
82             actionBar.setDisplayShowTitleEnabled(false);
83
84             // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
85             actionBar.setCustomView(R.layout.app_bar);
86             actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
87
88             // Set the "go" button on the keyboard to load the URL in urlTextBox.
89             EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
90             urlTextBox.setOnKeyListener(new View.OnKeyListener() {
91                 public boolean onKey(View v, int keyCode, KeyEvent event) {
92                     // If the event is a key-down event on the "enter" button, load the URL.
93                     if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
94                         // Load the URL into the mainWebView and consume the event.
95                         try {
96                             loadUrlFromTextBox();
97                         } catch (UnsupportedEncodingException e) {
98                             e.printStackTrace();
99                         }
100                         // If the enter key was pressed, consume the event.
101                         return true;
102                     } else {
103                         // If any other key was pressed, do not consume the event.
104                         return false;
105                     }
106                 }
107             });
108         }
109
110         mainWebView.setWebViewClient(new WebViewClient() {
111             // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
112             @Override
113             public boolean shouldOverrideUrlLoading(WebView view, String url) {
114                 mainWebView.loadUrl(url);
115                 return true;
116             }
117
118             public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
119                 Toast.makeText(mainWebViewActivity, "Error loading " + request + "   Error: " + error, Toast.LENGTH_LONG).show();
120             }
121
122             // Update the URL in urlTextBox when the page starts to load.
123             @Override
124             public void onPageStarted(WebView view, String url, Bitmap favicon) {
125                 if (actionBar != null) {
126                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
127                     urlTextBox.setText(url);
128                 }
129             }
130
131             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
132             @Override
133             public void onPageFinished(WebView view, String url) {
134                 formattedUrlString = url;
135
136                 if (actionBar != null) {
137                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
138                     urlTextBox.setText(formattedUrlString);
139                 }
140             }
141         });
142
143         mainWebView.setWebChromeClient(new WebChromeClient() {
144             // Update the progress bar when a page is loading.
145             @Override
146             public void onProgressChanged(WebView view, int progress) {
147                 // Make sure that actionBar is not null.
148                 if (actionBar != null) {
149                     ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
150                     progressBar.setProgress(progress);
151                     if (progress < 100) {
152                         progressBar.setVisibility(View.VISIBLE);
153                     } else {
154                         progressBar.setVisibility(View.GONE);
155                     }
156                 }
157             }
158
159             // Set the favorite icon when it changes.
160             @Override
161             public void onReceivedIcon(WebView view, Bitmap icon) {
162                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
163                 favoriteIcon = icon;
164
165                 // Place the favorite icon in the actionBar if it is not null.
166                 if (actionBar != null) {
167                     ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
168                     imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
169                 }
170             }
171
172             // Enter full screen video
173             @Override
174             public void onShowCustomView(View view, CustomViewCallback callback) {
175                 getSupportActionBar().hide();
176
177                 fullScreenVideoFrameLayout.addView(view);
178                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
179
180                 mainWebView.setVisibility(View.GONE);
181
182                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
183                 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
184                 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
185                 */
186
187                 // Set the one flag supported by API >= 14.
188                 if (Build.VERSION.SDK_INT >= 14) {
189                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
190                 }
191
192                 // Set the two flags that are supported by API >= 16.
193                 if (Build.VERSION.SDK_INT >= 16) {
194                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
195                 }
196
197                 // Set all three flags that are supported by API >= 19.
198                 if (Build.VERSION.SDK_INT >= 19) {
199                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
200                 }
201             }
202
203             // Exit full screen video
204             public void onHideCustomView() {
205                 getSupportActionBar().show();
206
207                 mainWebView.setVisibility(View.VISIBLE);
208
209                 fullScreenVideoFrameLayout.removeAllViews();
210                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
211             }
212         });
213
214         mainWebView.setDownloadListener(new DownloadListener() {
215             // Launch the Android download manager when a link leads to a download.
216             @Override
217             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
218                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
219                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
220
221                 // Add the URL as the description for the download.
222                 requestUri.setDescription(url);
223
224                 // Show the download notification after the download is completed if the API is 11 or greater.
225                 if (Build.VERSION.SDK_INT >= 11) {
226                     requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
227                 }
228
229                 downloadManager.enqueue(requestUri);
230                 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
231             }
232         });
233
234         // Allow pinch to zoom.
235         mainWebView.getSettings().setBuiltInZoomControls(true);
236
237         // Hide zoom controls if the API is 11 or greater.
238         if (Build.VERSION.SDK_INT >= 11) {
239             mainWebView.getSettings().setDisplayZoomControls(false);
240         }
241
242         // Enable JavaScript.
243         mainWebView.getSettings().setJavaScriptEnabled(true);
244
245         // Enable DOM Storage.
246         mainWebView.getSettings().setDomStorageEnabled(true);
247
248         // Get the intent information that started the app.
249         final Intent intent = getIntent();
250
251         if (intent.getData() != null) {
252             // Get the intent data and convert it to a string.
253             final Uri intentUriData = intent.getData();
254             formattedUrlString = intentUriData.toString();
255         }
256
257         // If formattedUrlString is null assign the homepage to it.
258         if (formattedUrlString == null) {
259             formattedUrlString = homepage;
260         }
261
262         // Load the initial website.
263         mainWebView.loadUrl(formattedUrlString);
264     }
265
266     @Override
267     public boolean onCreateOptionsMenu(Menu menu) {
268         // Inflate the menu; this adds items to the action bar if it is present.
269         getMenuInflater().inflate(R.menu.menu_webview, menu);
270         return true;
271     }
272
273     // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
274     @Override
275     @TargetApi(11)
276     public boolean onOptionsItemSelected(MenuItem menuItem) {
277         int menuItemId = menuItem.getItemId();
278         ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
279         ActionBar actionBar = getSupportActionBar();
280         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
281
282         // Sets the commands that relate to the menu entries.
283         switch (menuItemId) {
284             case R.id.home:
285                 mainWebView.loadUrl(homepage);
286                 break;
287
288             case R.id.refresh:
289                 mainWebView.loadUrl(formattedUrlString);
290                 break;
291
292             case R.id.back:
293                 mainWebView.goBack();
294                 break;
295
296             case R.id.forward:
297                 mainWebView.goForward();
298                 break;
299
300             case R.id.copyURL:
301                 // Make sure that actionBar is not null.
302                 if (actionBar != null) {
303                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
304                     clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
305                 }
306                 break;
307
308             case R.id.pasteURL:
309                 // Make sure that actionBar is not null.
310                 if (actionBar != null) {
311                     ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
312                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
313                     urlTextBox.setText(clipboardData.coerceToText(this));
314                     try {
315                         loadUrlFromTextBox();
316                     } catch (UnsupportedEncodingException e) {
317                         e.printStackTrace();
318                     }
319                 }
320                 break;
321
322             case R.id.shareURL:
323                 // Make sure that actionBar is not null.
324                 if (actionBar != null) {
325                     EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
326                     Intent shareIntent = new Intent();
327                     shareIntent.setAction(Intent.ACTION_SEND);
328                     shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
329                     shareIntent.setType("text/plain");
330                     startActivity(Intent.createChooser(shareIntent, "Share URL"));
331                 }
332                 break;
333
334             case R.id.addToHomescreen:
335                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
336                 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
337                 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
338
339                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
340                 break;
341
342             case R.id.downloads:
343                 // Launch the system Download Manager.
344                 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
345
346                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
347                 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
348
349                 startActivity(downloadManangerIntent);
350                 break;
351
352             case R.id.about:
353                 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
354                 AppCompatDialogFragment aboutDialog = new AboutDialog();
355                 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
356
357                 break;
358         }
359
360         return super.onOptionsItemSelected(menuItem);
361     }
362
363     @Override
364     public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
365         // Do nothing because the user selected "Cancel".
366     }
367
368     @Override
369     public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
370         // Get shortcutNameEditText from the alert dialog.
371         EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
372
373         // Create the bookmark shortcut based on formattedUrlString.
374         Intent bookmarkShortcut = new Intent();
375         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
376         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
377
378         // Place the bookmark shortcut on the home screen.
379         Intent placeBookmarkShortcut = new Intent();
380         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
381         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
382         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
383         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
384         sendBroadcast(placeBookmarkShortcut);
385     }
386
387     // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
388     @Override
389     public void onBackPressed() {
390         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
391
392         if (mainWebView.canGoBack()) {
393             mainWebView.goBack();
394         } else {
395             super.onBackPressed();
396         }
397     }
398
399     public void loadUrlFromTextBox() throws UnsupportedEncodingException {
400         // Make sure that actionBar is not null.
401         ActionBar actionBar = getSupportActionBar();
402         if (actionBar != null) {
403             final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
404             EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
405
406             // Get the text from urlTextInput and convert it to a string.
407             String unformattedUrlString = urlTextBox.getText().toString();
408             URL unformattedUrl = null;
409             Uri.Builder formattedUri = new Uri.Builder();
410
411             // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
412             if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
413
414                 // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
415                 if (!unformattedUrlString.startsWith("http")) {
416                     unformattedUrlString = "http://" + unformattedUrlString;
417                 }
418
419                 // 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.
420                 try {
421                     unformattedUrl = new URL(unformattedUrlString);
422                 } catch (MalformedURLException e) {
423                     e.printStackTrace();
424                 }
425
426                 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
427                 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
428                 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
429                 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
430                 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
431                 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
432
433                 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
434                 formattedUrlString = formattedUri.build().toString();
435
436             } else {
437                 // Sanitize the search input and convert it to a DuckDuckGo search.
438                 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
439                 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
440             }
441
442             mainWebView.loadUrl(formattedUrlString);
443
444             // Hides the keyboard so we can see the webpage.
445             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
446             inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
447         }
448     }
449 }