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