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