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