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