2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser.
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.
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.
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/>.
20 package com.stoutner.privacybrowser;
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.CookieManager;
45 import android.webkit.DownloadListener;
46 import android.webkit.WebChromeClient;
47 import android.webkit.WebView;
48 import android.webkit.WebViewClient;
49 import android.widget.EditText;
50 import android.widget.FrameLayout;
51 import android.widget.ImageView;
52 import android.widget.ProgressBar;
53 import android.widget.Toast;
54 import java.io.UnsupportedEncodingException;
55 import java.net.MalformedURLException;
57 import java.net.URLEncoder;
59 public class Webview extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
60 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
61 public static Bitmap favoriteIcon;
63 // mainWebView is used in onCreate and onOptionsItemSelected.
64 private WebView mainWebView;
65 // formattedUrlString is used in onCreate, onOptionsItemSelected, onCreateHomeScreenShortcutCreate, and loadUrlFromTextBox.
66 private String formattedUrlString;
67 // homepage is used in onCreate and onOptionsItemSelected.
68 private String homepage = "https://www.duckduckgo.com/";
69 // enableJavaScript is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
70 private boolean enableJavaScript;
71 // enableDomStorage is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
72 private boolean enableDomStorage;
74 /* enableSaveFormData does nothing until database storage is implemented.
75 // enableSaveFormData is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
76 private boolean enableSaveFormData;
79 // cookieManager is used in onCreate and onOptionsItemSelected.
80 private CookieManager cookieManager;
81 //enableCookies is used in onCreate, onCreateOptionsMenu, and onOptionsItemSelected.
82 private boolean enableCookies;
84 // actionBar is used in onCreate and onOptionsItemSelected.
85 private ActionBar actionBar;
87 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
88 @SuppressLint("SetJavaScriptEnabled")
91 protected void onCreate(Bundle savedInstanceState) {
92 super.onCreate(savedInstanceState);
93 setContentView(R.layout.activity_webview);
95 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
96 final Activity mainWebViewActivity = this;
98 mainWebView = (WebView) findViewById(R.id.mainWebView);
99 actionBar = getSupportActionBar();
101 if (actionBar != null) {
102 // Remove the title from the action bar.
103 actionBar.setDisplayShowTitleEnabled(false);
105 // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
106 actionBar.setCustomView(R.layout.app_bar);
107 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
109 // Set the "go" button on the keyboard to load the URL in urlTextBox.
110 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
111 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
112 public boolean onKey(View v, int keyCode, KeyEvent event) {
113 // If the event is a key-down event on the "enter" button, load the URL.
114 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
115 // Load the URL into the mainWebView and consume the event.
117 loadUrlFromTextBox();
118 } catch (UnsupportedEncodingException e) {
121 // If the enter key was pressed, consume the event.
124 // If any other key was pressed, do not consume the event.
131 mainWebView.setWebViewClient(new WebViewClient() {
132 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
134 public boolean shouldOverrideUrlLoading(WebView view, String url) {
135 mainWebView.loadUrl(url);
139 /* These errors do not provide any useful information and clutter the screen.
140 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
141 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_SHORT).show();
145 // Update the URL in urlTextBox when the page starts to load.
147 public void onPageStarted(WebView view, String url, Bitmap favicon) {
148 if (actionBar != null) {
149 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
150 urlTextBox.setText(url);
154 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
156 public void onPageFinished(WebView view, String url) {
157 formattedUrlString = url;
159 if (actionBar != null) {
160 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
161 urlTextBox.setText(formattedUrlString);
166 mainWebView.setWebChromeClient(new WebChromeClient() {
167 // Update the progress bar when a page is loading.
169 public void onProgressChanged(WebView view, int progress) {
170 // Make sure that actionBar is not null.
171 if (actionBar != null) {
172 ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
173 progressBar.setProgress(progress);
174 if (progress < 100) {
175 progressBar.setVisibility(View.VISIBLE);
177 progressBar.setVisibility(View.GONE);
182 // Set the favorite icon when it changes.
184 public void onReceivedIcon(WebView view, Bitmap icon) {
185 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
188 // Place the favorite icon in the actionBar if it is not null.
189 if (actionBar != null) {
190 ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
191 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
195 // Enter full screen video
197 public void onShowCustomView(View view, CustomViewCallback callback) {
198 if (getSupportActionBar() != null) {
199 getSupportActionBar().hide();
202 fullScreenVideoFrameLayout.addView(view);
203 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
205 mainWebView.setVisibility(View.GONE);
207 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
208 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
209 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
212 // Set the one flag supported by API >= 14.
213 if (Build.VERSION.SDK_INT >= 14) {
214 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
217 // Set the two flags that are supported by API >= 16.
218 if (Build.VERSION.SDK_INT >= 16) {
219 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
222 // Set all three flags that are supported by API >= 19.
223 if (Build.VERSION.SDK_INT >= 19) {
224 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
228 // Exit full screen video
229 public void onHideCustomView() {
230 if (getSupportActionBar() != null) {
231 getSupportActionBar().show();
234 mainWebView.setVisibility(View.VISIBLE);
236 fullScreenVideoFrameLayout.removeAllViews();
237 fullScreenVideoFrameLayout.setVisibility(View.GONE);
241 // Allow the downloading of files.
242 mainWebView.setDownloadListener(new DownloadListener() {
243 // Launch the Android download manager when a link leads to a download.
245 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
246 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
247 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
249 // Add the URL as the description for the download.
250 requestUri.setDescription(url);
252 // Show the download notification after the download is completed if the API is 11 or greater.
253 if (Build.VERSION.SDK_INT >= 11) {
254 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
257 downloadManager.enqueue(requestUri);
258 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
262 // Allow pinch to zoom.
263 mainWebView.getSettings().setBuiltInZoomControls(true);
265 // Hide zoom controls if the API is 11 or greater.
266 if (Build.VERSION.SDK_INT >= 11) {
267 mainWebView.getSettings().setDisplayZoomControls(false);
270 // Set JavaScript initial status.
271 enableJavaScript = true;
272 mainWebView.getSettings().setJavaScriptEnabled(enableJavaScript);
274 // Set DOM Storage initial status.
275 enableDomStorage = true;
276 mainWebView.getSettings().setDomStorageEnabled(enableDomStorage);
278 /* Save Form Data does nothing until database storage is implemented.
279 // Set Save Form Data initial status.
280 enableSaveFormData = true;
281 mainWebView.getSettings().setSaveFormData(enableSaveFormData);
284 // Set Cookies initial status.
285 cookieManager = CookieManager.getInstance();
286 enableCookies = true;
287 cookieManager.setAcceptCookie(enableCookies);
289 // Get the intent information that started the app.
290 final Intent intent = getIntent();
292 if (intent.getData() != null) {
293 // Get the intent data and convert it to a string.
294 final Uri intentUriData = intent.getData();
295 formattedUrlString = intentUriData.toString();
298 // If formattedUrlString is null assign the homepage to it.
299 if (formattedUrlString == null) {
300 formattedUrlString = homepage;
303 // Load the initial website.
304 mainWebView.loadUrl(formattedUrlString);
308 public boolean onCreateOptionsMenu(Menu menu) {
309 // Inflate the menu; this adds items to the action bar if it is present.
310 getMenuInflater().inflate(R.menu.menu_webview, menu);
312 // Get MenuItems for checkable menu items.
313 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
314 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
315 /* toggleSaveFormData does nothing until database storage is implemented.
316 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
318 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
319 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
321 // Set the initial status of the menu item checkboxes.
322 toggleJavaScript.setChecked(enableJavaScript);
323 toggleDomStorage.setChecked(enableDomStorage);
324 /* toggleSaveFormData does nothing until database storage is implemented.
325 toggleSaveFormData.setChecked(enableSaveFormData);
327 toggleCookies.setChecked(enableCookies);
329 // Disable Clear Cookies if there are none.
330 clearCookies.setEnabled(cookieManager.hasCookies());
336 public boolean onPrepareOptionsMenu(Menu menu) {
337 // Enable Clear Cookies if there are any.
338 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
339 clearCookies.setEnabled(cookieManager.hasCookies());
341 // Run all the other default commands.
342 super.onPrepareOptionsMenu(menu);
344 // Return true displays the menu.
349 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
351 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
352 @SuppressLint("SetJavaScriptEnabled")
353 public boolean onOptionsItemSelected(MenuItem menuItem) {
354 int menuItemId = menuItem.getItemId();
355 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
357 // Sets the commands that relate to the menu entries.
358 switch (menuItemId) {
359 case R.id.toggleJavaScript:
360 if (enableJavaScript) {
361 enableJavaScript = false;
362 menuItem.setChecked(false);
363 mainWebView.getSettings().setJavaScriptEnabled(false);
364 mainWebView.reload();
366 enableJavaScript = true;
367 menuItem.setChecked(true);
368 mainWebView.getSettings().setJavaScriptEnabled(true);
369 mainWebView.reload();
373 case R.id.toggleDomStorage:
374 if (enableDomStorage) {
375 enableDomStorage = false;
376 menuItem.setChecked(false);
377 mainWebView.getSettings().setDomStorageEnabled(false);
378 mainWebView.reload();
380 enableDomStorage = true;
381 menuItem.setChecked(true);
382 mainWebView.getSettings().setDomStorageEnabled(true);
383 mainWebView.reload();
387 /* toggleSaveFormData does nothing until database storage is implemented.
388 case R.id.toggleSaveFormData:
389 if (enableSaveFormData) {
390 enableSaveFormData = false;
391 menuItem.setChecked(false);
392 mainWebView.getSettings().setSaveFormData(false);
393 mainWebView.reload();
395 enableSaveFormData = true;
396 menuItem.setChecked(true);
397 mainWebView.getSettings().setSaveFormData(true);
398 mainWebView.reload();
403 case R.id.toggleCookies:
405 enableCookies = false;
406 menuItem.setChecked(false);
407 cookieManager.setAcceptCookie(false);
408 mainWebView.reload();
410 enableCookies = true;
411 menuItem.setChecked(true);
412 cookieManager.setAcceptCookie(true);
413 mainWebView.reload();
417 case R.id.clearCookies:
418 if (Build.VERSION.SDK_INT < 21) {
419 cookieManager.removeAllCookie();
421 cookieManager.removeAllCookies(null);
423 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
427 mainWebView.loadUrl(homepage);
431 mainWebView.reload();
435 mainWebView.goBack();
439 mainWebView.goForward();
443 // Make sure that actionBar is not null.
444 if (actionBar != null) {
445 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
446 clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
451 // Make sure that actionBar is not null.
452 if (actionBar != null) {
453 ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
454 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
455 urlTextBox.setText(clipboardData.coerceToText(this));
457 loadUrlFromTextBox();
458 } catch (UnsupportedEncodingException e) {
465 // Make sure that actionBar is not null.
466 if (actionBar != null) {
467 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
468 Intent shareIntent = new Intent();
469 shareIntent.setAction(Intent.ACTION_SEND);
470 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
471 shareIntent.setType("text/plain");
472 startActivity(Intent.createChooser(shareIntent, "Share URL"));
476 case R.id.addToHomescreen:
477 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
478 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
479 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
481 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
485 // Launch the system Download Manager.
486 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
488 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
489 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
491 startActivity(downloadManangerIntent);
495 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
496 AppCompatDialogFragment aboutDialog = new AboutDialog();
497 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
501 return super.onOptionsItemSelected(menuItem);
506 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
507 // Do nothing because the user selected "Cancel".
511 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
512 // Get shortcutNameEditText from the alert dialog.
513 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
515 // Create the bookmark shortcut based on formattedUrlString.
516 Intent bookmarkShortcut = new Intent();
517 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
518 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
520 // Place the bookmark shortcut on the home screen.
521 Intent placeBookmarkShortcut = new Intent();
522 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
523 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
524 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
525 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
526 sendBroadcast(placeBookmarkShortcut);
529 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
531 public void onBackPressed() {
532 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
534 if (mainWebView.canGoBack()) {
535 mainWebView.goBack();
537 super.onBackPressed();
541 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
542 // Make sure that actionBar is not null.
543 ActionBar actionBar = getSupportActionBar();
544 if (actionBar != null) {
545 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
546 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
548 // Get the text from urlTextInput and convert it to a string.
549 String unformattedUrlString = urlTextBox.getText().toString();
550 URL unformattedUrl = null;
551 Uri.Builder formattedUri = new Uri.Builder();
553 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
554 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
556 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
557 if (!unformattedUrlString.startsWith("http")) {
558 unformattedUrlString = "http://" + unformattedUrlString;
561 // 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.
563 unformattedUrl = new URL(unformattedUrlString);
564 } catch (MalformedURLException e) {
568 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
569 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
570 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
571 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
572 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
573 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
575 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
576 formattedUrlString = formattedUri.build().toString();
579 // Sanitize the search input and convert it to a DuckDuckGo search.
580 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
581 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
584 mainWebView.loadUrl(formattedUrlString);
586 // Hides the keyboard so we can see the webpage.
587 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
588 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);