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