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