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