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