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