]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebView.java
0b9c117a1ca962cacfa02073e9e08c5cbd23c368
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / MainWebView.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.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;
57 import java.net.URL;
58 import java.net.URLEncoder;
59
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;
65
66     // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
67     private Menu mainMenu;
68     // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
69     private String formattedUrlString;
70     // homepage is used in onCreate() and onOptionsItemSelected().
71     private String homepage = "https://www.duckduckgo.com/";
72     // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
73     private boolean javaScriptEnabled;
74     // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
75     private boolean domStorageEnabled;
76
77     /* saveFormDataEnabled does nothing until database storage is implemented.
78     // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
79     private boolean saveFormDataEnabled;
80     */
81
82     // cookieManager is used in onCreate() and onOptionsItemSelected().
83     private CookieManager cookieManager;
84     // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
85     private boolean cookiesEnabled;
86
87     // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
88     private EditText urlTextBox;
89
90     @Override
91     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
92     @SuppressLint("SetJavaScriptEnabled")
93     protected void onCreate(Bundle savedInstanceState) {
94         super.onCreate(savedInstanceState);
95         setContentView(R.layout.activity_webview);
96
97         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
98         final Activity mainWebViewActivity = this;
99         final ActionBar actionBar = getSupportActionBar();
100
101         mainWebView = (WebView) findViewById(R.id.mainWebView);
102
103         if (actionBar != null) {
104             // Remove the title from the action bar.
105             actionBar.setDisplayShowTitleEnabled(false);
106
107             // Add the custom app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
108             actionBar.setCustomView(R.layout.app_bar);
109             actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
110
111             // Set the "go" button on the keyboard to load the URL in urlTextBox.
112             urlTextBox = (EditText) actionBar.getCustomView().findViewById(R.id.urlTextBox);
113             urlTextBox.setOnKeyListener(new View.OnKeyListener() {
114                 public boolean onKey(View v, int keyCode, KeyEvent event) {
115                     // If the event is a key-down event on the "enter" button, load the URL.
116                     if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
117                         // Load the URL into the mainWebView and consume the event.
118                         try {
119                             loadUrlFromTextBox();
120                         } catch (UnsupportedEncodingException e) {
121                             e.printStackTrace();
122                         }
123                         // If the enter key was pressed, consume the event.
124                         return true;
125                     } else {
126                         // If any other key was pressed, do not consume the event.
127                         return false;
128                     }
129                 }
130             });
131         }
132
133         mainWebView.setWebViewClient(new WebViewClient() {
134             // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
135             @Override
136             public boolean shouldOverrideUrlLoading(WebView view, String url) {
137                 mainWebView.loadUrl(url);
138                 return true;
139             }
140
141             /* These errors do not provide any useful information and clutter the screen.
142             public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
143                 Toast.makeText(mainWebViewActivity, "Error loading " + request + "   Error: " + error, Toast.LENGTH_SHORT).show();
144             }
145             */
146
147             // Update the URL in urlTextBox when the page starts to load.
148             @Override
149             public void onPageStarted(WebView view, String url, Bitmap favicon) {
150                 urlTextBox.setText(url);
151             }
152
153             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
154             @Override
155             public void onPageFinished(WebView view, String url) {
156                 formattedUrlString = url;
157                 urlTextBox.setText(formattedUrlString);
158             }
159         });
160
161         mainWebView.setWebChromeClient(new WebChromeClient() {
162             // Update the progress bar when a page is loading.
163             @Override
164             public void onProgressChanged(WebView view, int progress) {
165                 // Make sure that actionBar is not null.
166                 if (actionBar != null) {
167                     ProgressBar progressBar = (ProgressBar) actionBar.getCustomView().findViewById(R.id.progressBar);
168                     progressBar.setProgress(progress);
169                     if (progress < 100) {
170                         progressBar.setVisibility(View.VISIBLE);
171                     } else {
172                         progressBar.setVisibility(View.GONE);
173                     }
174                 }
175             }
176
177             // Set the favorite icon when it changes.
178             @Override
179             public void onReceivedIcon(WebView view, Bitmap icon) {
180                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
181                 favoriteIcon = icon;
182
183                 // Place the favorite icon in the actionBar if it is not null.
184                 if (actionBar != null) {
185                     ImageView imageViewFavoriteIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.favoriteIcon);
186                     imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
187                 }
188             }
189
190             // Enter full screen video
191             @Override
192             public void onShowCustomView(View view, CustomViewCallback callback) {
193                 if (actionBar != null) {
194                     actionBar.hide();
195                 }
196
197                 fullScreenVideoFrameLayout.addView(view);
198                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
199
200                 mainWebView.setVisibility(View.GONE);
201
202                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
203                 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
204                 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
205                 */
206
207                 // Set the one flag supported by API >= 14.
208                 if (Build.VERSION.SDK_INT >= 14) {
209                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
210                 }
211
212                 // Set the two flags that are supported by API >= 16.
213                 if (Build.VERSION.SDK_INT >= 16) {
214                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
215                 }
216
217                 // Set all three flags that are supported by API >= 19.
218                 if (Build.VERSION.SDK_INT >= 19) {
219                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
220                 }
221             }
222
223             // Exit full screen video
224             public void onHideCustomView() {
225                 if (actionBar != null) {
226                     actionBar.show();
227                 }
228
229                 mainWebView.setVisibility(View.VISIBLE);
230
231                 fullScreenVideoFrameLayout.removeAllViews();
232                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
233             }
234         });
235
236         // Allow the downloading of files.
237         mainWebView.setDownloadListener(new DownloadListener() {
238             // Launch the Android download manager when a link leads to a download.
239             @Override
240             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
241                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
242                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
243
244                 // Add the URL as the description for the download.
245                 requestUri.setDescription(url);
246
247                 // Show the download notification after the download is completed if the API is 11 or greater.
248                 if (Build.VERSION.SDK_INT >= 11) {
249                     requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
250                 }
251
252                 downloadManager.enqueue(requestUri);
253                 Toast.makeText(mainWebViewActivity, "Download started", Toast.LENGTH_SHORT).show();
254             }
255         });
256
257         // Allow pinch to zoom.
258         mainWebView.getSettings().setBuiltInZoomControls(true);
259
260         // Hide zoom controls if the API is 11 or greater.
261         if (Build.VERSION.SDK_INT >= 11) {
262             mainWebView.getSettings().setDisplayZoomControls(false);
263         }
264
265         // Set JavaScript initial status.
266         javaScriptEnabled = false;
267         mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
268
269         // Set DOM Storage initial status.
270         domStorageEnabled = false;
271         mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
272
273         /* Save Form Data does nothing until database storage is implemented.
274         // Set Save Form Data initial status.
275         saveFormDataEnabled = true;
276         mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
277         */
278
279         // Set Cookies initial status.
280         cookiesEnabled = false;
281         cookieManager = CookieManager.getInstance();
282         cookieManager.setAcceptCookie(cookiesEnabled);
283
284         // Get the intent information that started the app.
285         final Intent intent = getIntent();
286
287         if (intent.getData() != null) {
288             // Get the intent data and convert it to a string.
289             final Uri intentUriData = intent.getData();
290             formattedUrlString = intentUriData.toString();
291         }
292
293         // If formattedUrlString is null assign the homepage to it.
294         if (formattedUrlString == null) {
295             formattedUrlString = homepage;
296         }
297
298         // Load the initial website.
299         mainWebView.loadUrl(formattedUrlString);
300     }
301
302     @Override
303     protected void onNewIntent(Intent intent) {
304         // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
305         setIntent(intent);
306
307         if (intent.getData() != null) {
308             // Get the intent data and convert it to a string.
309             final Uri intentUriData = intent.getData();
310             formattedUrlString = intentUriData.toString();
311         }
312
313         // Load the website.
314         mainWebView.loadUrl(formattedUrlString);
315     }
316
317     @Override
318     public boolean onCreateOptionsMenu(Menu menu) {
319         // Inflate the menu; this adds items to the action bar if it is present.
320         getMenuInflater().inflate(R.menu.menu_webview, menu);
321
322         // Set mainMenu so it can be used by onOptionsItemSelected.
323         mainMenu = menu;
324
325         // Get MenuItems for checkable menu items.
326         MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
327         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
328         /* toggleSaveFormData does nothing until database storage is implemented.
329         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
330         */
331         MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
332
333         // Set the initial icon for toggleJavaScript
334         if (javaScriptEnabled) {
335             toggleJavaScript.setIcon(R.drawable.javascript_on);
336         } else {
337             if (domStorageEnabled || cookiesEnabled) {
338                 toggleJavaScript.setIcon(R.drawable.warning_on);
339             } else {
340                 toggleJavaScript.setIcon(R.drawable.privacy_mode);
341             }
342         }
343
344         // Set the initial status of the menu item checkboxes.
345         toggleDomStorage.setChecked(domStorageEnabled);
346         /* toggleSaveFormData does nothing until database storage is implemented.
347         toggleSaveFormData.setChecked(saveFormDataEnabled);
348         */
349         toggleCookies.setChecked(cookiesEnabled);
350
351         return true;
352     }
353
354     @Override
355     public boolean onPrepareOptionsMenu(Menu menu) {
356         // Enable Clear Cookies if there are any.
357         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
358         clearCookies.setEnabled(cookieManager.hasCookies());
359
360         // Enable Back if canGoBack().
361         MenuItem back = menu.findItem(R.id.back);
362         back.setEnabled(mainWebView.canGoBack());
363
364         // Enable forward if canGoForward().
365         MenuItem forward = menu.findItem(R.id.forward);
366         forward.setEnabled(mainWebView.canGoForward());
367
368         // Run all the other default commands.
369         super.onPrepareOptionsMenu(menu);
370
371         // return true displays the menu.
372         return true;
373     }
374
375     @Override
376     // @TargetApi(11) turns off the errors regarding copy and paste, which are removed from view in menu_webview.xml for lower version of Android.
377     @TargetApi(11)
378     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
379     @SuppressLint("SetJavaScriptEnabled")
380     // removeAllCookies is deprecated, but it is required for API < 21.
381     @SuppressWarnings("deprecation")
382     public boolean onOptionsItemSelected(MenuItem menuItem) {
383         int menuItemId = menuItem.getItemId();
384
385         // Some options need to access the clipboard.
386         ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
387
388         // Some options need to update the drawable for toggleJavaScript.
389         MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
390
391         // Sets the commands that relate to the menu entries.
392         switch (menuItemId) {
393             case R.id.toggleJavaScript:
394                 if (javaScriptEnabled) {
395                     javaScriptEnabled = false;
396                     mainWebView.getSettings().setJavaScriptEnabled(false);
397                     mainWebView.reload();
398
399                     // Update the toggleJavaScript icon and display a toast message.
400                     if (domStorageEnabled || cookiesEnabled) {
401                         menuItem.setIcon(R.drawable.warning_on);
402                         if (domStorageEnabled && cookiesEnabled) {
403                             Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage and Cookies still enabled", Toast.LENGTH_SHORT).show();
404                         } else {
405                             if (domStorageEnabled) {
406                                 Toast.makeText(getApplicationContext(), "JavaScript disabled, DOM Storage still enabled", Toast.LENGTH_SHORT).show();
407                             } else {
408                                 Toast.makeText(getApplicationContext(), "JavaScript disabled, Cookies still enabled", Toast.LENGTH_SHORT).show();
409                             }
410                         }
411                     } else {
412                         menuItem.setIcon(R.drawable.privacy_mode);
413                         Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
414                     }
415                 } else {
416                     javaScriptEnabled = true;
417                     menuItem.setIcon(R.drawable.javascript_on);
418                     mainWebView.getSettings().setJavaScriptEnabled(true);
419                     mainWebView.reload();
420                     Toast.makeText(getApplicationContext(), "JavaScript enabled", Toast.LENGTH_SHORT).show();
421                 }
422                 return true;
423
424             case R.id.toggleDomStorage:
425                 if (domStorageEnabled) {
426                     domStorageEnabled = false;
427                     menuItem.setChecked(false);
428                     mainWebView.getSettings().setDomStorageEnabled(false);
429                     mainWebView.reload();
430
431                     // Update the toggleJavaScript icon and display a toast message if appropriate.
432                     if (!javaScriptEnabled && !cookiesEnabled) {
433                         toggleJavaScript.setIcon(R.drawable.privacy_mode);
434                         Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
435                     } else {
436                         if (cookiesEnabled) {
437                             toggleJavaScript.setIcon(R.drawable.warning_on);
438                             Toast.makeText(getApplicationContext(), "Cookies still enabled", Toast.LENGTH_SHORT).show();
439                         } // Else Do nothing because JavaScript is enabled.
440                     }
441                 } else {
442                     domStorageEnabled = true;
443                     menuItem.setChecked(true);
444                     mainWebView.getSettings().setDomStorageEnabled(true);
445                     mainWebView.reload();
446
447                     // Update the toggleJavaScript icon if appropriate.
448                     if (!javaScriptEnabled) {
449                         toggleJavaScript.setIcon(R.drawable.warning_on);
450                     } // Else Do nothing because JavaScript is enabled.
451
452                     Toast.makeText(getApplicationContext(), "DOM Storage enabled", Toast.LENGTH_SHORT).show();
453                 }
454                 return true;
455
456             /* toggleSaveFormData does nothing until database storage is implemented.
457             case R.id.toggleSaveFormData:
458                 if (saveFormDataEnabled) {
459                     saveFormDataEnabled = false;
460                     menuItem.setChecked(false);
461                     mainWebView.getSettings().setSaveFormData(false);
462                     mainWebView.reload();
463                 } else {
464                     saveFormDataEnabled = true;
465                     menuItem.setChecked(true);
466                     mainWebView.getSettings().setSaveFormData(true);
467                     mainWebView.reload();
468                 }
469                 return true;
470             */
471
472             case R.id.toggleCookies:
473                 if (cookiesEnabled) {
474                     cookiesEnabled = false;
475                     menuItem.setChecked(false);
476                     cookieManager.setAcceptCookie(false);
477                     mainWebView.reload();
478
479                     // Update the toggleJavaScript icon and display a toast message if appropriate.
480                     if (!javaScriptEnabled && !domStorageEnabled) {
481                         toggleJavaScript.setIcon(R.drawable.privacy_mode);
482                         Toast.makeText(getApplicationContext(), "Privacy Mode", Toast.LENGTH_SHORT).show();
483                     } else {
484                         if (domStorageEnabled) {
485                             toggleJavaScript.setIcon(R.drawable.warning_on);
486                             Toast.makeText(getApplicationContext(), "DOM Storage still enabled", Toast.LENGTH_SHORT).show();
487                         } // Else Do nothing because JavaScript is enabled.
488                     }
489                 } else {
490                     cookiesEnabled = true;
491                     menuItem.setChecked(true);
492                     cookieManager.setAcceptCookie(true);
493                     mainWebView.reload();
494
495                     // Update the toggleJavaScript icon if appropriate.
496                     if (!javaScriptEnabled) {
497                         toggleJavaScript.setIcon(R.drawable.warning_on);
498                     } // Else Do nothing because JavaScript is enabled.
499
500                     Toast.makeText(getApplicationContext(), "Cookies enabled", Toast.LENGTH_SHORT).show();
501                 }
502                 return true;
503
504             case R.id.clearDomStorage:
505                 WebStorage webStorage = WebStorage.getInstance();
506                 webStorage.deleteAllData();
507                 Toast.makeText(getApplicationContext(), "DOM storage deleted", Toast.LENGTH_SHORT).show();
508                 return true;
509
510             case R.id.clearCookies:
511                 if (Build.VERSION.SDK_INT < 21) {
512                     cookieManager.removeAllCookie();
513                 } else {
514                     cookieManager.removeAllCookies(null);
515                 }
516                 Toast.makeText(getApplicationContext(), "Cookies deleted", Toast.LENGTH_SHORT).show();
517                 return true;
518
519             case R.id.home:
520                 mainWebView.loadUrl(homepage);
521                 return true;
522
523             case R.id.refresh:
524                 mainWebView.reload();
525                 return true;
526
527             case R.id.back:
528                 mainWebView.goBack();
529                 return true;
530
531             case R.id.forward:
532                 mainWebView.goForward();
533                 return true;
534
535             case R.id.copyURL:
536                 clipboard.setPrimaryClip(ClipData.newPlainText("URL", urlTextBox.getText()));
537                 return true;
538
539             case R.id.pasteURL:
540                 ClipData.Item clipboardData = clipboard.getPrimaryClip().getItemAt(0);
541                 urlTextBox.setText(clipboardData.coerceToText(this));
542                     try {
543                         loadUrlFromTextBox();
544                     } catch (UnsupportedEncodingException e) {
545                         e.printStackTrace();
546                     }
547                 return true;
548
549             case R.id.shareURL:
550                 Intent shareIntent = new Intent();
551                 shareIntent.setAction(Intent.ACTION_SEND);
552                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
553                 shareIntent.setType("text/plain");
554                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
555                 return true;
556
557             case R.id.addToHomescreen:
558                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
559                 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
560                 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
561
562                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
563                 return true;
564
565             case R.id.downloads:
566                 // Launch the system Download Manager.
567                 Intent downloadManangerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
568
569                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
570                 downloadManangerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
571
572                 startActivity(downloadManangerIntent);
573                 return true;
574
575             case R.id.about:
576                 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
577                 AppCompatDialogFragment aboutDialog = new AboutDialog();
578                 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
579                 return true;
580
581             case R.id.clearAndExit:
582                 // Clear DOM storage.
583                 WebStorage domStorage = WebStorage.getInstance();
584                 domStorage.deleteAllData();
585
586                 // Clear cookies.
587                 if (Build.VERSION.SDK_INT < 21) {
588                     cookieManager.removeAllCookie();
589                 } else {
590                     cookieManager.removeAllCookies(null);
591                 }
592
593                 // Destroy the internal state of the webview.
594                 mainWebView.destroy();
595
596                 // Close Privacy Browser.
597                 finish();
598                 return true;
599
600             default:
601                 return super.onOptionsItemSelected(menuItem);
602         }
603     }
604
605     @Override
606     public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
607         // Do nothing because the user selected "Cancel".
608     }
609
610     @Override
611     public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
612         // Get shortcutNameEditText from the alert dialog.
613         EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
614
615         // Create the bookmark shortcut based on formattedUrlString.
616         Intent bookmarkShortcut = new Intent();
617         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
618         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
619
620         // Place the bookmark shortcut on the home screen.
621         Intent placeBookmarkShortcut = new Intent();
622         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
623         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
624         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
625         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
626         sendBroadcast(placeBookmarkShortcut);
627     }
628
629     // Override onBackPressed so that if mainWebView can go back it does when the system back button is pressed.
630     @Override
631     public void onBackPressed() {
632         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
633
634         if (mainWebView.canGoBack()) {
635             mainWebView.goBack();
636         } else {
637             super.onBackPressed();
638         }
639     }
640
641     public void loadUrlFromTextBox() throws UnsupportedEncodingException {
642         // Get the text from urlTextBox and convert it to a string.
643         String unformattedUrlString = urlTextBox.getText().toString();
644         URL unformattedUrl = null;
645         Uri.Builder formattedUri = new Uri.Builder();
646
647         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
648         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
649             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
650             if (!unformattedUrlString.startsWith("http")) {
651                 unformattedUrlString = "http://" + unformattedUrlString;
652             }
653
654             // 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.
655             try {
656                 unformattedUrl = new URL(unformattedUrlString);
657             } catch (MalformedURLException e) {
658                 e.printStackTrace();
659             }
660
661             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
662             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
663             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
664             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
665             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
666             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
667
668             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
669             formattedUrlString = formattedUri.build().toString();
670         } else {
671             // Sanitize the search input and convert it to a DuckDuckGo search.
672             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
673
674             // Use the correct search URL based on javaScriptEnabled.
675             if (javaScriptEnabled) {
676                 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
677             } else {
678                 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
679             }
680         }
681
682         mainWebView.loadUrl(formattedUrlString);
683
684         // Hides the keyboard so we can see the webpage.
685         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
686         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
687     }
688 }