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