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