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