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