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 initial status for the search URLs.
347 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
348 javaScriptDisabledSearchCustomURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
349 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
350 javaScriptEnabledSearchCustomURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
352 // Set homepage initial status. The default value is "https://www.duckduckgo.com".
353 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
355 // Set swipe to refresh initial status. The default is true.
356 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
357 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
360 // Get the intent information that started the app.
361 final Intent intent = getIntent();
363 if (intent.getData() != null) {
364 // Get the intent data and convert it to a string.
365 final Uri intentUriData = intent.getData();
366 formattedUrlString = intentUriData.toString();
369 // If formattedUrlString is null assign the homepage to it.
370 if (formattedUrlString == null) {
371 formattedUrlString = homepage;
374 // Load the initial website.
375 mainWebView.loadUrl(formattedUrlString);
377 // Load the ad if this is the free flavor.
378 BannerAd.requestAd(adView);
382 protected void onNewIntent(Intent intent) {
383 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
386 if (intent.getData() != null) {
387 // Get the intent data and convert it to a string.
388 final Uri intentUriData = intent.getData();
389 formattedUrlString = intentUriData.toString();
392 // Close the navigation drawer if it is open.
393 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
394 drawerLayout.closeDrawer(GravityCompat.START);
398 mainWebView.loadUrl(formattedUrlString);
400 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
401 mainWebView.requestFocus();
405 public boolean onCreateOptionsMenu(Menu menu) {
406 // Inflate the menu; this adds items to the action bar if it is present.
407 getMenuInflater().inflate(R.menu.menu_options, menu);
409 // Set mainMenu so it can be used by onOptionsItemSelected.
412 // Get MenuItems for checkable menu items.
413 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
414 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
415 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
416 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
417 /* toggleSaveFormData does nothing until database storage is implemented.
418 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
421 // Set the initial icon for toggleJavaScript
422 if (javaScriptEnabled) {
423 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
425 if (domStorageEnabled || firstPartyCookiesEnabled) {
426 toggleJavaScript.setIcon(R.drawable.warning);
428 toggleJavaScript.setIcon(R.drawable.privacy_mode);
432 // Set the initial status of the menu item checkboxes.
433 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
434 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
435 toggleDomStorage.setChecked(domStorageEnabled);
436 /* toggleSaveFormData does nothing until database storage is implemented.
437 toggleSaveFormData.setChecked(saveFormDataEnabled);
444 public boolean onPrepareOptionsMenu(Menu menu) {
445 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
446 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
447 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
448 toggleThirdPartyCookies.setEnabled(true);
450 toggleThirdPartyCookies.setEnabled(false);
453 // Enable Clear Cookies if there are any.
454 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
455 clearCookies.setEnabled(cookieManager.hasCookies());
457 // Run all the other default commands.
458 super.onPrepareOptionsMenu(menu);
460 // return true displays the menu.
465 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
466 @SuppressLint("SetJavaScriptEnabled")
467 // removeAllCookies is deprecated, but it is required for API < 21.
468 @SuppressWarnings("deprecation")
469 public boolean onOptionsItemSelected(MenuItem menuItem) {
470 int menuItemId = menuItem.getItemId();
472 // Some options need to update the drawable for toggleJavaScript.
473 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
475 // Set the commands that relate to the menu entries.
476 switch (menuItemId) {
477 case R.id.toggleJavaScript:
478 if (javaScriptEnabled) {
479 javaScriptEnabled = false;
480 mainWebView.getSettings().setJavaScriptEnabled(false);
481 mainWebView.reload();
483 // Update the toggleJavaScript icon and display a snackbar.
484 if (domStorageEnabled || firstPartyCookiesEnabled) {
485 menuItem.setIcon(R.drawable.warning);
486 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
488 menuItem.setIcon(R.drawable.privacy_mode);
489 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
492 javaScriptEnabled = true;
493 menuItem.setIcon(R.drawable.javascript_enabled);
494 mainWebView.getSettings().setJavaScriptEnabled(true);
495 mainWebView.reload();
496 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
500 case R.id.toggleFirstPartyCookies:
501 if (firstPartyCookiesEnabled) {
502 firstPartyCookiesEnabled = false;
503 menuItem.setChecked(false);
504 cookieManager.setAcceptCookie(false);
505 mainWebView.reload();
507 // Update the toggleJavaScript icon if appropriate and display a snackbar.
508 if (!javaScriptEnabled) {
509 if (domStorageEnabled) {
510 toggleJavaScript.setIcon(R.drawable.warning);
511 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
513 toggleJavaScript.setIcon(R.drawable.privacy_mode);
514 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
517 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
520 firstPartyCookiesEnabled = true;
521 menuItem.setChecked(true);
522 cookieManager.setAcceptCookie(true);
523 mainWebView.reload();
525 // Update the toggleJavaScript icon if appropriate.
526 if (!javaScriptEnabled) {
527 toggleJavaScript.setIcon(R.drawable.warning);
528 } // Else do nothing because JavaScript is enabled.
530 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
534 case R.id.toggleThirdPartyCookies:
535 if (Build.VERSION.SDK_INT >= 21) {
536 if (thirdPartyCookiesEnabled) {
537 thirdPartyCookiesEnabled = false;
538 menuItem.setChecked(false);
539 cookieManager.setAcceptThirdPartyCookies(mainWebView, false);
540 mainWebView.reload();
542 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
544 thirdPartyCookiesEnabled = true;
545 menuItem.setChecked(true);
546 cookieManager.setAcceptThirdPartyCookies(mainWebView, true);
547 mainWebView.reload();
549 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
551 } // Else do nothing because SDK < 21.
554 case R.id.toggleDomStorage:
555 if (domStorageEnabled) {
556 domStorageEnabled = false;
557 menuItem.setChecked(false);
558 mainWebView.getSettings().setDomStorageEnabled(false);
559 mainWebView.reload();
561 // Update the toggleJavaScript icon if appropriate and display a snackbar.
562 if (!javaScriptEnabled) {
563 if (firstPartyCookiesEnabled) {
564 toggleJavaScript.setIcon(R.drawable.warning);
565 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
567 toggleJavaScript.setIcon(R.drawable.privacy_mode);
568 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
571 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
574 domStorageEnabled = true;
575 menuItem.setChecked(true);
576 mainWebView.getSettings().setDomStorageEnabled(true);
577 mainWebView.reload();
579 // Update the toggleJavaScript icon if appropriate.
580 if (!javaScriptEnabled) {
581 toggleJavaScript.setIcon(R.drawable.warning);
582 } // Else Do nothing because JavaScript is enabled.
584 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
588 case R.id.clearCookies:
589 if (Build.VERSION.SDK_INT < 21) {
590 cookieManager.removeAllCookie();
592 cookieManager.removeAllCookies(null);
594 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
597 case R.id.clearDomStorage:
598 WebStorage webStorage = WebStorage.getInstance();
599 webStorage.deleteAllData();
600 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
604 Intent shareIntent = new Intent();
605 shareIntent.setAction(Intent.ACTION_SEND);
606 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
607 shareIntent.setType("text/plain");
608 startActivity(Intent.createChooser(shareIntent, "Share URL"));
611 case R.id.addToHomescreen:
612 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
613 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
614 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
616 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
620 mainWebView.reload();
623 return super.onOptionsItemSelected(menuItem);
628 // removeAllCookies is deprecated, but it is required for API < 21.
629 @SuppressWarnings("deprecation")
630 public boolean onNavigationItemSelected(MenuItem menuItem) {
631 int menuItemId = menuItem.getItemId();
633 switch (menuItemId) {
635 mainWebView.loadUrl(homepage);
639 if (mainWebView.canGoBack()) {
640 mainWebView.goBack();
645 if (mainWebView.canGoForward()) {
646 mainWebView.goForward();
651 // Launch the system Download Manager.
652 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
654 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
655 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
657 startActivity(downloadManagerIntent);
661 // Launch PreferenceFragment.
662 Intent intent = new Intent(this, SettingsActivity.class);
663 startActivity(intent);
667 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
668 AppCompatDialogFragment aboutDialog = new AboutDialog();
669 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
672 case R.id.clearAndExit:
673 // Clear DOM storage.
674 WebStorage domStorage = WebStorage.getInstance();
675 domStorage.deleteAllData();
677 // Clear cookies. The commands changed slightly in API 21.
678 if (Build.VERSION.SDK_INT >= 21) {
679 cookieManager.removeAllCookies(null);
681 cookieManager.removeAllCookie();
684 // Destroy the internal state of the webview.
685 mainWebView.destroy();
687 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
688 if (Build.VERSION.SDK_INT >= 21) {
689 finishAndRemoveTask();
699 // Close the navigation drawer.
700 drawerLayout.closeDrawer(GravityCompat.START);
705 public void onPostCreate(Bundle savedInstanceState) {
706 super.onPostCreate(savedInstanceState);
708 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
709 drawerToggle.syncState();
713 public void onConfigurationChanged(Configuration newConfig) {
714 super.onConfigurationChanged(newConfig);
716 // Update the status of the drawerToggle icon.
717 drawerToggle.onConfigurationChanged(newConfig);
721 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
722 // Do nothing because the user selected "Cancel".
726 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
727 // Get shortcutNameEditText from the alert dialog.
728 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
730 // Create the bookmark shortcut based on formattedUrlString.
731 Intent bookmarkShortcut = new Intent();
732 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
733 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
735 // Place the bookmark shortcut on the home screen.
736 Intent placeBookmarkShortcut = new Intent();
737 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
738 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
739 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
740 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
741 sendBroadcast(placeBookmarkShortcut);
744 // Override onBackPressed to handle the navigation drawer and mainWebView.
746 public void onBackPressed() {
747 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
749 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
750 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
751 drawerLayout.closeDrawer(GravityCompat.START);
753 // Load the previous URL if available.
754 if (mainWebView.canGoBack()) {
755 mainWebView.goBack();
757 // Pass onBackPressed to the system.
758 super.onBackPressed();
763 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
764 // Get the text from urlTextBox and convert it to a string.
765 String unformattedUrlString = urlTextBox.getText().toString();
766 URL unformattedUrl = null;
767 Uri.Builder formattedUri = new Uri.Builder();
769 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
770 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
771 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
772 if (!unformattedUrlString.startsWith("http")) {
773 unformattedUrlString = "http://" + unformattedUrlString;
776 // 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.
778 unformattedUrl = new URL(unformattedUrlString);
779 } catch (MalformedURLException e) {
783 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
784 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
785 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
786 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
787 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
788 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
790 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
791 formattedUrlString = formattedUri.build().toString();
793 // Sanitize the search input and convert it to a DuckDuckGo search.
794 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
796 // Use the correct search URL based on javaScriptEnabled.
797 if (javaScriptEnabled) {
798 if (javaScriptEnabledSearchURL.equals("Custom URL")) {
799 formattedUrlString = javaScriptEnabledSearchCustomURL + encodedUrlString;
801 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
803 } else { // JavaScript is disabled.
804 if (javaScriptDisabledSearchURL.equals("Custom URL")) {
805 formattedUrlString = javaScriptDisabledSearchCustomURL + encodedUrlString;
807 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
812 mainWebView.loadUrl(formattedUrlString);
814 // Hides the keyboard so we can see the webpage.
815 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
816 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);