2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser;
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;
61 import java.io.UnsupportedEncodingException;
62 import java.net.MalformedURLException;
64 import java.net.URLEncoder;
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;
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 // 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 // javaScriptDisabledSearchCustomURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
88 public static String javaScriptDisabledSearchCustomURL;
89 // javaScriptEnabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
90 public static String javaScriptEnabledSearchURL;
91 // javaScriptEnabledSearchCustomURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
92 public static String javaScriptEnabledSearchCustomURL;
93 // homepage is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and onOptionsItemSelected().
94 public static String homepage;
95 // swipeToRefresh is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
96 public static SwipeRefreshLayout swipeToRefresh;
97 // swipeToRefreshEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
98 public static boolean swipeToRefreshEnabled;
100 // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
101 private ActionBarDrawerToggle drawerToggle;
102 // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
103 private DrawerLayout drawerLayout;
104 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
105 private String formattedUrlString;
107 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
108 private EditText urlTextBox;
111 // 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.
112 @SuppressLint("SetJavaScriptEnabled")
113 protected void onCreate(Bundle savedInstanceState) {
114 super.onCreate(savedInstanceState);
115 setContentView(R.layout.coordinator_layout);
117 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
118 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
119 setSupportActionBar(supportAppBar);
121 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
123 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
124 final ActionBar appBar = getSupportActionBar();
126 // Setup AdView for the free flavor.
127 final View adView = findViewById(R.id.adView);
129 // Implement swipe to refresh
130 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
131 swipeToRefresh.setColorSchemeResources(R.color.blue);
132 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
134 public void onRefresh() {
135 mainWebView.reload();
139 mainWebView = (WebView) findViewById(R.id.mainWebView);
141 if (appBar != null) {
142 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
143 appBar.setCustomView(R.layout.url_bar);
144 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
146 // Set the "go" button on the keyboard to load the URL in urlTextBox.
147 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
148 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
149 public boolean onKey(View v, int keyCode, KeyEvent event) {
150 // If the event is a key-down event on the "enter" button, load the URL.
151 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
152 // Load the URL into the mainWebView and consume the event.
154 loadUrlFromTextBox();
155 } catch (UnsupportedEncodingException e) {
158 // If the enter key was pressed, consume the event.
161 // If any other key was pressed, do not consume the event.
168 // Create the navigation drawer.
169 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
170 // The DrawerTitle identifies the drawer in accessibility mode.
171 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
173 // Listen for touches on the navigation menu.
174 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
175 navigationView.setNavigationItemSelectedListener(this);
177 // drawerToggle creates the hamburger icon at the start of the AppBar.
178 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
180 mainWebView.setWebViewClient(new WebViewClient() {
181 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
183 public boolean shouldOverrideUrlLoading(WebView view, String url) {
184 mainWebView.loadUrl(url);
188 // Update the URL in urlTextBox when the page starts to load.
190 public void onPageStarted(WebView view, String url, Bitmap favicon) {
191 urlTextBox.setText(url);
194 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
196 public void onPageFinished(WebView view, String url) {
197 formattedUrlString = url;
199 // Only update urlTextBox if the user is not typing in it.
200 if (!urlTextBox.hasFocus()) {
201 urlTextBox.setText(formattedUrlString);
206 mainWebView.setWebChromeClient(new WebChromeClient() {
207 // Update the progress bar when a page is loading.
209 public void onProgressChanged(WebView view, int progress) {
210 // Make sure that appBar is not null.
211 if (appBar != null) {
212 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
213 progressBar.setProgress(progress);
214 if (progress < 100) {
215 progressBar.setVisibility(View.VISIBLE);
217 progressBar.setVisibility(View.GONE);
219 //Stop the SwipeToRefresh indicator if it is running
220 swipeToRefresh.setRefreshing(false);
225 // Set the favorite icon when it changes.
227 public void onReceivedIcon(WebView view, Bitmap icon) {
228 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
231 // Place the favorite icon in the appBar if it is not null.
232 if (appBar != null) {
233 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
234 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
238 // Enter full screen video
240 public void onShowCustomView(View view, CustomViewCallback callback) {
241 if (appBar != null) {
245 // Show the fullScreenVideoFrameLayout.
246 fullScreenVideoFrameLayout.addView(view);
247 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
249 // Hide the mainWebView.
250 mainWebView.setVisibility(View.GONE);
252 // Hide the ad if this is the free flavor.
253 BannerAd.hideAd(adView);
255 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
256 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
257 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
260 // Set the one flag supported by API >= 14.
261 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
263 // Set the two flags that are supported by API >= 16.
264 if (Build.VERSION.SDK_INT >= 16) {
265 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
268 // Set all three flags that are supported by API >= 19.
269 if (Build.VERSION.SDK_INT >= 19) {
270 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
274 // Exit full screen video
275 public void onHideCustomView() {
276 if (appBar != null) {
280 // Show the mainWebView.
281 mainWebView.setVisibility(View.VISIBLE);
283 // Show the ad if this is the free flavor.
284 BannerAd.showAd(adView);
286 // Hide the fullScreenVideoFrameLayout.
287 fullScreenVideoFrameLayout.removeAllViews();
288 fullScreenVideoFrameLayout.setVisibility(View.GONE);
292 // Allow the downloading of files.
293 mainWebView.setDownloadListener(new DownloadListener() {
294 // Launch the Android download manager when a link leads to a download.
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));
300 // Add the URL as the description for the download.
301 requestUri.setDescription(url);
303 // Show the download notification after the download is completed.
304 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
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();
312 // Allow pinch to zoom.
313 mainWebView.getSettings().setBuiltInZoomControls(true);
315 // Hide zoom controls.
316 mainWebView.getSettings().setDisplayZoomControls(false);
319 // Initialize the default preference values the first time the program is run.
320 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
322 // Get the shared preference values.
323 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
325 // Set JavaScript initial status. The default value is false.
326 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
327 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
329 // Initialize cookieManager.
330 cookieManager = CookieManager.getInstance();
332 // Set cookies initial status. The default value is false.
333 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
334 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
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);
342 // Set DOM storage initial status. The default value is false.
343 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
344 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
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":
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"));
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"));
364 // Set the initial status for the search URLs.
365 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
366 javaScriptDisabledSearchCustomURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
367 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
368 javaScriptEnabledSearchCustomURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
370 // Set homepage initial status. The default value is "https://www.duckduckgo.com".
371 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
373 // Set swipe to refresh initial status. The default is true.
374 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
375 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
378 // Get the intent information that started the app.
379 final Intent intent = getIntent();
381 if (intent.getData() != null) {
382 // Get the intent data and convert it to a string.
383 final Uri intentUriData = intent.getData();
384 formattedUrlString = intentUriData.toString();
387 // If formattedUrlString is null assign the homepage to it.
388 if (formattedUrlString == null) {
389 formattedUrlString = homepage;
392 // Load the initial website.
393 mainWebView.loadUrl(formattedUrlString);
395 // Load the ad if this is the free flavor.
396 BannerAd.requestAd(adView);
400 protected void onNewIntent(Intent intent) {
401 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
404 if (intent.getData() != null) {
405 // Get the intent data and convert it to a string.
406 final Uri intentUriData = intent.getData();
407 formattedUrlString = intentUriData.toString();
410 // Close the navigation drawer if it is open.
411 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
412 drawerLayout.closeDrawer(GravityCompat.START);
416 mainWebView.loadUrl(formattedUrlString);
418 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
419 mainWebView.requestFocus();
423 public boolean onCreateOptionsMenu(Menu menu) {
424 // Inflate the menu; this adds items to the action bar if it is present.
425 getMenuInflater().inflate(R.menu.menu_options, menu);
427 // Set mainMenu so it can be used by onOptionsItemSelected.
430 // Get MenuItems for checkable menu items.
431 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
432 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
433 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
434 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
435 /* toggleSaveFormData does nothing until database storage is implemented.
436 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
439 // Set the initial icon for toggleJavaScript
440 if (javaScriptEnabled) {
441 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
443 if (domStorageEnabled || firstPartyCookiesEnabled) {
444 toggleJavaScript.setIcon(R.drawable.warning);
446 toggleJavaScript.setIcon(R.drawable.privacy_mode);
450 // Set the initial status of the menu item checkboxes.
451 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
452 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
453 toggleDomStorage.setChecked(domStorageEnabled);
454 /* toggleSaveFormData does nothing until database storage is implemented.
455 toggleSaveFormData.setChecked(saveFormDataEnabled);
462 public boolean onPrepareOptionsMenu(Menu menu) {
463 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
464 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
465 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
466 toggleThirdPartyCookies.setEnabled(true);
468 toggleThirdPartyCookies.setEnabled(false);
471 // Enable Clear Cookies if there are any.
472 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
473 clearCookies.setEnabled(cookieManager.hasCookies());
475 // Run all the other default commands.
476 super.onPrepareOptionsMenu(menu);
478 // return true displays the menu.
483 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
484 @SuppressLint("SetJavaScriptEnabled")
485 // removeAllCookies is deprecated, but it is required for API < 21.
486 @SuppressWarnings("deprecation")
487 public boolean onOptionsItemSelected(MenuItem menuItem) {
488 int menuItemId = menuItem.getItemId();
490 // Some options need to update the drawable for toggleJavaScript.
491 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
493 // Set the commands that relate to the menu entries.
494 switch (menuItemId) {
495 case R.id.toggleJavaScript:
496 if (javaScriptEnabled) {
497 javaScriptEnabled = false;
498 mainWebView.getSettings().setJavaScriptEnabled(false);
499 mainWebView.reload();
501 // Update the toggleJavaScript icon and display a snackbar.
502 if (domStorageEnabled || firstPartyCookiesEnabled) {
503 menuItem.setIcon(R.drawable.warning);
504 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
506 menuItem.setIcon(R.drawable.privacy_mode);
507 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
510 javaScriptEnabled = true;
511 menuItem.setIcon(R.drawable.javascript_enabled);
512 mainWebView.getSettings().setJavaScriptEnabled(true);
513 mainWebView.reload();
514 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
518 case R.id.toggleFirstPartyCookies:
519 if (firstPartyCookiesEnabled) {
520 firstPartyCookiesEnabled = false;
521 menuItem.setChecked(false);
522 cookieManager.setAcceptCookie(false);
523 mainWebView.reload();
525 // Update the toggleJavaScript icon if appropriate and display a snackbar.
526 if (!javaScriptEnabled) {
527 if (domStorageEnabled) {
528 toggleJavaScript.setIcon(R.drawable.warning);
529 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
531 toggleJavaScript.setIcon(R.drawable.privacy_mode);
532 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
535 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
538 firstPartyCookiesEnabled = true;
539 menuItem.setChecked(true);
540 cookieManager.setAcceptCookie(true);
541 mainWebView.reload();
543 // Update the toggleJavaScript icon if appropriate.
544 if (!javaScriptEnabled) {
545 toggleJavaScript.setIcon(R.drawable.warning);
546 } // Else do nothing because JavaScript is enabled.
548 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
552 case R.id.toggleThirdPartyCookies:
553 if (Build.VERSION.SDK_INT >= 21) {
554 if (thirdPartyCookiesEnabled) {
555 thirdPartyCookiesEnabled = false;
556 menuItem.setChecked(false);
557 cookieManager.setAcceptThirdPartyCookies(mainWebView, false);
558 mainWebView.reload();
560 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
562 thirdPartyCookiesEnabled = true;
563 menuItem.setChecked(true);
564 cookieManager.setAcceptThirdPartyCookies(mainWebView, true);
565 mainWebView.reload();
567 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
569 } // Else do nothing because SDK < 21.
572 case R.id.toggleDomStorage:
573 if (domStorageEnabled) {
574 domStorageEnabled = false;
575 menuItem.setChecked(false);
576 mainWebView.getSettings().setDomStorageEnabled(false);
577 mainWebView.reload();
579 // Update the toggleJavaScript icon if appropriate and display a snackbar.
580 if (!javaScriptEnabled) {
581 if (firstPartyCookiesEnabled) {
582 toggleJavaScript.setIcon(R.drawable.warning);
583 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
585 toggleJavaScript.setIcon(R.drawable.privacy_mode);
586 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
589 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
592 domStorageEnabled = true;
593 menuItem.setChecked(true);
594 mainWebView.getSettings().setDomStorageEnabled(true);
595 mainWebView.reload();
597 // Update the toggleJavaScript icon if appropriate.
598 if (!javaScriptEnabled) {
599 toggleJavaScript.setIcon(R.drawable.warning);
600 } // Else Do nothing because JavaScript is enabled.
602 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
606 case R.id.clearCookies:
607 if (Build.VERSION.SDK_INT < 21) {
608 cookieManager.removeAllCookie();
610 cookieManager.removeAllCookies(null);
612 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
615 case R.id.clearDomStorage:
616 WebStorage webStorage = WebStorage.getInstance();
617 webStorage.deleteAllData();
618 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
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"));
629 case R.id.addToHomescreen:
630 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
631 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
632 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
634 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
638 mainWebView.reload();
642 // Don't consume the event.
643 return super.onOptionsItemSelected(menuItem);
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();
653 switch (menuItemId) {
655 mainWebView.loadUrl(homepage);
659 if (mainWebView.canGoBack()) {
660 mainWebView.goBack();
665 if (mainWebView.canGoForward()) {
666 mainWebView.goForward();
671 // Launch the system Download Manager.
672 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
674 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
675 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
677 startActivity(downloadManagerIntent);
681 // Launch PreferenceFragment.
682 Intent intent = new Intent(this, SettingsActivity.class);
683 startActivity(intent);
687 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
688 AppCompatDialogFragment aboutDialog = new AboutDialog();
689 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
692 case R.id.clearAndExit:
693 // Clear DOM storage.
694 WebStorage domStorage = WebStorage.getInstance();
695 domStorage.deleteAllData();
697 // Clear cookies. The commands changed slightly in API 21.
698 if (Build.VERSION.SDK_INT >= 21) {
699 cookieManager.removeAllCookies(null);
701 cookieManager.removeAllCookie();
704 // Destroy the internal state of the webview.
705 mainWebView.destroy();
707 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
708 if (Build.VERSION.SDK_INT >= 21) {
709 finishAndRemoveTask();
719 // Close the navigation drawer.
720 drawerLayout.closeDrawer(GravityCompat.START);
725 public void onPostCreate(Bundle savedInstanceState) {
726 super.onPostCreate(savedInstanceState);
728 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
729 drawerToggle.syncState();
733 public void onConfigurationChanged(Configuration newConfig) {
734 super.onConfigurationChanged(newConfig);
736 // Update the status of the drawerToggle icon.
737 drawerToggle.onConfigurationChanged(newConfig);
741 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
742 // Do nothing because the user selected "Cancel".
746 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
747 // Get shortcutNameEditText from the alert dialog.
748 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
750 // Create the bookmark shortcut based on formattedUrlString.
751 Intent bookmarkShortcut = new Intent();
752 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
753 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
755 // Place the bookmark shortcut on the home screen.
756 Intent placeBookmarkShortcut = new Intent();
757 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
758 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
759 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
760 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
761 sendBroadcast(placeBookmarkShortcut);
764 // Override onBackPressed to handle the navigation drawer and mainWebView.
766 public void onBackPressed() {
767 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
769 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
770 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
771 drawerLayout.closeDrawer(GravityCompat.START);
773 // Load the previous URL if available.
774 if (mainWebView.canGoBack()) {
775 mainWebView.goBack();
777 // Pass onBackPressed to the system.
778 super.onBackPressed();
783 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
784 // Get the text from urlTextBox and convert it to a string.
785 String unformattedUrlString = urlTextBox.getText().toString();
786 URL unformattedUrl = null;
787 Uri.Builder formattedUri = new Uri.Builder();
789 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
790 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
791 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
792 if (!unformattedUrlString.startsWith("http")) {
793 unformattedUrlString = "http://" + unformattedUrlString;
796 // 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.
798 unformattedUrl = new URL(unformattedUrlString);
799 } catch (MalformedURLException e) {
803 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
804 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
805 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
806 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
807 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
808 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
810 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
811 formattedUrlString = formattedUri.build().toString();
813 // Sanitize the search input and convert it to a DuckDuckGo search.
814 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
816 // Use the correct search URL based on javaScriptEnabled.
817 if (javaScriptEnabled) {
818 if (javaScriptEnabledSearchURL.equals("Custom URL")) {
819 formattedUrlString = javaScriptEnabledSearchCustomURL + encodedUrlString;
821 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
823 } else { // JavaScript is disabled.
824 if (javaScriptDisabledSearchURL.equals("Custom URL")) {
825 formattedUrlString = javaScriptDisabledSearchCustomURL + encodedUrlString;
827 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
832 mainWebView.loadUrl(formattedUrlString);
834 // Hides the keyboard so we can see the webpage.
835 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
836 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);