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