3 * Copyright (C) 2007 The Android Open Source Project
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package com.android.browser;
20 import com.android.browser.search.SearchEngine;
21 import com.android.browser.search.SearchEngines;
23 import android.app.ActivityManager;
24 import android.content.ComponentName;
25 import android.content.ContentResolver;
26 import android.content.Context;
27 import android.content.pm.ActivityInfo;
28 import android.content.SharedPreferences;
29 import android.content.SharedPreferences.Editor;
30 import android.database.ContentObserver;
31 import android.os.Handler;
32 import android.preference.PreferenceActivity;
33 import android.preference.PreferenceScreen;
34 import android.provider.Settings;
35 import android.util.Log;
36 import android.webkit.CookieManager;
37 import android.webkit.GeolocationPermissions;
38 import android.webkit.ValueCallback;
39 import android.webkit.WebView;
40 import android.webkit.WebViewDatabase;
41 import android.webkit.WebIconDatabase;
42 import android.webkit.WebSettings;
43 import android.webkit.WebStorage;
44 import android.preference.PreferenceManager;
45 import android.provider.Browser;
47 import java.util.HashMap;
50 import java.util.Observable;
53 * Package level class for storing various WebView and Browser settings. To use
55 * BrowserSettings s = BrowserSettings.getInstance();
56 * s.addObserver(webView.getSettings());
57 * s.loadFromDb(context); // Only needed on app startup
58 * s.javaScriptEnabled = true;
59 * ... // set any other settings
60 * s.update(); // this will update all the observers
62 * To remove an observer:
63 * s.deleteObserver(webView.getSettings());
65 class BrowserSettings extends Observable {
67 // Private variables for settings
68 // NOTE: these defaults need to be kept in sync with the XML
69 // until the performance of PreferenceManager.setDefaultValues()
71 // Note: boolean variables are set inside reset function.
72 private boolean loadsImagesAutomatically;
73 private boolean javaScriptEnabled;
74 private WebSettings.PluginState pluginState;
75 private boolean javaScriptCanOpenWindowsAutomatically;
76 private boolean showSecurityWarnings;
77 private boolean rememberPasswords;
78 private boolean saveFormData;
79 private boolean openInBackground;
80 private String defaultTextEncodingName;
81 private String homeUrl = "";
82 private SearchEngine searchEngine;
83 private boolean showSearchSuggestions;
84 private boolean autoFitPage;
85 private boolean landscapeOnly;
86 private boolean loadsPageInOverviewMode;
87 private boolean showDebugSettings;
89 private boolean appCacheEnabled;
90 private boolean databaseEnabled;
91 private boolean domStorageEnabled;
92 private boolean geolocationEnabled;
93 private boolean workersEnabled; // only affects V8. JSC does not have a similar setting
94 // HTML5 API configuration params
95 private long appCacheMaxSize = Long.MAX_VALUE;
96 private String appCachePath; // default value set in loadFromDb().
97 private String databasePath; // default value set in loadFromDb()
98 private String geolocationDatabasePath; // default value set in loadFromDb()
99 private WebStorageSizeManager webStorageSizeManager;
101 private String jsFlags = "";
103 private final static String TAG = "BrowserSettings";
105 // Development settings
106 public WebSettings.LayoutAlgorithm layoutAlgorithm =
107 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
108 private boolean useWideViewPort = true;
109 private int userAgent = 0;
110 private boolean tracing = false;
111 private boolean lightTouch = false;
112 private boolean navDump = false;
114 // By default the error console is shown once the user navigates to about:debug.
115 // The setting can be then toggled from the settings menu.
116 private boolean showConsole = true;
118 // Private preconfigured values
119 private static int minimumFontSize = 8;
120 private static int minimumLogicalFontSize = 8;
121 private static int defaultFontSize = 16;
122 private static int defaultFixedFontSize = 13;
123 private static WebSettings.TextSize textSize =
124 WebSettings.TextSize.NORMAL;
125 private static WebSettings.ZoomDensity zoomDensity =
126 WebSettings.ZoomDensity.MEDIUM;
127 private static int pageCacheCapacity;
129 // Preference keys that are used outside this class
130 public final static String PREF_CLEAR_CACHE = "privacy_clear_cache";
131 public final static String PREF_CLEAR_COOKIES = "privacy_clear_cookies";
132 public final static String PREF_CLEAR_HISTORY = "privacy_clear_history";
133 public final static String PREF_HOMEPAGE = "homepage";
134 public final static String PREF_SEARCH_ENGINE = "search_engine";
135 public final static String PREF_SHOW_SEARCH_SUGGESTIONS = "show_search_suggestions";
136 public final static String PREF_CLEAR_FORM_DATA =
137 "privacy_clear_form_data";
138 public final static String PREF_CLEAR_PASSWORDS =
139 "privacy_clear_passwords";
140 public final static String PREF_EXTRAS_RESET_DEFAULTS =
141 "reset_default_preferences";
142 public final static String PREF_DEBUG_SETTINGS = "debug_menu";
143 public final static String PREF_WEBSITE_SETTINGS = "website_settings";
144 public final static String PREF_TEXT_SIZE = "text_size";
145 public final static String PREF_DEFAULT_ZOOM = "default_zoom";
146 public final static String PREF_DEFAULT_TEXT_ENCODING =
147 "default_text_encoding";
148 public final static String PREF_CLEAR_GEOLOCATION_ACCESS =
149 "privacy_clear_geolocation_access";
151 private static final String DESKTOP_USERAGENT = "Mozilla/5.0 (Macintosh; " +
152 "U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.17 (KHTML, " +
153 "like Gecko) Version/4.0 Safari/530.17";
155 private static final String IPHONE_USERAGENT = "Mozilla/5.0 (iPhone; U; " +
156 "CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 " +
157 "(KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";
159 // Value to truncate strings when adding them to a TextView within
161 public final static int MAX_TEXTVIEW_LEN = 80;
163 private TabControl mTabControl;
165 // Single instance of the BrowserSettings for use in the Browser app.
166 private static BrowserSettings sSingleton;
168 // Private map of WebSettings to Observer objects used when deleting an
170 private HashMap<WebSettings,Observer> mWebSettingsToObservers =
171 new HashMap<WebSettings,Observer>();
174 * An observer wrapper for updating a WebSettings object with the new
175 * settings after a call to BrowserSettings.update().
177 static class Observer implements java.util.Observer {
178 // Private WebSettings object that will be updated.
179 private WebSettings mSettings;
181 Observer(WebSettings w) {
185 public void update(Observable o, Object arg) {
186 BrowserSettings b = (BrowserSettings)o;
187 WebSettings s = mSettings;
189 s.setLayoutAlgorithm(b.layoutAlgorithm);
190 if (b.userAgent == 0) {
191 // use the default ua string
192 s.setUserAgentString(null);
193 } else if (b.userAgent == 1) {
194 s.setUserAgentString(DESKTOP_USERAGENT);
195 } else if (b.userAgent == 2) {
196 s.setUserAgentString(IPHONE_USERAGENT);
198 s.setUseWideViewPort(b.useWideViewPort);
199 s.setLoadsImagesAutomatically(b.loadsImagesAutomatically);
200 s.setJavaScriptEnabled(b.javaScriptEnabled);
201 s.setPluginState(b.pluginState);
202 s.setJavaScriptCanOpenWindowsAutomatically(
203 b.javaScriptCanOpenWindowsAutomatically);
204 s.setDefaultTextEncodingName(b.defaultTextEncodingName);
205 s.setMinimumFontSize(b.minimumFontSize);
206 s.setMinimumLogicalFontSize(b.minimumLogicalFontSize);
207 s.setDefaultFontSize(b.defaultFontSize);
208 s.setDefaultFixedFontSize(b.defaultFixedFontSize);
209 s.setNavDump(b.navDump);
210 s.setTextSize(b.textSize);
211 s.setDefaultZoom(b.zoomDensity);
212 s.setLightTouchEnabled(b.lightTouch);
213 s.setSaveFormData(b.saveFormData);
214 s.setSavePassword(b.rememberPasswords);
215 s.setLoadWithOverviewMode(b.loadsPageInOverviewMode);
216 s.setPageCacheCapacity(pageCacheCapacity);
218 // WebView inside Browser doesn't want initial focus to be set.
219 s.setNeedInitialFocus(false);
220 // Browser supports multiple windows
221 s.setSupportMultipleWindows(true);
224 s.setAppCacheEnabled(b.appCacheEnabled);
225 s.setDatabaseEnabled(b.databaseEnabled);
226 s.setDomStorageEnabled(b.domStorageEnabled);
227 s.setWorkersEnabled(b.workersEnabled); // This only affects V8.
228 s.setGeolocationEnabled(b.geolocationEnabled);
230 // HTML5 configuration parameters.
231 s.setAppCacheMaxSize(b.appCacheMaxSize);
232 s.setAppCachePath(b.appCachePath);
233 s.setDatabasePath(b.databasePath);
234 s.setGeolocationDatabasePath(b.geolocationDatabasePath);
236 b.updateTabControlSettings();
241 * Load settings from the browser app's database.
242 * NOTE: Strings used for the preferences must match those specified
243 * in the browser_preferences.xml
244 * @param ctx A Context object used to query the browser's settings
245 * database. If the database exists, the saved settings will be
246 * stored in this BrowserSettings object. This will update all
247 * observers of this object.
249 public void loadFromDb(final Context ctx) {
250 SharedPreferences p =
251 PreferenceManager.getDefaultSharedPreferences(ctx);
252 // Set the default value for the Application Caches path.
253 appCachePath = ctx.getDir("appcache", 0).getPath();
254 // Determine the maximum size of the application cache.
255 webStorageSizeManager = new WebStorageSizeManager(
257 new WebStorageSizeManager.StatFsDiskInfo(appCachePath),
258 new WebStorageSizeManager.WebKitAppCacheInfo(appCachePath));
259 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
260 // Set the default value for the Database path.
261 databasePath = ctx.getDir("databases", 0).getPath();
262 // Set the default value for the Geolocation database path.
263 geolocationDatabasePath = ctx.getDir("geolocation", 0).getPath();
265 if (p.getString(PREF_HOMEPAGE, "") == "") {
266 // No home page preferences is set, set it to default.
267 setHomePage(ctx, getFactoryResetHomeUrl(ctx));
270 // the cost of one cached page is ~3M (measured using nytimes.com). For
271 // low end devices, we only cache one page. For high end devices, we try
272 // to cache more pages, currently choose 5.
273 ActivityManager am = (ActivityManager) ctx
274 .getSystemService(Context.ACTIVITY_SERVICE);
275 if (am.getMemoryClass() > 16) {
276 pageCacheCapacity = 5;
278 pageCacheCapacity = 1;
281 final ContentResolver cr = ctx.getContentResolver();
282 cr.registerContentObserver(
283 Settings.System.getUriFor(Settings.System.SHOW_WEB_SUGGESTIONS), false,
284 new ContentObserver(new Handler()) {
286 public void onChange(boolean selfChange) {
287 SharedPreferences p =
288 PreferenceManager.getDefaultSharedPreferences(ctx);
289 updateShowWebSuggestions(cr, p);
292 updateShowWebSuggestions(cr, p);
294 // Load the defaults from the xml
295 // This call is TOO SLOW, need to manually keep the defaults
297 //PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences);
298 syncSharedPreferences(ctx, p);
301 /* package */ void syncSharedPreferences(Context ctx, SharedPreferences p) {
304 p.getString(PREF_HOMEPAGE, homeUrl);
305 String searchEngineName = p.getString(PREF_SEARCH_ENGINE,
306 SearchEngine.GOOGLE);
307 if (searchEngine == null || !searchEngine.getName().equals(searchEngineName)) {
308 if (searchEngine != null) {
309 if (searchEngine.supportsVoiceSearch()) {
310 // One or more tabs could have been in voice search mode.
311 // Clear it, since the new SearchEngine may not support
312 // it, or may handle it differently.
313 for (int i = 0; i < mTabControl.getTabCount(); i++) {
314 mTabControl.getTab(i).revertVoiceSearchMode();
317 searchEngine.close();
319 searchEngine = SearchEngines.get(ctx, searchEngineName);
321 Log.i(TAG, "Selected search engine: " + searchEngine);
322 showSearchSuggestions = p.getBoolean(PREF_SHOW_SEARCH_SUGGESTIONS, true);
323 // Persist to system settings
324 saveShowWebSuggestions(ctx.getContentResolver());
326 loadsImagesAutomatically = p.getBoolean("load_images",
327 loadsImagesAutomatically);
328 javaScriptEnabled = p.getBoolean("enable_javascript",
330 pluginState = WebSettings.PluginState.valueOf(
331 p.getString("plugin_state", pluginState.name()));
332 javaScriptCanOpenWindowsAutomatically = !p.getBoolean(
333 "block_popup_windows",
334 !javaScriptCanOpenWindowsAutomatically);
335 showSecurityWarnings = p.getBoolean("show_security_warnings",
336 showSecurityWarnings);
337 rememberPasswords = p.getBoolean("remember_passwords",
339 saveFormData = p.getBoolean("save_formdata",
341 boolean accept_cookies = p.getBoolean("accept_cookies",
342 CookieManager.getInstance().acceptCookie());
343 CookieManager.getInstance().setAcceptCookie(accept_cookies);
344 openInBackground = p.getBoolean("open_in_background", openInBackground);
345 textSize = WebSettings.TextSize.valueOf(
346 p.getString(PREF_TEXT_SIZE, textSize.name()));
347 zoomDensity = WebSettings.ZoomDensity.valueOf(
348 p.getString(PREF_DEFAULT_ZOOM, zoomDensity.name()));
349 autoFitPage = p.getBoolean("autofit_pages", autoFitPage);
350 loadsPageInOverviewMode = p.getBoolean("load_page",
351 loadsPageInOverviewMode);
352 boolean landscapeOnlyTemp =
353 p.getBoolean("landscape_only", landscapeOnly);
354 if (landscapeOnlyTemp != landscapeOnly) {
355 landscapeOnly = landscapeOnlyTemp;
357 useWideViewPort = true; // use wide view port for either setting
359 layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
361 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
363 defaultTextEncodingName =
364 p.getString(PREF_DEFAULT_TEXT_ENCODING,
365 defaultTextEncodingName);
368 p.getBoolean(PREF_DEBUG_SETTINGS, showDebugSettings);
369 // Debug menu items have precidence if the menu is visible
370 if (showDebugSettings) {
371 boolean small_screen = p.getBoolean("small_screen",
373 WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
375 layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
377 boolean normal_layout = p.getBoolean("normal_layout",
378 layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
380 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
383 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
386 useWideViewPort = p.getBoolean("wide_viewport", useWideViewPort);
387 tracing = p.getBoolean("enable_tracing", tracing);
388 lightTouch = p.getBoolean("enable_light_touch", lightTouch);
389 navDump = p.getBoolean("enable_nav_dump", navDump);
390 userAgent = Integer.parseInt(p.getString("user_agent", "0"));
392 // JS flags is loaded from DB even if showDebugSettings is false,
393 // so that it can be set once and be effective all the time.
394 jsFlags = p.getString("js_engine_flags", "");
396 // Read the setting for showing/hiding the JS Console always so that should the
397 // user enable debug settings, we already know if we should show the console.
398 // The user will never see the console unless they navigate to about:debug,
399 // regardless of the setting we read here. This setting is only used after debug
401 showConsole = p.getBoolean("javascript_console", showConsole);
404 appCacheEnabled = p.getBoolean("enable_appcache", appCacheEnabled);
405 databaseEnabled = p.getBoolean("enable_database", databaseEnabled);
406 domStorageEnabled = p.getBoolean("enable_domstorage", domStorageEnabled);
407 geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled);
408 workersEnabled = p.getBoolean("enable_workers", workersEnabled);
413 private void saveShowWebSuggestions(ContentResolver cr) {
414 int value = showSearchSuggestions ? 1 : 0;
415 Settings.System.putInt(cr, Settings.System.SHOW_WEB_SUGGESTIONS, value);
418 private void updateShowWebSuggestions(ContentResolver cr, SharedPreferences p) {
419 showSearchSuggestions =
420 Settings.System.getInt(cr,
421 Settings.System.SHOW_WEB_SUGGESTIONS, 1) == 1;
422 p.edit().putBoolean(PREF_SHOW_SEARCH_SUGGESTIONS, showSearchSuggestions).commit();
425 public String getHomePage() {
429 public SearchEngine getSearchEngine() {
433 public boolean getShowSearchSuggestions() {
434 return showSearchSuggestions;
437 public String getJsFlags() {
441 public WebStorageSizeManager getWebStorageSizeManager() {
442 return webStorageSizeManager;
445 public void setHomePage(Context context, String url) {
446 Editor ed = PreferenceManager.
447 getDefaultSharedPreferences(context).edit();
448 ed.putString(PREF_HOMEPAGE, url);
453 public WebSettings.TextSize getTextSize() {
457 public WebSettings.ZoomDensity getDefaultZoom() {
461 public boolean openInBackground() {
462 return openInBackground;
465 public boolean showSecurityWarnings() {
466 return showSecurityWarnings;
469 public boolean isTracing() {
473 public boolean isLightTouch() {
477 public boolean isNavDump() {
481 public boolean showDebugSettings() {
482 return showDebugSettings;
485 public void toggleDebugSettings() {
486 showDebugSettings = !showDebugSettings;
487 navDump = showDebugSettings;
492 * Add a WebSettings object to the list of observers that will be updated
493 * when update() is called.
495 * @param s A WebSettings object that is strictly tied to the life of a
498 public Observer addObserver(WebSettings s) {
499 Observer old = mWebSettingsToObservers.get(s);
501 super.deleteObserver(old);
503 Observer o = new Observer(s);
504 mWebSettingsToObservers.put(s, o);
505 super.addObserver(o);
510 * Delete the given WebSettings observer from the list of observers.
511 * @param s The WebSettings object to be deleted.
513 public void deleteObserver(WebSettings s) {
514 Observer o = mWebSettingsToObservers.get(s);
516 mWebSettingsToObservers.remove(s);
517 super.deleteObserver(o);
522 * Package level method for obtaining a single app instance of the
525 /*package*/ static BrowserSettings getInstance() {
526 if (sSingleton == null ) {
527 sSingleton = new BrowserSettings();
533 * Package level method for associating the BrowserSettings with TabControl
535 /* package */void setTabControl(TabControl tabControl) {
536 mTabControl = tabControl;
537 updateTabControlSettings();
541 * Update all the observers of the object.
543 /*package*/ void update() {
548 /*package*/ void clearCache(Context context) {
549 WebIconDatabase.getInstance().removeAllIcons();
550 if (mTabControl != null) {
551 WebView current = mTabControl.getCurrentWebView();
552 if (current != null) {
553 current.clearCache(true);
558 /*package*/ void clearCookies(Context context) {
559 CookieManager.getInstance().removeAllCookie();
562 /* package */void clearHistory(Context context) {
563 ContentResolver resolver = context.getContentResolver();
564 Browser.clearHistory(resolver);
565 Browser.clearSearches(resolver);
568 /* package */ void clearFormData(Context context) {
569 WebViewDatabase.getInstance(context).clearFormData();
570 if (mTabControl != null) {
571 mTabControl.getCurrentTopWebView().clearFormData();
575 /*package*/ void clearPasswords(Context context) {
576 WebViewDatabase db = WebViewDatabase.getInstance(context);
577 db.clearUsernamePassword();
578 db.clearHttpAuthUsernamePassword();
581 private void updateTabControlSettings() {
582 // Enable/disable the error console.
583 mTabControl.getBrowserActivity().setShouldShowErrorConsole(
584 showDebugSettings && showConsole);
585 mTabControl.getBrowserActivity().setRequestedOrientation(
586 landscapeOnly ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
587 : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
590 private void maybeDisableWebsiteSettings(Context context) {
591 PreferenceActivity activity = (PreferenceActivity) context;
592 final PreferenceScreen screen = (PreferenceScreen)
593 activity.findPreference(BrowserSettings.PREF_WEBSITE_SETTINGS);
594 screen.setEnabled(false);
595 WebStorage.getInstance().getOrigins(new ValueCallback<Map>() {
596 public void onReceiveValue(Map webStorageOrigins) {
597 if ((webStorageOrigins != null) && !webStorageOrigins.isEmpty()) {
598 screen.setEnabled(true);
603 GeolocationPermissions.getInstance().getOrigins(new ValueCallback<Set<String> >() {
604 public void onReceiveValue(Set<String> geolocationOrigins) {
605 if ((geolocationOrigins != null) && !geolocationOrigins.isEmpty()) {
606 screen.setEnabled(true);
612 /*package*/ void clearDatabases(Context context) {
613 WebStorage.getInstance().deleteAllData();
614 maybeDisableWebsiteSettings(context);
617 /*package*/ void clearLocationAccess(Context context) {
618 GeolocationPermissions.getInstance().clearAll();
619 maybeDisableWebsiteSettings(context);
622 /*package*/ void resetDefaultPreferences(Context ctx) {
624 SharedPreferences p =
625 PreferenceManager.getDefaultSharedPreferences(ctx);
626 p.edit().clear().commit();
627 PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences,
630 setHomePage(ctx, getFactoryResetHomeUrl(ctx));
631 // reset appcache max size
632 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
635 private String getFactoryResetHomeUrl(Context context) {
636 String url = context.getResources().getString(R.string.homepage_base);
637 if (url.indexOf("{CID}") != -1) {
638 url = url.replace("{CID}",
639 BrowserProvider.getClientId(context.getContentResolver()));
644 // Private constructor that does nothing.
645 private BrowserSettings() {
649 private void reset() {
650 // Private variables for settings
651 // NOTE: these defaults need to be kept in sync with the XML
652 // until the performance of PreferenceManager.setDefaultValues()
654 loadsImagesAutomatically = true;
655 javaScriptEnabled = true;
656 pluginState = WebSettings.PluginState.ON;
657 javaScriptCanOpenWindowsAutomatically = false;
658 showSecurityWarnings = true;
659 rememberPasswords = true;
661 openInBackground = false;
663 landscapeOnly = false;
664 loadsPageInOverviewMode = true;
665 showDebugSettings = false;
667 appCacheEnabled = true;
668 databaseEnabled = true;
669 domStorageEnabled = true;
670 geolocationEnabled = true;
671 workersEnabled = true; // only affects V8. JSC does not have a similar setting