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