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, null);
306 if (searchEngine == null || !searchEngine.getName().equals(searchEngineName)) {
307 if (searchEngine != null) {
308 if (searchEngine.supportsVoiceSearch()) {
309 // One or more tabs could have been in voice search mode.
310 // Clear it, since the new SearchEngine may not support
311 // it, or may handle it differently.
312 for (int i = 0; i < mTabControl.getTabCount(); i++) {
313 mTabControl.getTab(i).revertVoiceSearchMode();
316 searchEngine.close();
318 searchEngine = SearchEngines.get(ctx, searchEngineName);
320 Log.i(TAG, "Selected search engine: " + searchEngine);
321 showSearchSuggestions = p.getBoolean(PREF_SHOW_SEARCH_SUGGESTIONS, true);
322 // Persist to system settings
323 saveShowWebSuggestions(ctx.getContentResolver());
325 loadsImagesAutomatically = p.getBoolean("load_images",
326 loadsImagesAutomatically);
327 javaScriptEnabled = p.getBoolean("enable_javascript",
329 pluginState = WebSettings.PluginState.valueOf(
330 p.getString("plugin_state", pluginState.name()));
331 javaScriptCanOpenWindowsAutomatically = !p.getBoolean(
332 "block_popup_windows",
333 !javaScriptCanOpenWindowsAutomatically);
334 showSecurityWarnings = p.getBoolean("show_security_warnings",
335 showSecurityWarnings);
336 rememberPasswords = p.getBoolean("remember_passwords",
338 saveFormData = p.getBoolean("save_formdata",
340 boolean accept_cookies = p.getBoolean("accept_cookies",
341 CookieManager.getInstance().acceptCookie());
342 CookieManager.getInstance().setAcceptCookie(accept_cookies);
343 openInBackground = p.getBoolean("open_in_background", openInBackground);
344 textSize = WebSettings.TextSize.valueOf(
345 p.getString(PREF_TEXT_SIZE, textSize.name()));
346 zoomDensity = WebSettings.ZoomDensity.valueOf(
347 p.getString(PREF_DEFAULT_ZOOM, zoomDensity.name()));
348 autoFitPage = p.getBoolean("autofit_pages", autoFitPage);
349 loadsPageInOverviewMode = p.getBoolean("load_page",
350 loadsPageInOverviewMode);
351 boolean landscapeOnlyTemp =
352 p.getBoolean("landscape_only", landscapeOnly);
353 if (landscapeOnlyTemp != landscapeOnly) {
354 landscapeOnly = landscapeOnlyTemp;
356 useWideViewPort = true; // use wide view port for either setting
358 layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
360 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
362 defaultTextEncodingName =
363 p.getString(PREF_DEFAULT_TEXT_ENCODING,
364 defaultTextEncodingName);
367 p.getBoolean(PREF_DEBUG_SETTINGS, showDebugSettings);
368 // Debug menu items have precidence if the menu is visible
369 if (showDebugSettings) {
370 boolean small_screen = p.getBoolean("small_screen",
372 WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
374 layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
376 boolean normal_layout = p.getBoolean("normal_layout",
377 layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
379 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
382 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
385 useWideViewPort = p.getBoolean("wide_viewport", useWideViewPort);
386 tracing = p.getBoolean("enable_tracing", tracing);
387 lightTouch = p.getBoolean("enable_light_touch", lightTouch);
388 navDump = p.getBoolean("enable_nav_dump", navDump);
389 userAgent = Integer.parseInt(p.getString("user_agent", "0"));
391 // JS flags is loaded from DB even if showDebugSettings is false,
392 // so that it can be set once and be effective all the time.
393 jsFlags = p.getString("js_engine_flags", "");
395 // Read the setting for showing/hiding the JS Console always so that should the
396 // user enable debug settings, we already know if we should show the console.
397 // The user will never see the console unless they navigate to about:debug,
398 // regardless of the setting we read here. This setting is only used after debug
400 showConsole = p.getBoolean("javascript_console", showConsole);
403 appCacheEnabled = p.getBoolean("enable_appcache", appCacheEnabled);
404 databaseEnabled = p.getBoolean("enable_database", databaseEnabled);
405 domStorageEnabled = p.getBoolean("enable_domstorage", domStorageEnabled);
406 geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled);
407 workersEnabled = p.getBoolean("enable_workers", workersEnabled);
412 private void saveShowWebSuggestions(ContentResolver cr) {
413 int value = showSearchSuggestions ? 1 : 0;
414 Settings.System.putInt(cr, Settings.System.SHOW_WEB_SUGGESTIONS, value);
417 private void updateShowWebSuggestions(ContentResolver cr, SharedPreferences p) {
418 showSearchSuggestions =
419 Settings.System.getInt(cr,
420 Settings.System.SHOW_WEB_SUGGESTIONS, 1) == 1;
421 p.edit().putBoolean(PREF_SHOW_SEARCH_SUGGESTIONS, showSearchSuggestions).commit();
424 public String getHomePage() {
428 public SearchEngine getSearchEngine() {
432 public boolean getShowSearchSuggestions() {
433 return showSearchSuggestions;
436 public String getJsFlags() {
440 public WebStorageSizeManager getWebStorageSizeManager() {
441 return webStorageSizeManager;
444 public void setHomePage(Context context, String url) {
445 Editor ed = PreferenceManager.
446 getDefaultSharedPreferences(context).edit();
447 ed.putString(PREF_HOMEPAGE, url);
452 public WebSettings.TextSize getTextSize() {
456 public WebSettings.ZoomDensity getDefaultZoom() {
460 public boolean openInBackground() {
461 return openInBackground;
464 public boolean showSecurityWarnings() {
465 return showSecurityWarnings;
468 public boolean isTracing() {
472 public boolean isLightTouch() {
476 public boolean isNavDump() {
480 public boolean showDebugSettings() {
481 return showDebugSettings;
484 public void toggleDebugSettings() {
485 showDebugSettings = !showDebugSettings;
486 navDump = showDebugSettings;
491 * Add a WebSettings object to the list of observers that will be updated
492 * when update() is called.
494 * @param s A WebSettings object that is strictly tied to the life of a
497 public Observer addObserver(WebSettings s) {
498 Observer old = mWebSettingsToObservers.get(s);
500 super.deleteObserver(old);
502 Observer o = new Observer(s);
503 mWebSettingsToObservers.put(s, o);
504 super.addObserver(o);
509 * Delete the given WebSettings observer from the list of observers.
510 * @param s The WebSettings object to be deleted.
512 public void deleteObserver(WebSettings s) {
513 Observer o = mWebSettingsToObservers.get(s);
515 mWebSettingsToObservers.remove(s);
516 super.deleteObserver(o);
521 * Package level method for obtaining a single app instance of the
524 /*package*/ static BrowserSettings getInstance() {
525 if (sSingleton == null ) {
526 sSingleton = new BrowserSettings();
532 * Package level method for associating the BrowserSettings with TabControl
534 /* package */void setTabControl(TabControl tabControl) {
535 mTabControl = tabControl;
536 updateTabControlSettings();
540 * Update all the observers of the object.
542 /*package*/ void update() {
547 /*package*/ void clearCache(Context context) {
548 WebIconDatabase.getInstance().removeAllIcons();
549 if (mTabControl != null) {
550 WebView current = mTabControl.getCurrentWebView();
551 if (current != null) {
552 current.clearCache(true);
557 /*package*/ void clearCookies(Context context) {
558 CookieManager.getInstance().removeAllCookie();
561 /* package */void clearHistory(Context context) {
562 ContentResolver resolver = context.getContentResolver();
563 Browser.clearHistory(resolver);
564 Browser.clearSearches(resolver);
567 /* package */ void clearFormData(Context context) {
568 WebViewDatabase.getInstance(context).clearFormData();
569 if (mTabControl != null) {
570 mTabControl.getCurrentTopWebView().clearFormData();
574 /*package*/ void clearPasswords(Context context) {
575 WebViewDatabase db = WebViewDatabase.getInstance(context);
576 db.clearUsernamePassword();
577 db.clearHttpAuthUsernamePassword();
580 private void updateTabControlSettings() {
581 // Enable/disable the error console.
582 mTabControl.getBrowserActivity().setShouldShowErrorConsole(
583 showDebugSettings && showConsole);
584 mTabControl.getBrowserActivity().setRequestedOrientation(
585 landscapeOnly ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
586 : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
589 private void maybeDisableWebsiteSettings(Context context) {
590 PreferenceActivity activity = (PreferenceActivity) context;
591 final PreferenceScreen screen = (PreferenceScreen)
592 activity.findPreference(BrowserSettings.PREF_WEBSITE_SETTINGS);
593 screen.setEnabled(false);
594 WebStorage.getInstance().getOrigins(new ValueCallback<Map>() {
595 public void onReceiveValue(Map webStorageOrigins) {
596 if ((webStorageOrigins != null) && !webStorageOrigins.isEmpty()) {
597 screen.setEnabled(true);
602 GeolocationPermissions.getInstance().getOrigins(new ValueCallback<Set<String> >() {
603 public void onReceiveValue(Set<String> geolocationOrigins) {
604 if ((geolocationOrigins != null) && !geolocationOrigins.isEmpty()) {
605 screen.setEnabled(true);
611 /*package*/ void clearDatabases(Context context) {
612 WebStorage.getInstance().deleteAllData();
613 maybeDisableWebsiteSettings(context);
616 /*package*/ void clearLocationAccess(Context context) {
617 GeolocationPermissions.getInstance().clearAll();
618 maybeDisableWebsiteSettings(context);
621 /*package*/ void resetDefaultPreferences(Context ctx) {
623 SharedPreferences p =
624 PreferenceManager.getDefaultSharedPreferences(ctx);
625 p.edit().clear().commit();
626 PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences,
629 setHomePage(ctx, getFactoryResetHomeUrl(ctx));
630 // reset appcache max size
631 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
634 private String getFactoryResetHomeUrl(Context context) {
635 String url = context.getResources().getString(R.string.homepage_base);
636 if (url.indexOf("{CID}") != -1) {
637 url = url.replace("{CID}",
638 BrowserProvider.getClientId(context.getContentResolver()));
643 // Private constructor that does nothing.
644 private BrowserSettings() {
648 private void reset() {
649 // Private variables for settings
650 // NOTE: these defaults need to be kept in sync with the XML
651 // until the performance of PreferenceManager.setDefaultValues()
653 loadsImagesAutomatically = true;
654 javaScriptEnabled = true;
655 pluginState = WebSettings.PluginState.ON;
656 javaScriptCanOpenWindowsAutomatically = false;
657 showSecurityWarnings = true;
658 rememberPasswords = true;
660 openInBackground = false;
662 landscapeOnly = false;
663 loadsPageInOverviewMode = true;
664 showDebugSettings = false;
666 appCacheEnabled = true;
667 databaseEnabled = true;
668 domStorageEnabled = true;
669 geolocationEnabled = true;
670 workersEnabled = true; // only affects V8. JSC does not have a similar setting