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