]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebViewActivity.java
Allow customization of the search URLs.
[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 initial status for the search URLs.
347         javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
348         javaScriptDisabledSearchCustomURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
349         javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
350         javaScriptEnabledSearchCustomURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
351
352         // Set homepage initial status.  The default value is "https://www.duckduckgo.com".
353         homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
354
355         // Set swipe to refresh initial status.  The default is true.
356         swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
357         swipeToRefresh.setEnabled(swipeToRefreshEnabled);
358
359
360         // Get the intent information that started the app.
361         final Intent intent = getIntent();
362
363         if (intent.getData() != null) {
364             // Get the intent data and convert it to a string.
365             final Uri intentUriData = intent.getData();
366             formattedUrlString = intentUriData.toString();
367         }
368
369         // If formattedUrlString is null assign the homepage to it.
370         if (formattedUrlString == null) {
371             formattedUrlString = homepage;
372         }
373
374         // Load the initial website.
375         mainWebView.loadUrl(formattedUrlString);
376
377         // Load the ad if this is the free flavor.
378         BannerAd.requestAd(adView);
379     }
380
381     @Override
382     protected void onNewIntent(Intent intent) {
383         // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
384         setIntent(intent);
385
386         if (intent.getData() != null) {
387             // Get the intent data and convert it to a string.
388             final Uri intentUriData = intent.getData();
389             formattedUrlString = intentUriData.toString();
390         }
391
392         // Close the navigation drawer if it is open.
393         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
394             drawerLayout.closeDrawer(GravityCompat.START);
395         }
396
397         // Load the website.
398         mainWebView.loadUrl(formattedUrlString);
399
400         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
401         mainWebView.requestFocus();
402     }
403
404     @Override
405     public boolean onCreateOptionsMenu(Menu menu) {
406         // Inflate the menu; this adds items to the action bar if it is present.
407         getMenuInflater().inflate(R.menu.menu_options, menu);
408
409         // Set mainMenu so it can be used by onOptionsItemSelected.
410         mainMenu = menu;
411
412         // Get MenuItems for checkable menu items.
413         MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
414         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
415         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
416         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
417         /* toggleSaveFormData does nothing until database storage is implemented.
418         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
419         */
420
421         // Set the initial icon for toggleJavaScript
422         if (javaScriptEnabled) {
423             toggleJavaScript.setIcon(R.drawable.javascript_enabled);
424         } else {
425             if (domStorageEnabled || firstPartyCookiesEnabled) {
426                 toggleJavaScript.setIcon(R.drawable.warning);
427             } else {
428                 toggleJavaScript.setIcon(R.drawable.privacy_mode);
429             }
430         }
431
432         // Set the initial status of the menu item checkboxes.
433         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
434         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
435         toggleDomStorage.setChecked(domStorageEnabled);
436         /* toggleSaveFormData does nothing until database storage is implemented.
437         toggleSaveFormData.setChecked(saveFormDataEnabled);
438         */
439
440         return true;
441     }
442
443     @Override
444     public boolean onPrepareOptionsMenu(Menu menu) {
445         // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
446         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
447         if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
448             toggleThirdPartyCookies.setEnabled(true);
449         } else {
450             toggleThirdPartyCookies.setEnabled(false);
451         }
452
453         // Enable Clear Cookies if there are any.
454         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
455         clearCookies.setEnabled(cookieManager.hasCookies());
456
457         // Run all the other default commands.
458         super.onPrepareOptionsMenu(menu);
459
460         // return true displays the menu.
461         return true;
462     }
463
464     @Override
465     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
466     @SuppressLint("SetJavaScriptEnabled")
467     // removeAllCookies is deprecated, but it is required for API < 21.
468     @SuppressWarnings("deprecation")
469     public boolean onOptionsItemSelected(MenuItem menuItem) {
470         int menuItemId = menuItem.getItemId();
471
472         // Some options need to update the drawable for toggleJavaScript.
473         MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
474
475         // Set the commands that relate to the menu entries.
476         switch (menuItemId) {
477             case R.id.toggleJavaScript:
478                 if (javaScriptEnabled) {
479                     javaScriptEnabled = false;
480                     mainWebView.getSettings().setJavaScriptEnabled(false);
481                     mainWebView.reload();
482
483                     // Update the toggleJavaScript icon and display a snackbar.
484                     if (domStorageEnabled || firstPartyCookiesEnabled) {
485                         menuItem.setIcon(R.drawable.warning);
486                         Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
487                     } else {
488                         menuItem.setIcon(R.drawable.privacy_mode);
489                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
490                     }
491                 } else {
492                     javaScriptEnabled = true;
493                     menuItem.setIcon(R.drawable.javascript_enabled);
494                     mainWebView.getSettings().setJavaScriptEnabled(true);
495                     mainWebView.reload();
496                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
497                 }
498                 return true;
499
500             case R.id.toggleFirstPartyCookies:
501                 if (firstPartyCookiesEnabled) {
502                     firstPartyCookiesEnabled = false;
503                     menuItem.setChecked(false);
504                     cookieManager.setAcceptCookie(false);
505                     mainWebView.reload();
506
507                     // Update the toggleJavaScript icon if appropriate and display a snackbar.
508                     if (!javaScriptEnabled) {
509                         if (domStorageEnabled) {
510                             toggleJavaScript.setIcon(R.drawable.warning);
511                             Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
512                         } else {
513                             toggleJavaScript.setIcon(R.drawable.privacy_mode);
514                             Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
515                         }
516                     } else {
517                         Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
518                     }
519                 } else {
520                     firstPartyCookiesEnabled = true;
521                     menuItem.setChecked(true);
522                     cookieManager.setAcceptCookie(true);
523                     mainWebView.reload();
524
525                     // Update the toggleJavaScript icon if appropriate.
526                     if (!javaScriptEnabled) {
527                         toggleJavaScript.setIcon(R.drawable.warning);
528                     } // Else do nothing because JavaScript is enabled.
529
530                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
531                 }
532                 return true;
533
534             case R.id.toggleThirdPartyCookies:
535                 if (Build.VERSION.SDK_INT >= 21) {
536                     if (thirdPartyCookiesEnabled) {
537                         thirdPartyCookiesEnabled = false;
538                         menuItem.setChecked(false);
539                         cookieManager.setAcceptThirdPartyCookies(mainWebView, false);
540                         mainWebView.reload();
541
542                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
543                     } else {
544                         thirdPartyCookiesEnabled = true;
545                         menuItem.setChecked(true);
546                         cookieManager.setAcceptThirdPartyCookies(mainWebView, true);
547                         mainWebView.reload();
548
549                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
550                     }
551                 } // Else do nothing because SDK < 21.
552                 return true;
553
554             case R.id.toggleDomStorage:
555                 if (domStorageEnabled) {
556                     domStorageEnabled = false;
557                     menuItem.setChecked(false);
558                     mainWebView.getSettings().setDomStorageEnabled(false);
559                     mainWebView.reload();
560
561                     // Update the toggleJavaScript icon if appropriate and display a snackbar.
562                     if (!javaScriptEnabled) {
563                         if (firstPartyCookiesEnabled) {
564                             toggleJavaScript.setIcon(R.drawable.warning);
565                             Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
566                         } else {
567                             toggleJavaScript.setIcon(R.drawable.privacy_mode);
568                             Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
569                         }
570                     }else {
571                         Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
572                     }
573                 } else {
574                     domStorageEnabled = true;
575                     menuItem.setChecked(true);
576                     mainWebView.getSettings().setDomStorageEnabled(true);
577                     mainWebView.reload();
578
579                     // Update the toggleJavaScript icon if appropriate.
580                     if (!javaScriptEnabled) {
581                         toggleJavaScript.setIcon(R.drawable.warning);
582                     } // Else Do nothing because JavaScript is enabled.
583
584                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
585                 }
586                 return true;
587
588             case R.id.clearCookies:
589                 if (Build.VERSION.SDK_INT < 21) {
590                     cookieManager.removeAllCookie();
591                 } else {
592                     cookieManager.removeAllCookies(null);
593                 }
594                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
595                 return true;
596
597             case R.id.clearDomStorage:
598                 WebStorage webStorage = WebStorage.getInstance();
599                 webStorage.deleteAllData();
600                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
601                 return true;
602
603             case R.id.share:
604                 Intent shareIntent = new Intent();
605                 shareIntent.setAction(Intent.ACTION_SEND);
606                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
607                 shareIntent.setType("text/plain");
608                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
609                 return true;
610
611             case R.id.addToHomescreen:
612                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
613                 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
614                 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
615
616                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
617                 return true;
618
619             case R.id.refresh:
620                 mainWebView.reload();
621
622             default:
623                 return super.onOptionsItemSelected(menuItem);
624         }
625     }
626
627     @Override
628     // removeAllCookies is deprecated, but it is required for API < 21.
629     @SuppressWarnings("deprecation")
630     public boolean onNavigationItemSelected(MenuItem menuItem) {
631         int menuItemId = menuItem.getItemId();
632
633         switch (menuItemId) {
634             case R.id.home:
635                 mainWebView.loadUrl(homepage);
636                 break;
637
638             case R.id.back:
639                 if (mainWebView.canGoBack()) {
640                     mainWebView.goBack();
641                 }
642                 break;
643
644             case R.id.forward:
645                 if (mainWebView.canGoForward()) {
646                     mainWebView.goForward();
647                 }
648                 break;
649
650             case R.id.downloads:
651                 // Launch the system Download Manager.
652                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
653
654                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
655                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
656
657                 startActivity(downloadManagerIntent);
658                 break;
659
660             case R.id.settings:
661                 // Launch PreferenceFragment.
662                 Intent intent = new Intent(this, SettingsActivity.class);
663                 startActivity(intent);
664                 break;
665
666             case R.id.about:
667                 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
668                 AppCompatDialogFragment aboutDialog = new AboutDialog();
669                 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
670                 break;
671
672             case R.id.clearAndExit:
673                 // Clear DOM storage.
674                 WebStorage domStorage = WebStorage.getInstance();
675                 domStorage.deleteAllData();
676
677                 // Clear cookies.  The commands changed slightly in API 21.
678                 if (Build.VERSION.SDK_INT >= 21) {
679                     cookieManager.removeAllCookies(null);
680                 } else {
681                     cookieManager.removeAllCookie();
682                 }
683
684                 // Destroy the internal state of the webview.
685                 mainWebView.destroy();
686
687                 // Close Privacy Browser.  finishAndRemoveTask also removes Privacy Browser from the recent app list.
688                 if (Build.VERSION.SDK_INT >= 21) {
689                     finishAndRemoveTask();
690                 } else {
691                     finish();
692                 }
693                 break;
694
695             default:
696                 break;
697         }
698
699         // Close the navigation drawer.
700         drawerLayout.closeDrawer(GravityCompat.START);
701         return true;
702     }
703
704     @Override
705     public void onPostCreate(Bundle savedInstanceState) {
706         super.onPostCreate(savedInstanceState);
707
708         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
709         drawerToggle.syncState();
710     }
711
712     @Override
713     public void onConfigurationChanged(Configuration newConfig) {
714         super.onConfigurationChanged(newConfig);
715
716         // Update the status of the drawerToggle icon.
717         drawerToggle.onConfigurationChanged(newConfig);
718     }
719
720     @Override
721     public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
722         // Do nothing because the user selected "Cancel".
723     }
724
725     @Override
726     public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
727         // Get shortcutNameEditText from the alert dialog.
728         EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
729
730         // Create the bookmark shortcut based on formattedUrlString.
731         Intent bookmarkShortcut = new Intent();
732         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
733         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
734
735         // Place the bookmark shortcut on the home screen.
736         Intent placeBookmarkShortcut = new Intent();
737         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
738         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
739         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
740         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
741         sendBroadcast(placeBookmarkShortcut);
742     }
743
744     // Override onBackPressed to handle the navigation drawer and mainWebView.
745     @Override
746     public void onBackPressed() {
747         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
748
749         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
750         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
751             drawerLayout.closeDrawer(GravityCompat.START);
752         } else {
753             // Load the previous URL if available.
754             if (mainWebView.canGoBack()) {
755                 mainWebView.goBack();
756             } else {
757                 // Pass onBackPressed to the system.
758                 super.onBackPressed();
759             }
760         }
761     }
762
763     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
764         // Get the text from urlTextBox and convert it to a string.
765         String unformattedUrlString = urlTextBox.getText().toString();
766         URL unformattedUrl = null;
767         Uri.Builder formattedUri = new Uri.Builder();
768
769         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
770         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
771             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
772             if (!unformattedUrlString.startsWith("http")) {
773                 unformattedUrlString = "http://" + unformattedUrlString;
774             }
775
776             // 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.
777             try {
778                 unformattedUrl = new URL(unformattedUrlString);
779             } catch (MalformedURLException e) {
780                 e.printStackTrace();
781             }
782
783             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
784             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
785             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
786             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
787             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
788             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
789
790             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
791             formattedUrlString = formattedUri.build().toString();
792         } else {
793             // Sanitize the search input and convert it to a DuckDuckGo search.
794             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
795
796             // Use the correct search URL based on javaScriptEnabled.
797             if (javaScriptEnabled) {
798                 if (javaScriptEnabledSearchURL.equals("Custom URL")) {
799                     formattedUrlString = javaScriptEnabledSearchCustomURL + encodedUrlString;
800                 } else {
801                     formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
802                 }
803             } else { // JavaScript is disabled.
804                 if (javaScriptDisabledSearchURL.equals("Custom URL")) {
805                     formattedUrlString = javaScriptDisabledSearchCustomURL + encodedUrlString;
806                 } else {
807                     formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
808                 }
809             }
810         }
811
812         mainWebView.loadUrl(formattedUrlString);
813
814         // Hides the keyboard so we can see the webpage.
815         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
816         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
817     }
818 }