BrowserSettings.java revision ba676ef140a27c03c2ad502bbfa41fbce2d570b3
1 2/* 3 * Copyright (C) 2007 The Android Open Source Project 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18package com.android.browser; 19 20import android.app.ActivityManager; 21import android.content.ContentResolver; 22import android.content.Context; 23import android.content.pm.ActivityInfo; 24import android.content.SharedPreferences; 25import android.content.SharedPreferences.Editor; 26import android.preference.PreferenceActivity; 27import android.preference.PreferenceScreen; 28import android.webkit.CookieManager; 29import android.webkit.GeolocationPermissions; 30import android.webkit.ValueCallback; 31import android.webkit.WebView; 32import android.webkit.WebViewDatabase; 33import android.webkit.WebIconDatabase; 34import android.webkit.WebSettings; 35import android.webkit.WebStorage; 36import android.preference.PreferenceManager; 37import android.provider.Browser; 38 39import java.util.HashMap; 40import java.util.Map; 41import java.util.Set; 42import java.util.Observable; 43 44/* 45 * Package level class for storing various WebView and Browser settings. To use 46 * this class: 47 * BrowserSettings s = BrowserSettings.getInstance(); 48 * s.addObserver(webView.getSettings()); 49 * s.loadFromDb(context); // Only needed on app startup 50 * s.javaScriptEnabled = true; 51 * ... // set any other settings 52 * s.update(); // this will update all the observers 53 * 54 * To remove an observer: 55 * s.deleteObserver(webView.getSettings()); 56 */ 57class BrowserSettings extends Observable { 58 59 // Private variables for settings 60 // NOTE: these defaults need to be kept in sync with the XML 61 // until the performance of PreferenceManager.setDefaultValues() 62 // is improved. 63 // Note: boolean variables are set inside reset function. 64 private boolean loadsImagesAutomatically; 65 private boolean javaScriptEnabled; 66 private WebSettings.PluginState pluginState; 67 private boolean javaScriptCanOpenWindowsAutomatically; 68 private boolean showSecurityWarnings; 69 private boolean rememberPasswords; 70 private boolean saveFormData; 71 private boolean openInBackground; 72 private String defaultTextEncodingName; 73 private String homeUrl = ""; 74 private boolean autoFitPage; 75 private boolean landscapeOnly; 76 private boolean loadsPageInOverviewMode; 77 private boolean showDebugSettings; 78 // HTML5 API flags 79 private boolean appCacheEnabled; 80 private boolean databaseEnabled; 81 private boolean domStorageEnabled; 82 private boolean geolocationEnabled; 83 private boolean workersEnabled; // only affects V8. JSC does not have a similar setting 84 // HTML5 API configuration params 85 private long appCacheMaxSize = Long.MAX_VALUE; 86 private String appCachePath; // default value set in loadFromDb(). 87 private String databasePath; // default value set in loadFromDb() 88 private String geolocationDatabasePath; // default value set in loadFromDb() 89 private WebStorageSizeManager webStorageSizeManager; 90 91 private String jsFlags = ""; 92 93 private final static String TAG = "BrowserSettings"; 94 95 // Development settings 96 public WebSettings.LayoutAlgorithm layoutAlgorithm = 97 WebSettings.LayoutAlgorithm.NARROW_COLUMNS; 98 private boolean useWideViewPort = true; 99 private int userAgent = 0; 100 private boolean tracing = false; 101 private boolean lightTouch = false; 102 private boolean navDump = false; 103 104 // By default the error console is shown once the user navigates to about:debug. 105 // The setting can be then toggled from the settings menu. 106 private boolean showConsole = true; 107 108 // Private preconfigured values 109 private static int minimumFontSize = 8; 110 private static int minimumLogicalFontSize = 8; 111 private static int defaultFontSize = 16; 112 private static int defaultFixedFontSize = 13; 113 private static WebSettings.TextSize textSize = 114 WebSettings.TextSize.NORMAL; 115 private static WebSettings.ZoomDensity zoomDensity = 116 WebSettings.ZoomDensity.MEDIUM; 117 private static int pageCacheCapacity; 118 119 // Preference keys that are used outside this class 120 public final static String PREF_CLEAR_CACHE = "privacy_clear_cache"; 121 public final static String PREF_CLEAR_COOKIES = "privacy_clear_cookies"; 122 public final static String PREF_CLEAR_HISTORY = "privacy_clear_history"; 123 public final static String PREF_HOMEPAGE = "homepage"; 124 public final static String PREF_CLEAR_FORM_DATA = 125 "privacy_clear_form_data"; 126 public final static String PREF_CLEAR_PASSWORDS = 127 "privacy_clear_passwords"; 128 public final static String PREF_EXTRAS_RESET_DEFAULTS = 129 "reset_default_preferences"; 130 public final static String PREF_DEBUG_SETTINGS = "debug_menu"; 131 public final static String PREF_WEBSITE_SETTINGS = "website_settings"; 132 public final static String PREF_TEXT_SIZE = "text_size"; 133 public final static String PREF_DEFAULT_ZOOM = "default_zoom"; 134 public final static String PREF_DEFAULT_TEXT_ENCODING = 135 "default_text_encoding"; 136 public final static String PREF_CLEAR_GEOLOCATION_ACCESS = 137 "privacy_clear_geolocation_access"; 138 139 private static final String DESKTOP_USERAGENT = "Mozilla/5.0 (Macintosh; " + 140 "U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.17 (KHTML, " + 141 "like Gecko) Version/4.0 Safari/530.17"; 142 143 private static final String IPHONE_USERAGENT = "Mozilla/5.0 (iPhone; U; " + 144 "CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 " + 145 "(KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"; 146 147 // Value to truncate strings when adding them to a TextView within 148 // a ListView 149 public final static int MAX_TEXTVIEW_LEN = 80; 150 151 private TabControl mTabControl; 152 153 // Single instance of the BrowserSettings for use in the Browser app. 154 private static BrowserSettings sSingleton; 155 156 // Private map of WebSettings to Observer objects used when deleting an 157 // observer. 158 private HashMap<WebSettings,Observer> mWebSettingsToObservers = 159 new HashMap<WebSettings,Observer>(); 160 161 /* 162 * An observer wrapper for updating a WebSettings object with the new 163 * settings after a call to BrowserSettings.update(). 164 */ 165 static class Observer implements java.util.Observer { 166 // Private WebSettings object that will be updated. 167 private WebSettings mSettings; 168 169 Observer(WebSettings w) { 170 mSettings = w; 171 } 172 173 public void update(Observable o, Object arg) { 174 BrowserSettings b = (BrowserSettings)o; 175 WebSettings s = mSettings; 176 177 s.setLayoutAlgorithm(b.layoutAlgorithm); 178 if (b.userAgent == 0) { 179 // use the default ua string 180 s.setUserAgentString(null); 181 } else if (b.userAgent == 1) { 182 s.setUserAgentString(DESKTOP_USERAGENT); 183 } else if (b.userAgent == 2) { 184 s.setUserAgentString(IPHONE_USERAGENT); 185 } 186 s.setUseWideViewPort(b.useWideViewPort); 187 s.setLoadsImagesAutomatically(b.loadsImagesAutomatically); 188 s.setJavaScriptEnabled(b.javaScriptEnabled); 189 s.setPluginState(b.pluginState); 190 s.setJavaScriptCanOpenWindowsAutomatically( 191 b.javaScriptCanOpenWindowsAutomatically); 192 s.setDefaultTextEncodingName(b.defaultTextEncodingName); 193 s.setMinimumFontSize(b.minimumFontSize); 194 s.setMinimumLogicalFontSize(b.minimumLogicalFontSize); 195 s.setDefaultFontSize(b.defaultFontSize); 196 s.setDefaultFixedFontSize(b.defaultFixedFontSize); 197 s.setNavDump(b.navDump); 198 s.setTextSize(b.textSize); 199 s.setDefaultZoom(b.zoomDensity); 200 s.setLightTouchEnabled(b.lightTouch); 201 s.setSaveFormData(b.saveFormData); 202 s.setSavePassword(b.rememberPasswords); 203 s.setLoadWithOverviewMode(b.loadsPageInOverviewMode); 204 s.setPageCacheCapacity(pageCacheCapacity); 205 206 // WebView inside Browser doesn't want initial focus to be set. 207 s.setNeedInitialFocus(false); 208 // Browser supports multiple windows 209 s.setSupportMultipleWindows(true); 210 // Use internal pattern for over scroll background 211 s.setUseWebViewBackgroundForOverscrollBackground(false); 212 213 // HTML5 API flags 214 s.setAppCacheEnabled(b.appCacheEnabled); 215 s.setDatabaseEnabled(b.databaseEnabled); 216 s.setDomStorageEnabled(b.domStorageEnabled); 217 s.setWorkersEnabled(b.workersEnabled); // This only affects V8. 218 s.setGeolocationEnabled(b.geolocationEnabled); 219 220 // HTML5 configuration parameters. 221 s.setAppCacheMaxSize(b.appCacheMaxSize); 222 s.setAppCachePath(b.appCachePath); 223 s.setDatabasePath(b.databasePath); 224 s.setGeolocationDatabasePath(b.geolocationDatabasePath); 225 226 b.updateTabControlSettings(); 227 } 228 } 229 230 /** 231 * Load settings from the browser app's database. 232 * NOTE: Strings used for the preferences must match those specified 233 * in the browser_preferences.xml 234 * @param ctx A Context object used to query the browser's settings 235 * database. If the database exists, the saved settings will be 236 * stored in this BrowserSettings object. This will update all 237 * observers of this object. 238 */ 239 public void loadFromDb(Context ctx) { 240 SharedPreferences p = 241 PreferenceManager.getDefaultSharedPreferences(ctx); 242 // Set the default value for the Application Caches path. 243 appCachePath = ctx.getDir("appcache", 0).getPath(); 244 // Determine the maximum size of the application cache. 245 webStorageSizeManager = new WebStorageSizeManager( 246 ctx, 247 new WebStorageSizeManager.StatFsDiskInfo(appCachePath), 248 new WebStorageSizeManager.WebKitAppCacheInfo(appCachePath)); 249 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize(); 250 // Set the default value for the Database path. 251 databasePath = ctx.getDir("databases", 0).getPath(); 252 // Set the default value for the Geolocation database path. 253 geolocationDatabasePath = ctx.getDir("geolocation", 0).getPath(); 254 255 homeUrl = getFactoryResetHomeUrl(ctx); 256 257 // the cost of one cached page is ~3M (measured using nytimes.com). For 258 // low end devices, we only cache one page. For high end devices, we try 259 // to cache more pages, currently choose 5. 260 ActivityManager am = (ActivityManager) ctx 261 .getSystemService(Context.ACTIVITY_SERVICE); 262 if (am.getMemoryClass() > 16) { 263 pageCacheCapacity = 5; 264 } else { 265 pageCacheCapacity = 1; 266 } 267 268 // Load the defaults from the xml 269 // This call is TOO SLOW, need to manually keep the defaults 270 // in sync 271 //PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences); 272 syncSharedPreferences(p); 273 } 274 275 /* package */ void syncSharedPreferences(SharedPreferences p) { 276 277 homeUrl = 278 p.getString(PREF_HOMEPAGE, homeUrl); 279 280 loadsImagesAutomatically = p.getBoolean("load_images", 281 loadsImagesAutomatically); 282 javaScriptEnabled = p.getBoolean("enable_javascript", 283 javaScriptEnabled); 284 pluginState = WebSettings.PluginState.valueOf( 285 p.getString("plugin_state", pluginState.name())); 286 javaScriptCanOpenWindowsAutomatically = !p.getBoolean( 287 "block_popup_windows", 288 !javaScriptCanOpenWindowsAutomatically); 289 showSecurityWarnings = p.getBoolean("show_security_warnings", 290 showSecurityWarnings); 291 rememberPasswords = p.getBoolean("remember_passwords", 292 rememberPasswords); 293 saveFormData = p.getBoolean("save_formdata", 294 saveFormData); 295 boolean accept_cookies = p.getBoolean("accept_cookies", 296 CookieManager.getInstance().acceptCookie()); 297 CookieManager.getInstance().setAcceptCookie(accept_cookies); 298 openInBackground = p.getBoolean("open_in_background", openInBackground); 299 textSize = WebSettings.TextSize.valueOf( 300 p.getString(PREF_TEXT_SIZE, textSize.name())); 301 zoomDensity = WebSettings.ZoomDensity.valueOf( 302 p.getString(PREF_DEFAULT_ZOOM, zoomDensity.name())); 303 autoFitPage = p.getBoolean("autofit_pages", autoFitPage); 304 loadsPageInOverviewMode = p.getBoolean("load_page", 305 loadsPageInOverviewMode); 306 boolean landscapeOnlyTemp = 307 p.getBoolean("landscape_only", landscapeOnly); 308 if (landscapeOnlyTemp != landscapeOnly) { 309 landscapeOnly = landscapeOnlyTemp; 310 } 311 useWideViewPort = true; // use wide view port for either setting 312 if (autoFitPage) { 313 layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS; 314 } else { 315 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL; 316 } 317 defaultTextEncodingName = 318 p.getString(PREF_DEFAULT_TEXT_ENCODING, 319 defaultTextEncodingName); 320 321 showDebugSettings = 322 p.getBoolean(PREF_DEBUG_SETTINGS, showDebugSettings); 323 // Debug menu items have precidence if the menu is visible 324 if (showDebugSettings) { 325 boolean small_screen = p.getBoolean("small_screen", 326 layoutAlgorithm == 327 WebSettings.LayoutAlgorithm.SINGLE_COLUMN); 328 if (small_screen) { 329 layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN; 330 } else { 331 boolean normal_layout = p.getBoolean("normal_layout", 332 layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL); 333 if (normal_layout) { 334 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL; 335 } else { 336 layoutAlgorithm = 337 WebSettings.LayoutAlgorithm.NARROW_COLUMNS; 338 } 339 } 340 useWideViewPort = p.getBoolean("wide_viewport", useWideViewPort); 341 tracing = p.getBoolean("enable_tracing", tracing); 342 lightTouch = p.getBoolean("enable_light_touch", lightTouch); 343 navDump = p.getBoolean("enable_nav_dump", navDump); 344 userAgent = Integer.parseInt(p.getString("user_agent", "0")); 345 } 346 // JS flags is loaded from DB even if showDebugSettings is false, 347 // so that it can be set once and be effective all the time. 348 jsFlags = p.getString("js_engine_flags", ""); 349 350 // Read the setting for showing/hiding the JS Console always so that should the 351 // user enable debug settings, we already know if we should show the console. 352 // The user will never see the console unless they navigate to about:debug, 353 // regardless of the setting we read here. This setting is only used after debug 354 // is enabled. 355 showConsole = p.getBoolean("javascript_console", showConsole); 356 357 // HTML5 API flags 358 appCacheEnabled = p.getBoolean("enable_appcache", appCacheEnabled); 359 databaseEnabled = p.getBoolean("enable_database", databaseEnabled); 360 domStorageEnabled = p.getBoolean("enable_domstorage", domStorageEnabled); 361 geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled); 362 workersEnabled = p.getBoolean("enable_workers", workersEnabled); 363 364 update(); 365 } 366 367 public String getHomePage() { 368 return homeUrl; 369 } 370 371 public String getJsFlags() { 372 return jsFlags; 373 } 374 375 public WebStorageSizeManager getWebStorageSizeManager() { 376 return webStorageSizeManager; 377 } 378 379 public void setHomePage(Context context, String url) { 380 Editor ed = PreferenceManager. 381 getDefaultSharedPreferences(context).edit(); 382 ed.putString(PREF_HOMEPAGE, url); 383 ed.commit(); 384 homeUrl = url; 385 } 386 387 public WebSettings.TextSize getTextSize() { 388 return textSize; 389 } 390 391 public WebSettings.ZoomDensity getDefaultZoom() { 392 return zoomDensity; 393 } 394 395 public boolean openInBackground() { 396 return openInBackground; 397 } 398 399 public boolean showSecurityWarnings() { 400 return showSecurityWarnings; 401 } 402 403 public boolean isTracing() { 404 return tracing; 405 } 406 407 public boolean isLightTouch() { 408 return lightTouch; 409 } 410 411 public boolean isNavDump() { 412 return navDump; 413 } 414 415 public boolean showDebugSettings() { 416 return showDebugSettings; 417 } 418 419 public void toggleDebugSettings() { 420 showDebugSettings = !showDebugSettings; 421 navDump = showDebugSettings; 422 update(); 423 } 424 425 /** 426 * Add a WebSettings object to the list of observers that will be updated 427 * when update() is called. 428 * 429 * @param s A WebSettings object that is strictly tied to the life of a 430 * WebView. 431 */ 432 public Observer addObserver(WebSettings s) { 433 Observer old = mWebSettingsToObservers.get(s); 434 if (old != null) { 435 super.deleteObserver(old); 436 } 437 Observer o = new Observer(s); 438 mWebSettingsToObservers.put(s, o); 439 super.addObserver(o); 440 return o; 441 } 442 443 /** 444 * Delete the given WebSettings observer from the list of observers. 445 * @param s The WebSettings object to be deleted. 446 */ 447 public void deleteObserver(WebSettings s) { 448 Observer o = mWebSettingsToObservers.get(s); 449 if (o != null) { 450 mWebSettingsToObservers.remove(s); 451 super.deleteObserver(o); 452 } 453 } 454 455 /* 456 * Package level method for obtaining a single app instance of the 457 * BrowserSettings. 458 */ 459 /*package*/ static BrowserSettings getInstance() { 460 if (sSingleton == null ) { 461 sSingleton = new BrowserSettings(); 462 } 463 return sSingleton; 464 } 465 466 /* 467 * Package level method for associating the BrowserSettings with TabControl 468 */ 469 /* package */void setTabControl(TabControl tabControl) { 470 mTabControl = tabControl; 471 updateTabControlSettings(); 472 } 473 474 /* 475 * Update all the observers of the object. 476 */ 477 /*package*/ void update() { 478 setChanged(); 479 notifyObservers(); 480 } 481 482 /*package*/ void clearCache(Context context) { 483 WebIconDatabase.getInstance().removeAllIcons(); 484 if (mTabControl != null) { 485 WebView current = mTabControl.getCurrentWebView(); 486 if (current != null) { 487 current.clearCache(true); 488 } 489 } 490 } 491 492 /*package*/ void clearCookies(Context context) { 493 CookieManager.getInstance().removeAllCookie(); 494 } 495 496 /* package */void clearHistory(Context context) { 497 ContentResolver resolver = context.getContentResolver(); 498 Browser.clearHistory(resolver); 499 Browser.clearSearches(resolver); 500 } 501 502 /* package */ void clearFormData(Context context) { 503 WebViewDatabase.getInstance(context).clearFormData(); 504 if (mTabControl != null) { 505 mTabControl.getCurrentTopWebView().clearFormData(); 506 } 507 } 508 509 /*package*/ void clearPasswords(Context context) { 510 WebViewDatabase db = WebViewDatabase.getInstance(context); 511 db.clearUsernamePassword(); 512 db.clearHttpAuthUsernamePassword(); 513 } 514 515 private void updateTabControlSettings() { 516 // Enable/disable the error console. 517 mTabControl.getBrowserActivity().setShouldShowErrorConsole( 518 showDebugSettings && showConsole); 519 mTabControl.getBrowserActivity().setRequestedOrientation( 520 landscapeOnly ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE 521 : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 522 } 523 524 private void maybeDisableWebsiteSettings(Context context) { 525 PreferenceActivity activity = (PreferenceActivity) context; 526 final PreferenceScreen screen = (PreferenceScreen) 527 activity.findPreference(BrowserSettings.PREF_WEBSITE_SETTINGS); 528 screen.setEnabled(false); 529 WebStorage.getInstance().getOrigins(new ValueCallback<Map>() { 530 public void onReceiveValue(Map webStorageOrigins) { 531 if ((webStorageOrigins != null) && !webStorageOrigins.isEmpty()) { 532 screen.setEnabled(true); 533 } 534 } 535 }); 536 537 GeolocationPermissions.getInstance().getOrigins(new ValueCallback<Set<String> >() { 538 public void onReceiveValue(Set<String> geolocationOrigins) { 539 if ((geolocationOrigins != null) && !geolocationOrigins.isEmpty()) { 540 screen.setEnabled(true); 541 } 542 } 543 }); 544 } 545 546 /*package*/ void clearDatabases(Context context) { 547 WebStorage.getInstance().deleteAllData(); 548 maybeDisableWebsiteSettings(context); 549 } 550 551 /*package*/ void clearLocationAccess(Context context) { 552 GeolocationPermissions.getInstance().clearAll(); 553 maybeDisableWebsiteSettings(context); 554 } 555 556 /*package*/ void resetDefaultPreferences(Context ctx) { 557 reset(); 558 SharedPreferences p = 559 PreferenceManager.getDefaultSharedPreferences(ctx); 560 p.edit().clear().commit(); 561 PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences, 562 true); 563 // reset homeUrl 564 setHomePage(ctx, getFactoryResetHomeUrl(ctx)); 565 // reset appcache max size 566 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize(); 567 } 568 569 private String getFactoryResetHomeUrl(Context context) { 570 String url = context.getResources().getString(R.string.homepage_base); 571 if (url.indexOf("{CID}") != -1) { 572 url = url.replace("{CID}", 573 BrowserProvider.getClientId(context.getContentResolver())); 574 } 575 return url; 576 } 577 578 // Private constructor that does nothing. 579 private BrowserSettings() { 580 reset(); 581 } 582 583 private void reset() { 584 // Private variables for settings 585 // NOTE: these defaults need to be kept in sync with the XML 586 // until the performance of PreferenceManager.setDefaultValues() 587 // is improved. 588 loadsImagesAutomatically = true; 589 javaScriptEnabled = true; 590 pluginState = WebSettings.PluginState.ON; 591 javaScriptCanOpenWindowsAutomatically = false; 592 showSecurityWarnings = true; 593 rememberPasswords = true; 594 saveFormData = true; 595 openInBackground = false; 596 autoFitPage = true; 597 landscapeOnly = false; 598 loadsPageInOverviewMode = true; 599 showDebugSettings = false; 600 // HTML5 API flags 601 appCacheEnabled = true; 602 databaseEnabled = true; 603 domStorageEnabled = true; 604 geolocationEnabled = true; 605 workersEnabled = true; // only affects V8. JSC does not have a similar setting 606 } 607} 608