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