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 // javaScriptEnabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
88 public static String javaScriptEnabledSearchURL;
89 // homepage is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and onOptionsItemSelected().
90 public static String homepage;
91 // swipeToRefresh is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
92 public static SwipeRefreshLayout swipeToRefresh;
93 // swipeToRefreshEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
94 public static boolean swipeToRefreshEnabled;
96 // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
97 private ActionBarDrawerToggle drawerToggle;
98 // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
99 private DrawerLayout drawerLayout;
100 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
101 private String formattedUrlString;
103 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
104 private EditText urlTextBox;
107 // 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.
108 @SuppressLint("SetJavaScriptEnabled")
109 protected void onCreate(Bundle savedInstanceState) {
110 super.onCreate(savedInstanceState);
111 setContentView(R.layout.coordinator_layout);
113 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
114 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
115 setSupportActionBar(supportAppBar);
117 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
119 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
120 final ActionBar appBar = getSupportActionBar();
122 // Setup AdView for the free flavor.
123 final View adView = findViewById(R.id.adView);
125 // Implement swipe to refresh
126 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
127 swipeToRefresh.setColorSchemeResources(R.color.blue);
128 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
130 public void onRefresh() {
131 mainWebView.reload();
135 mainWebView = (WebView) findViewById(R.id.mainWebView);
137 if (appBar != null) {
138 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
139 appBar.setCustomView(R.layout.url_bar);
140 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
142 // Set the "go" button on the keyboard to load the URL in urlTextBox.
143 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
144 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
145 public boolean onKey(View v, int keyCode, KeyEvent event) {
146 // If the event is a key-down event on the "enter" button, load the URL.
147 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
148 // Load the URL into the mainWebView and consume the event.
150 loadUrlFromTextBox();
151 } catch (UnsupportedEncodingException e) {
154 // If the enter key was pressed, consume the event.
157 // If any other key was pressed, do not consume the event.
164 // Create the navigation drawer.
165 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
166 // The DrawerTitle identifies the drawer in accessibility mode.
167 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
169 // Listen for touches on the navigation menu.
170 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
171 navigationView.setNavigationItemSelectedListener(this);
173 // drawerToggle creates the hamburger icon at the start of the AppBar.
174 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
176 mainWebView.setWebViewClient(new WebViewClient() {
177 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
179 public boolean shouldOverrideUrlLoading(WebView view, String url) {
180 mainWebView.loadUrl(url);
184 // Update the URL in urlTextBox when the page starts to load.
186 public void onPageStarted(WebView view, String url, Bitmap favicon) {
187 urlTextBox.setText(url);
190 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
192 public void onPageFinished(WebView view, String url) {
193 formattedUrlString = url;
195 // Only update urlTextBox if the user is not typing in it.
196 if (!urlTextBox.hasFocus()) {
197 urlTextBox.setText(formattedUrlString);
202 mainWebView.setWebChromeClient(new WebChromeClient() {
203 // Update the progress bar when a page is loading.
205 public void onProgressChanged(WebView view, int progress) {
206 // Make sure that appBar is not null.
207 if (appBar != null) {
208 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
209 progressBar.setProgress(progress);
210 if (progress < 100) {
211 progressBar.setVisibility(View.VISIBLE);
213 progressBar.setVisibility(View.GONE);
215 //Stop the SwipeToRefresh indicator if it is running
216 swipeToRefresh.setRefreshing(false);
221 // Set the favorite icon when it changes.
223 public void onReceivedIcon(WebView view, Bitmap icon) {
224 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
227 // Place the favorite icon in the appBar if it is not null.
228 if (appBar != null) {
229 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
230 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
234 // Enter full screen video
236 public void onShowCustomView(View view, CustomViewCallback callback) {
237 if (appBar != null) {
241 // Show the fullScreenVideoFrameLayout.
242 fullScreenVideoFrameLayout.addView(view);
243 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
245 // Hide the mainWebView.
246 mainWebView.setVisibility(View.GONE);
248 // Hide the ad if this is the free flavor.
249 BannerAd.hideAd(adView);
251 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
252 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
253 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
256 // Set the one flag supported by API >= 14.
257 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
259 // Set the two flags that are supported by API >= 16.
260 if (Build.VERSION.SDK_INT >= 16) {
261 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
264 // Set all three flags that are supported by API >= 19.
265 if (Build.VERSION.SDK_INT >= 19) {
266 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
270 // Exit full screen video
271 public void onHideCustomView() {
272 if (appBar != null) {
276 // Show the mainWebView.
277 mainWebView.setVisibility(View.VISIBLE);
279 // Show the ad if this is the free flavor.
280 BannerAd.showAd(adView);
282 // Hide the fullScreenVideoFrameLayout.
283 fullScreenVideoFrameLayout.removeAllViews();
284 fullScreenVideoFrameLayout.setVisibility(View.GONE);
288 // Allow the downloading of files.
289 mainWebView.setDownloadListener(new DownloadListener() {
290 // Launch the Android download manager when a link leads to a download.
292 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
293 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
294 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
296 // Add the URL as the description for the download.
297 requestUri.setDescription(url);
299 // Show the download notification after the download is completed.
300 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
302 // Initiate the download and display a Snackbar.
303 downloadManager.enqueue(requestUri);
304 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
308 // Allow pinch to zoom.
309 mainWebView.getSettings().setBuiltInZoomControls(true);
311 // Hide zoom controls.
312 mainWebView.getSettings().setDisplayZoomControls(false);
315 // Initialize the default preference values the first time the program is run.
316 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
318 // Get the shared preference values.
319 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
321 // Set JavaScript initial status. The default value is false.
322 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
323 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
325 // Initialize cookieManager.
326 cookieManager = CookieManager.getInstance();
328 // Set cookies initial status. The default value is false.
329 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
330 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
332 // Set third-party cookies initial status if API >= 21. The default value is false.
333 if (Build.VERSION.SDK_INT >= 21) {
334 thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
335 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
338 // Set DOM storage initial status. The default value is false.
339 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
340 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
342 // Set the user agent initial status.
343 String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
344 switch (userAgentString) {
345 case "Default user agent":
349 case "Custom user agent":
350 // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0".
351 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
355 // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0".
356 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
360 // Set the initial string for JavaScript disabled search.
361 if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
362 // Get the custom URL string. The default is "".
363 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
365 // Use the string from javascript_disabled_search.
366 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
369 // Set the initial string for JavaScript enabled search.
370 if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
371 // Get the custom URL string. The default is "".
372 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
374 // Use the string from javascript_enabled_search.
375 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
379 // Set homepage initial status. The default value is "https://www.duckduckgo.com".
380 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
382 // Set swipe to refresh initial status. The default is true.
383 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
384 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
387 // Get the intent information that started the app.
388 final Intent intent = getIntent();
390 if (intent.getData() != null) {
391 // Get the intent data and convert it to a string.
392 final Uri intentUriData = intent.getData();
393 formattedUrlString = intentUriData.toString();
396 // If formattedUrlString is null assign the homepage to it.
397 if (formattedUrlString == null) {
398 formattedUrlString = homepage;
401 // Load the initial website.
402 mainWebView.loadUrl(formattedUrlString);
404 // Load the ad if this is the free flavor.
405 BannerAd.requestAd(adView);
409 protected void onNewIntent(Intent intent) {
410 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
413 if (intent.getData() != null) {
414 // Get the intent data and convert it to a string.
415 final Uri intentUriData = intent.getData();
416 formattedUrlString = intentUriData.toString();
419 // Close the navigation drawer if it is open.
420 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
421 drawerLayout.closeDrawer(GravityCompat.START);
425 mainWebView.loadUrl(formattedUrlString);
427 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
428 mainWebView.requestFocus();
432 public boolean onCreateOptionsMenu(Menu menu) {
433 // Inflate the menu; this adds items to the action bar if it is present.
434 getMenuInflater().inflate(R.menu.menu_options, menu);
436 // Set mainMenu so it can be used by onOptionsItemSelected.
439 // Get MenuItems for checkable menu items.
440 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
441 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
442 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
443 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
444 /* toggleSaveFormData does nothing until database storage is implemented.
445 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
448 // Set the initial icon for toggleJavaScript
449 if (javaScriptEnabled) {
450 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
452 if (domStorageEnabled || firstPartyCookiesEnabled) {
453 toggleJavaScript.setIcon(R.drawable.warning);
455 toggleJavaScript.setIcon(R.drawable.privacy_mode);
459 // Set the initial status of the menu item checkboxes.
460 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
461 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
462 toggleDomStorage.setChecked(domStorageEnabled);
463 /* toggleSaveFormData does nothing until database storage is implemented.
464 toggleSaveFormData.setChecked(saveFormDataEnabled);
471 public boolean onPrepareOptionsMenu(Menu menu) {
472 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
473 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
474 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
475 toggleThirdPartyCookies.setEnabled(true);
477 toggleThirdPartyCookies.setEnabled(false);
480 // Enable Clear Cookies if there are any.
481 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
482 clearCookies.setEnabled(cookieManager.hasCookies());
484 // Run all the other default commands.
485 super.onPrepareOptionsMenu(menu);
487 // return true displays the menu.
492 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
493 @SuppressLint("SetJavaScriptEnabled")
494 // removeAllCookies is deprecated, but it is required for API < 21.
495 @SuppressWarnings("deprecation")
496 public boolean onOptionsItemSelected(MenuItem menuItem) {
497 int menuItemId = menuItem.getItemId();
499 // Some options need to update the drawable for toggleJavaScript.
500 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
502 // Set the commands that relate to the menu entries.
503 switch (menuItemId) {
504 case R.id.toggleJavaScript:
505 if (javaScriptEnabled) {
506 javaScriptEnabled = false;
507 mainWebView.getSettings().setJavaScriptEnabled(false);
508 mainWebView.reload();
510 // Update the toggleJavaScript icon and display a snackbar.
511 if (domStorageEnabled || firstPartyCookiesEnabled) {
512 menuItem.setIcon(R.drawable.warning);
513 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
515 menuItem.setIcon(R.drawable.privacy_mode);
516 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
519 javaScriptEnabled = true;
520 menuItem.setIcon(R.drawable.javascript_enabled);
521 mainWebView.getSettings().setJavaScriptEnabled(true);
522 mainWebView.reload();
523 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
527 case R.id.toggleFirstPartyCookies:
528 if (firstPartyCookiesEnabled) {
529 firstPartyCookiesEnabled = false;
530 menuItem.setChecked(false);
531 cookieManager.setAcceptCookie(false);
532 mainWebView.reload();
534 // Update the toggleJavaScript icon if appropriate and display a snackbar.
535 if (!javaScriptEnabled) {
536 if (domStorageEnabled) {
537 toggleJavaScript.setIcon(R.drawable.warning);
538 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
540 toggleJavaScript.setIcon(R.drawable.privacy_mode);
541 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
544 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
547 firstPartyCookiesEnabled = true;
548 menuItem.setChecked(true);
549 cookieManager.setAcceptCookie(true);
550 mainWebView.reload();
552 // Update the toggleJavaScript icon if appropriate.
553 if (!javaScriptEnabled) {
554 toggleJavaScript.setIcon(R.drawable.warning);
555 } // Else do nothing because JavaScript is enabled.
557 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
561 case R.id.toggleThirdPartyCookies:
562 if (Build.VERSION.SDK_INT >= 21) {
563 if (thirdPartyCookiesEnabled) {
564 thirdPartyCookiesEnabled = false;
565 menuItem.setChecked(false);
566 cookieManager.setAcceptThirdPartyCookies(mainWebView, false);
567 mainWebView.reload();
569 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
571 thirdPartyCookiesEnabled = true;
572 menuItem.setChecked(true);
573 cookieManager.setAcceptThirdPartyCookies(mainWebView, true);
574 mainWebView.reload();
576 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
578 } // Else do nothing because SDK < 21.
581 case R.id.toggleDomStorage:
582 if (domStorageEnabled) {
583 domStorageEnabled = false;
584 menuItem.setChecked(false);
585 mainWebView.getSettings().setDomStorageEnabled(false);
586 mainWebView.reload();
588 // Update the toggleJavaScript icon if appropriate and display a snackbar.
589 if (!javaScriptEnabled) {
590 if (firstPartyCookiesEnabled) {
591 toggleJavaScript.setIcon(R.drawable.warning);
592 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
594 toggleJavaScript.setIcon(R.drawable.privacy_mode);
595 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
598 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
601 domStorageEnabled = true;
602 menuItem.setChecked(true);
603 mainWebView.getSettings().setDomStorageEnabled(true);
604 mainWebView.reload();
606 // Update the toggleJavaScript icon if appropriate.
607 if (!javaScriptEnabled) {
608 toggleJavaScript.setIcon(R.drawable.warning);
609 } // Else Do nothing because JavaScript is enabled.
611 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
615 case R.id.clearCookies:
616 if (Build.VERSION.SDK_INT < 21) {
617 cookieManager.removeAllCookie();
619 cookieManager.removeAllCookies(null);
621 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
624 case R.id.clearDomStorage:
625 WebStorage webStorage = WebStorage.getInstance();
626 webStorage.deleteAllData();
627 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
631 Intent shareIntent = new Intent();
632 shareIntent.setAction(Intent.ACTION_SEND);
633 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
634 shareIntent.setType("text/plain");
635 startActivity(Intent.createChooser(shareIntent, "Share URL"));
638 case R.id.addToHomescreen:
639 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
640 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
641 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
643 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
647 mainWebView.reload();
651 // Don't consume the event.
652 return super.onOptionsItemSelected(menuItem);
657 // removeAllCookies is deprecated, but it is required for API < 21.
658 @SuppressWarnings("deprecation")
659 public boolean onNavigationItemSelected(MenuItem menuItem) {
660 int menuItemId = menuItem.getItemId();
662 switch (menuItemId) {
664 mainWebView.loadUrl(homepage);
668 if (mainWebView.canGoBack()) {
669 mainWebView.goBack();
674 if (mainWebView.canGoForward()) {
675 mainWebView.goForward();
680 // Launch the system Download Manager.
681 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
683 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
684 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
686 startActivity(downloadManagerIntent);
690 // Launch PreferenceFragment.
691 Intent intent = new Intent(this, SettingsActivity.class);
692 startActivity(intent);
696 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
697 AppCompatDialogFragment aboutDialog = new AboutDialog();
698 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
701 case R.id.clearAndExit:
702 // Clear DOM storage.
703 WebStorage domStorage = WebStorage.getInstance();
704 domStorage.deleteAllData();
706 // Clear cookies. The commands changed slightly in API 21.
707 if (Build.VERSION.SDK_INT >= 21) {
708 cookieManager.removeAllCookies(null);
710 cookieManager.removeAllCookie();
713 // Destroy the internal state of the webview.
714 mainWebView.destroy();
716 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
717 if (Build.VERSION.SDK_INT >= 21) {
718 finishAndRemoveTask();
728 // Close the navigation drawer.
729 drawerLayout.closeDrawer(GravityCompat.START);
734 public void onPostCreate(Bundle savedInstanceState) {
735 super.onPostCreate(savedInstanceState);
737 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
738 drawerToggle.syncState();
742 public void onConfigurationChanged(Configuration newConfig) {
743 super.onConfigurationChanged(newConfig);
745 // Update the status of the drawerToggle icon.
746 drawerToggle.onConfigurationChanged(newConfig);
750 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
751 // Do nothing because the user selected "Cancel".
755 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
756 // Get shortcutNameEditText from the alert dialog.
757 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
759 // Create the bookmark shortcut based on formattedUrlString.
760 Intent bookmarkShortcut = new Intent();
761 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
762 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
764 // Place the bookmark shortcut on the home screen.
765 Intent placeBookmarkShortcut = new Intent();
766 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
767 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
768 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
769 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
770 sendBroadcast(placeBookmarkShortcut);
773 // Override onBackPressed to handle the navigation drawer and mainWebView.
775 public void onBackPressed() {
776 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
778 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
779 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
780 drawerLayout.closeDrawer(GravityCompat.START);
782 // Load the previous URL if available.
783 if (mainWebView.canGoBack()) {
784 mainWebView.goBack();
786 // Pass onBackPressed to the system.
787 super.onBackPressed();
792 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
793 // Get the text from urlTextBox and convert it to a string.
794 String unformattedUrlString = urlTextBox.getText().toString();
795 URL unformattedUrl = null;
796 Uri.Builder formattedUri = new Uri.Builder();
798 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
799 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
800 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
801 if (!unformattedUrlString.startsWith("http")) {
802 unformattedUrlString = "http://" + unformattedUrlString;
805 // 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.
807 unformattedUrl = new URL(unformattedUrlString);
808 } catch (MalformedURLException e) {
812 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
813 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
814 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
815 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
816 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
817 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
819 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
820 formattedUrlString = formattedUri.build().toString();
822 // Sanitize the search input and convert it to a DuckDuckGo search.
823 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
825 // Use the correct search URL based on javaScriptEnabled.
826 if (javaScriptEnabled) {
827 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
828 } else { // JavaScript is disabled.
829 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
833 mainWebView.loadUrl(formattedUrlString);
835 // Hides the keyboard so we can see the webpage.
836 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
837 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);