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