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 searchEngine.close();
310 searchEngine = SearchEngines.get(ctx, searchEngineName);
312 Log.i(TAG, "Selected search engine: " + searchEngine);
313 showSearchSuggestions = p.getBoolean(PREF_SHOW_SEARCH_SUGGESTIONS, true);
314 // Persist to system settings
315 saveShowWebSuggestions(ctx.getContentResolver());
317 loadsImagesAutomatically = p.getBoolean("load_images",
318 loadsImagesAutomatically);
319 javaScriptEnabled = p.getBoolean("enable_javascript",
321 pluginState = WebSettings.PluginState.valueOf(
322 p.getString("plugin_state", pluginState.name()));
323 javaScriptCanOpenWindowsAutomatically = !p.getBoolean(
324 "block_popup_windows",
325 !javaScriptCanOpenWindowsAutomatically);
326 showSecurityWarnings = p.getBoolean("show_security_warnings",
327 showSecurityWarnings);
328 rememberPasswords = p.getBoolean("remember_passwords",
330 saveFormData = p.getBoolean("save_formdata",
332 boolean accept_cookies = p.getBoolean("accept_cookies",
333 CookieManager.getInstance().acceptCookie());
334 CookieManager.getInstance().setAcceptCookie(accept_cookies);
335 openInBackground = p.getBoolean("open_in_background", openInBackground);
336 textSize = WebSettings.TextSize.valueOf(
337 p.getString(PREF_TEXT_SIZE, textSize.name()));
338 zoomDensity = WebSettings.ZoomDensity.valueOf(
339 p.getString(PREF_DEFAULT_ZOOM, zoomDensity.name()));
340 autoFitPage = p.getBoolean("autofit_pages", autoFitPage);
341 loadsPageInOverviewMode = p.getBoolean("load_page",
342 loadsPageInOverviewMode);
343 boolean landscapeOnlyTemp =
344 p.getBoolean("landscape_only", landscapeOnly);
345 if (landscapeOnlyTemp != landscapeOnly) {
346 landscapeOnly = landscapeOnlyTemp;
348 useWideViewPort = true; // use wide view port for either setting
350 layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
352 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
354 defaultTextEncodingName =
355 p.getString(PREF_DEFAULT_TEXT_ENCODING,
356 defaultTextEncodingName);
359 p.getBoolean(PREF_DEBUG_SETTINGS, showDebugSettings);
360 // Debug menu items have precidence if the menu is visible
361 if (showDebugSettings) {
362 boolean small_screen = p.getBoolean("small_screen",
364 WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
366 layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
368 boolean normal_layout = p.getBoolean("normal_layout",
369 layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
371 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
374 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
377 useWideViewPort = p.getBoolean("wide_viewport", useWideViewPort);
378 tracing = p.getBoolean("enable_tracing", tracing);
379 lightTouch = p.getBoolean("enable_light_touch", lightTouch);
380 navDump = p.getBoolean("enable_nav_dump", navDump);
381 userAgent = Integer.parseInt(p.getString("user_agent", "0"));
383 // JS flags is loaded from DB even if showDebugSettings is false,
384 // so that it can be set once and be effective all the time.
385 jsFlags = p.getString("js_engine_flags", "");
387 // Read the setting for showing/hiding the JS Console always so that should the
388 // user enable debug settings, we already know if we should show the console.
389 // The user will never see the console unless they navigate to about:debug,
390 // regardless of the setting we read here. This setting is only used after debug
392 showConsole = p.getBoolean("javascript_console", showConsole);
395 appCacheEnabled = p.getBoolean("enable_appcache", appCacheEnabled);
396 databaseEnabled = p.getBoolean("enable_database", databaseEnabled);
397 domStorageEnabled = p.getBoolean("enable_domstorage", domStorageEnabled);
398 geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled);
399 workersEnabled = p.getBoolean("enable_workers", workersEnabled);
404 private void saveShowWebSuggestions(ContentResolver cr) {
405 int value = showSearchSuggestions ? 1 : 0;
406 Settings.System.putInt(cr, Settings.System.SHOW_WEB_SUGGESTIONS, value);
409 private void updateShowWebSuggestions(ContentResolver cr, SharedPreferences p) {
410 showSearchSuggestions =
411 Settings.System.getInt(cr,
412 Settings.System.SHOW_WEB_SUGGESTIONS, 1) == 1;
413 p.edit().putBoolean(PREF_SHOW_SEARCH_SUGGESTIONS, showSearchSuggestions).commit();
416 public String getHomePage() {
420 public SearchEngine getSearchEngine() {
424 public boolean getShowSearchSuggestions() {
425 return showSearchSuggestions;
428 public String getJsFlags() {
432 public WebStorageSizeManager getWebStorageSizeManager() {
433 return webStorageSizeManager;
436 public void setHomePage(Context context, String url) {
437 Editor ed = PreferenceManager.
438 getDefaultSharedPreferences(context).edit();
439 ed.putString(PREF_HOMEPAGE, url);
444 public WebSettings.TextSize getTextSize() {
448 public WebSettings.ZoomDensity getDefaultZoom() {
452 public boolean openInBackground() {
453 return openInBackground;
456 public boolean showSecurityWarnings() {
457 return showSecurityWarnings;
460 public boolean isTracing() {
464 public boolean isLightTouch() {
468 public boolean isNavDump() {
472 public boolean showDebugSettings() {
473 return showDebugSettings;
476 public void toggleDebugSettings() {
477 showDebugSettings = !showDebugSettings;
478 navDump = showDebugSettings;
483 * Add a WebSettings object to the list of observers that will be updated
484 * when update() is called.
486 * @param s A WebSettings object that is strictly tied to the life of a
489 public Observer addObserver(WebSettings s) {
490 Observer old = mWebSettingsToObservers.get(s);
492 super.deleteObserver(old);
494 Observer o = new Observer(s);
495 mWebSettingsToObservers.put(s, o);
496 super.addObserver(o);
501 * Delete the given WebSettings observer from the list of observers.
502 * @param s The WebSettings object to be deleted.
504 public void deleteObserver(WebSettings s) {
505 Observer o = mWebSettingsToObservers.get(s);
507 mWebSettingsToObservers.remove(s);
508 super.deleteObserver(o);
513 * Package level method for obtaining a single app instance of the
516 /*package*/ static BrowserSettings getInstance() {
517 if (sSingleton == null ) {
518 sSingleton = new BrowserSettings();
524 * Package level method for associating the BrowserSettings with TabControl
526 /* package */void setTabControl(TabControl tabControl) {
527 mTabControl = tabControl;
528 updateTabControlSettings();
532 * Update all the observers of the object.
534 /*package*/ void update() {
539 /*package*/ void clearCache(Context context) {
540 WebIconDatabase.getInstance().removeAllIcons();
541 if (mTabControl != null) {
542 WebView current = mTabControl.getCurrentWebView();
543 if (current != null) {
544 current.clearCache(true);
549 /*package*/ void clearCookies(Context context) {
550 CookieManager.getInstance().removeAllCookie();
553 /* package */void clearHistory(Context context) {
554 ContentResolver resolver = context.getContentResolver();
555 Browser.clearHistory(resolver);
556 Browser.clearSearches(resolver);
559 /* package */ void clearFormData(Context context) {
560 WebViewDatabase.getInstance(context).clearFormData();
561 if (mTabControl != null) {
562 mTabControl.getCurrentTopWebView().clearFormData();
566 /*package*/ void clearPasswords(Context context) {
567 WebViewDatabase db = WebViewDatabase.getInstance(context);
568 db.clearUsernamePassword();
569 db.clearHttpAuthUsernamePassword();
572 private void updateTabControlSettings() {
573 // Enable/disable the error console.
574 mTabControl.getBrowserActivity().setShouldShowErrorConsole(
575 showDebugSettings && showConsole);
576 mTabControl.getBrowserActivity().setRequestedOrientation(
577 landscapeOnly ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
578 : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
581 private void maybeDisableWebsiteSettings(Context context) {
582 PreferenceActivity activity = (PreferenceActivity) context;
583 final PreferenceScreen screen = (PreferenceScreen)
584 activity.findPreference(BrowserSettings.PREF_WEBSITE_SETTINGS);
585 screen.setEnabled(false);
586 WebStorage.getInstance().getOrigins(new ValueCallback<Map>() {
587 public void onReceiveValue(Map webStorageOrigins) {
588 if ((webStorageOrigins != null) && !webStorageOrigins.isEmpty()) {
589 screen.setEnabled(true);
594 GeolocationPermissions.getInstance().getOrigins(new ValueCallback<Set<String> >() {
595 public void onReceiveValue(Set<String> geolocationOrigins) {
596 if ((geolocationOrigins != null) && !geolocationOrigins.isEmpty()) {
597 screen.setEnabled(true);
603 /*package*/ void clearDatabases(Context context) {
604 WebStorage.getInstance().deleteAllData();
605 maybeDisableWebsiteSettings(context);
608 /*package*/ void clearLocationAccess(Context context) {
609 GeolocationPermissions.getInstance().clearAll();
610 maybeDisableWebsiteSettings(context);
613 /*package*/ void resetDefaultPreferences(Context ctx) {
615 SharedPreferences p =
616 PreferenceManager.getDefaultSharedPreferences(ctx);
617 p.edit().clear().commit();
618 PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences,
621 setHomePage(ctx, getFactoryResetHomeUrl(ctx));
622 // reset appcache max size
623 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
626 private String getFactoryResetHomeUrl(Context context) {
627 String url = context.getResources().getString(R.string.homepage_base);
628 if (url.indexOf("{CID}") != -1) {
629 url = url.replace("{CID}",
630 BrowserProvider.getClientId(context.getContentResolver()));
635 // Private constructor that does nothing.
636 private BrowserSettings() {
640 private void reset() {
641 // Private variables for settings
642 // NOTE: these defaults need to be kept in sync with the XML
643 // until the performance of PreferenceManager.setDefaultValues()
645 loadsImagesAutomatically = true;
646 javaScriptEnabled = true;
647 pluginState = WebSettings.PluginState.ON;
648 javaScriptCanOpenWindowsAutomatically = false;
649 showSecurityWarnings = true;
650 rememberPasswords = true;
652 openInBackground = false;
654 landscapeOnly = false;
655 loadsPageInOverviewMode = true;
656 showDebugSettings = false;
658 appCacheEnabled = true;
659 databaseEnabled = true;
660 domStorageEnabled = true;
661 geolocationEnabled = true;
662 workersEnabled = true; // only affects V8. JSC does not have a similar setting