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.WebStorage;
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;
58 import java.net.URLEncoder;
60 public class MainWebView extends AppCompatActivity implements CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
61 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut.
62 public static Bitmap favoriteIcon;
63 // mainWebView is public static so it can be accessed from AboutDialog. It is also used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
64 public static WebView mainWebView;
66 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
67 private String formattedUrlString;
68 // homepage is used in onCreate() and onOptionsItemSelected().
69 private String homepage = "https://www.duckduckgo.com/";
70 // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
71 private boolean javaScriptEnabled;
72 // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
73 private boolean domStorageEnabled;
75 /* saveFormDataEnabled does nothing until database storage is implemented.
76 // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
77 private boolean saveFormDataEnabled;
80 // cookieManager is used in onCreate() and onOptionsItemSelected().
81 private CookieManager cookieManager;
82 // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
83 private boolean cookiesEnabled;
85 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
86 private EditText urlTextBox;
89 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
90 @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;
97 final ActionBar actionBar = getSupportActionBar();
99 mainWebView = (WebView) findViewById(R.id.mainWebView);
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 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 urlTextBox.setText(url);
151 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
153 public void onPageFinished(WebView view, String url) {
154 formattedUrlString = url;
155 urlTextBox.setText(formattedUrlString);
159 mainWebView.setWebChromeClient(new WebChromeClient() {
160 // Update the progress bar when a page is loading.
162 public void onProgressChanged(WebView view, int progress) {
163 // Make sure that actionBar is not null.
164 if (actionBar != null) {
165 ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
166 progressBar.setProgress(progress);
167 if (progress < 100) {
168 progressBar.setVisibility(View.VISIBLE);
170 progressBar.setVisibility(View.GONE);
175 // Set the favorite icon when it changes.
177 public void onReceivedIcon(WebView view, Bitmap icon) {
178 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
181 // Place the favorite icon in the actionBar if it is not null.
182 if (actionBar != null) {
183 ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
184 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
188 // Enter full screen video
190 public void onShowCustomView(View view, CustomViewCallback callback) {
191 if (actionBar != null) {
195 fullScreenVideoFrameLayout.addView(view);
196 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
198 mainWebView.setVisibility(View.GONE);
200 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
201 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
202 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
205 // Set the one flag supported by API >= 14.
206 if (Build.VERSION.SDK_INT >= 14) {
207 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
210 // Set the two flags that are supported by API >= 16.
211 if (Build.VERSION.SDK_INT >= 16) {
212 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
215 // Set all three flags that are supported by API >= 19.
216 if (Build.VERSION.SDK_INT >= 19) {
217 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
221 // Exit full screen video
222 public void onHideCustomView() {
223 if (actionBar != null) {
227 mainWebView.setVisibility(View.VISIBLE);
229 fullScreenVideoFrameLayout.removeAllViews();
230 fullScreenVideoFrameLayout.setVisibility(View.GONE);
234 // Allow the downloading of files.
235 mainWebView.setDownloadListener(new DownloadListener() {
236 // Launch the Android download manager when a link leads to a download.
238 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
239 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
240 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
242 // Add the URL as the description for the download.
243 requestUri.setDescription(url);
245 // Show the download notification after the download is completed if the API is 11 or greater.
246 if (Build.VERSION.SDK_INT >= 11) {
247 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
250 downloadManager.enqueue(requestUri);
251 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
255 // Allow pinch to zoom.
256 mainWebView.getSettings().setBuiltInZoomControls(true);
258 // Hide zoom controls if the API is 11 or greater.
259 if (Build.VERSION.SDK_INT >= 11) {
260 mainWebView.getSettings().setDisplayZoomControls(false);
263 // Set JavaScript initial status.
264 javaScriptEnabled = false;
265 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
267 // Set DOM Storage initial status.
268 domStorageEnabled = false;
269 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
271 /* Save Form Data does nothing until database storage is implemented.
272 // Set Save Form Data initial status.
273 saveFormDataEnabled = true;
274 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
277 // Set Cookies initial status.
278 cookiesEnabled = false;
279 cookieManager = CookieManager.getInstance();
280 cookieManager.setAcceptCookie(cookiesEnabled);
282 // Get the intent information that started the app.
283 final Intent intent = getIntent();
285 if (intent.getData() != null) {
286 // Get the intent data and convert it to a string.
287 final Uri intentUriData = intent.getData();
288 formattedUrlString = intentUriData.toString();
291 // If formattedUrlString is null assign the homepage to it.
292 if (formattedUrlString == null) {
293 formattedUrlString = homepage;
296 // Load the initial website.
297 mainWebView.loadUrl(formattedUrlString);
301 protected void onNewIntent(Intent intent) {
302 // Sets the new intent as the activity intent, so that any future getIntent() picks up this one.
305 if (intent.getData() != null) {
306 // Get the intent data and convert it to a string.
307 final Uri intentUriData = intent.getData();
308 formattedUrlString = intentUriData.toString();
312 mainWebView.loadUrl(formattedUrlString);
316 public boolean onCreateOptionsMenu(Menu menu) {
317 // Inflate the menu; this adds items to the action bar if it is present.
318 getMenuInflater().inflate(R.menu.menu_webview, menu);
320 // Get MenuItems for checkable menu items.
321 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
322 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
323 /* toggleSaveFormData does nothing until database storage is implemented.
324 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
326 MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
328 // Set the initial icon for toggleJavaScript
329 if (javaScriptEnabled) {
330 toggleJavaScript.setIcon(R.drawable.javascript_on);
332 toggleJavaScript.setIcon(R.drawable.javascript_off);
335 // Set the initial status of the menu item checkboxes.
336 toggleDomStorage.setChecked(domStorageEnabled);
337 /* toggleSaveFormData does nothing until database storage is implemented.
338 toggleSaveFormData.setChecked(saveFormDataEnabled);
340 toggleCookies.setChecked(cookiesEnabled);
346 public boolean onPrepareOptionsMenu(Menu menu) {
347 // Enable Clear Cookies if there are any.
348 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
349 clearCookies.setEnabled(cookieManager.hasCookies());
351 // Enable Back if canGoBack().
352 MenuItem back = menu.findItem(R.id.back);
353 back.setEnabled(mainWebView.canGoBack());
355 // Enable forward if canGoForward().
356 MenuItem forward = menu.findItem(R.id.forward);
357 forward.setEnabled(mainWebView.canGoForward());
359 // Run all the other default commands.
360 super.onPrepareOptionsMenu(menu);
362 // return true displays the menu.
367 // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
369 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
370 @SuppressLint("SetJavaScriptEnabled")
371 // removeAllCookies is deprecated, but it is required for API < 21.
372 @SuppressWarnings("deprecation")
373 public boolean onOptionsItemSelected(MenuItem menuItem) {
374 int menuItemId = menuItem.getItemId();
375 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
377 // Sets the commands that relate to the menu entries.
378 switch (menuItemId) {
379 case R.id.toggleJavaScript:
380 if (javaScriptEnabled) {
381 javaScriptEnabled = false;
382 menuItem.setIcon(R.drawable.javascript_off);
383 mainWebView.getSettings().setJavaScriptEnabled(false);
384 mainWebView.reload();
385 Toast.makeText(getApplicationContext(), "JavaScript Disabled", Toast.LENGTH_SHORT).show();
387 javaScriptEnabled = true;
388 menuItem.setIcon(R.drawable.javascript_on);
389 mainWebView.getSettings().setJavaScriptEnabled(true);
390 mainWebView.reload();
391 Toast.makeText(getApplicationContext(), "JavaScript Enabled", Toast.LENGTH_SHORT).show();
395 case R.id.toggleDomStorage:
396 if (domStorageEnabled) {
397 domStorageEnabled = false;
398 menuItem.setChecked(false);
399 mainWebView.getSettings().setDomStorageEnabled(false);
400 mainWebView.reload();
402 domStorageEnabled = true;
403 menuItem.setChecked(true);
404 mainWebView.getSettings().setDomStorageEnabled(true);
405 mainWebView.reload();
409 /* toggleSaveFormData does nothing until database storage is implemented.
410 case R.id.toggleSaveFormData:
411 if (saveFormDataEnabled) {
412 saveFormDataEnabled = false;
413 menuItem.setChecked(false);
414 mainWebView.getSettings().setSaveFormData(false);
415 mainWebView.reload();
417 saveFormDataEnabled = true;
418 menuItem.setChecked(true);
419 mainWebView.getSettings().setSaveFormData(true);
420 mainWebView.reload();
425 case R.id.toggleCookies:
426 if (cookiesEnabled) {
427 cookiesEnabled = false;
428 menuItem.setChecked(false);
429 cookieManager.setAcceptCookie(false);
430 mainWebView.reload();
432 cookiesEnabled = true;
433 menuItem.setChecked(true);
434 cookieManager.setAcceptCookie(true);
435 mainWebView.reload();
439 case R.id.clearDomStorage:
440 WebStorage webStorage = WebStorage.getInstance();
441 webStorage.deleteAllData();
442 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
445 case R.id.clearCookies:
446 if (Build.VERSION.SDK_INT < 21) {
447 cookieManager.removeAllCookie();
449 cookieManager.removeAllCookies(null);
451 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
455 mainWebView.loadUrl(homepage);
459 mainWebView.reload();
463 mainWebView.goBack();
467 mainWebView.goForward();
471 clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
475 ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
476 urlTextBox.setText(clipboardData.coerceToText(this));
478 loadUrlFromTextBox();
479 } catch (UnsupportedEncodingException e) {
485 Intent shareIntent = new Intent();
486 shareIntent.setAction(Intent.ACTION_SEND);
487 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
488 shareIntent.setType("text/plain");
489 startActivity(Intent.createChooser(shareIntent, "Share URL"));
492 case R.id.addToHomescreen:
493 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
494 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
495 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
497 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
501 // Launch the system Download Manager.
502 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
504 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
505 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
507 startActivity(downloadManangerIntent);
511 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
512 AppCompatDialogFragment aboutDialog = new AboutDialog();
513 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
516 case R.id.clearAndExit:
517 // Clear DOM storage.
518 WebStorage domStorage = WebStorage.getInstance();
519 domStorage.deleteAllData();
522 if (Build.VERSION.SDK_INT < 21) {
523 cookieManager.removeAllCookie();
525 cookieManager.removeAllCookies(null);
528 // Destroy the internal state of the webview.
529 mainWebView.destroy();
531 // Close Privacy Browser.
536 return super.onOptionsItemSelected(menuItem);
541 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
542 // Do nothing because the user selected "Cancel".
546 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
547 // Get shortcutNameEditText from the alert dialog.
548 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
550 // Create the bookmark shortcut based on formattedUrlString.
551 Intent bookmarkShortcut = new Intent();
552 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
553 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
555 // Place the bookmark shortcut on the home screen.
556 Intent placeBookmarkShortcut = new Intent();
557 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
558 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
559 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
560 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
561 sendBroadcast(placeBookmarkShortcut);
564 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
566 public void onBackPressed() {
567 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
569 if (mainWebView.canGoBack()) {
570 mainWebView.goBack();
572 super.onBackPressed();
576 public void loadUrlFromTextBox() throws UnsupportedEncodingException {
577 // Get the text from urlTextBox and convert it to a string.
578 String unformattedUrlString = urlTextBox.getText().toString();
579 URL unformattedUrl = null;
580 Uri.Builder formattedUri = new Uri.Builder();
582 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
583 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
584 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
585 if (!unformattedUrlString.startsWith("http")) {
586 unformattedUrlString = "http://" + unformattedUrlString;
589 // 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.
591 unformattedUrl = new URL(unformattedUrlString);
592 } catch (MalformedURLException e) {
596 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
597 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
598 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
599 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
600 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
601 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
603 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
604 formattedUrlString = formattedUri.build().toString();
606 // Sanitize the search input and convert it to a DuckDuckGo search.
607 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
609 // Use the correct search URL based on javaScriptEnabled.
610 if (javaScriptEnabled) {
611 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
613 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
617 mainWebView.loadUrl(formattedUrlString);
619 // Hides the keyboard so we can see the webpage.
620 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
621 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);