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