1 package com.stoutner.privacybrowser;
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;
36 import java.net.URLEncoder;
38 public class Webview extends AppCompatActivity {
40 private String formattedUrlString;
41 private String homepage = "https://www.duckduckgo.com/";
43 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
44 @SuppressLint("SetJavaScriptEnabled")
47 protected void onCreate(Bundle savedInstanceState) {
48 super.onCreate(savedInstanceState);
49 setContentView(R.layout.activity_webview);
51 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
52 final Activity mainWebViewActivity = this;
54 final ActionBar actionBar = getSupportActionBar();
55 if (actionBar != null) {
56 // Remove the title from the action bar.
57 actionBar.setDisplayShowTitleEnabled(false);
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);
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.
73 } catch (UnsupportedEncodingException e) {
76 // If the enter key was pressed, consume the event.
79 // If any other key was pressed, do not consume the event.
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.
88 public boolean shouldOverrideUrlLoading(WebView view, String url) {
89 mainWebView.loadUrl(url);
93 public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
94 Toast.makeText(mainWebViewActivity, "Error loading " + request + " Error: " + error, Toast.LENGTH_LONG).show();
97 // Update the URL in urlTextBox when the page starts to load.
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);
106 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
108 public void onPageFinished(WebView view, String url) {
109 formattedUrlString = url;
111 if (actionBar != null) {
112 EditText urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
113 urlTextBox.setText(formattedUrlString);
118 mainWebView.setWebChromeClient(new WebChromeClient() {
119 // Update the progress bar when a page is loading.
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);
129 progressBar.setVisibility(View.GONE);
134 // Set the favorite icon when it changes.
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));
145 mainWebView.setDownloadListener(new DownloadListener() {
146 // Launch the Android download manager when a link leads to a download.
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));
152 // Add the URL as the description for the download.
153 requestUri.setDescription(url);
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);
160 downloadManager.enqueue(requestUri);
161 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
165 // Allow pinch to zoom.
166 mainWebView.getSettings().setBuiltInZoomControls(true);
168 // Hide zoom controls if the API is 11 or greater.
169 if (Build.VERSION.SDK_INT >= 11) {
170 mainWebView.getSettings().setDisplayZoomControls(false);
173 // Enable JavaScript.
174 mainWebView.getSettings().setJavaScriptEnabled(true);
176 // Enable DOM Storage.
177 mainWebView.getSettings().setDomStorageEnabled(true);
179 // Get the intent information that started the app.
180 final Intent intent = getIntent();
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();
188 // If formattedUrlString is null assign the homepage to it.
189 if (formattedUrlString == null) {
190 formattedUrlString = homepage;
193 // Load the initial website.
194 mainWebView.loadUrl(formattedUrlString);
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);
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.
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);
213 // Sets the commands that relate to the menu entries.
214 switch (menuItemId) {
216 mainWebView.loadUrl(homepage);
220 mainWebView.loadUrl(formattedUrlString);
224 mainWebView.goBack();
228 mainWebView.goForward();
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()));
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));
246 loadUrlFromTextBox();
247 } catch (UnsupportedEncodingException e) {
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"));
266 // Launch the system Download Manager.
267 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
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);
272 startActivity(downloadManangerIntent);
275 return super.onOptionsItemSelected(menuItem);
278 // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
280 public void onBackPressed() {
281 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
283 if (mainWebView.canGoBack()) {
284 mainWebView.goBack();
286 super.onBackPressed();
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);
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();
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()) {
305 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
306 if (!unformattedUrlString.startsWith("http")) {
307 unformattedUrlString = "http://" + unformattedUrlString;
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.
312 unformattedUrl = new URL(unformattedUrlString);
313 } catch (MalformedURLException e) {
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;
324 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
325 formattedUrlString = formattedUri.build().toString();
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;
333 mainWebView.loadUrl(formattedUrlString);
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);