2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.browser;
19 import com.google.android.providers.GoogleSettings.Partner;
21 import android.content.ContentResolver;
22 import android.content.Context;
23 import android.content.pm.ActivityInfo;
24 import android.content.SharedPreferences;
25 import android.content.SharedPreferences.Editor;
26 import android.preference.PreferenceActivity;
27 import android.preference.PreferenceScreen;
28 import android.webkit.CookieManager;
29 import android.webkit.GeolocationPermissions;
30 import android.webkit.WebView;
31 import android.webkit.WebViewDatabase;
32 import android.webkit.WebIconDatabase;
33 import android.webkit.WebSettings;
34 import android.webkit.WebStorage;
35 import android.preference.PreferenceManager;
36 import android.provider.Browser;
39 import java.util.HashMap;
40 import java.util.Observable;
43 * Package level class for storing various WebView and Browser settings. To use
45 * BrowserSettings s = BrowserSettings.getInstance();
46 * s.addObserver(webView.getSettings());
47 * s.loadFromDb(context); // Only needed on app startup
48 * s.javaScriptEnabled = true;
49 * ... // set any other settings
50 * s.update(); // this will update all the observers
52 * To remove an observer:
53 * s.deleteObserver(webView.getSettings());
55 class BrowserSettings extends Observable {
57 // Private variables for settings
58 // NOTE: these defaults need to be kept in sync with the XML
59 // until the performance of PreferenceManager.setDefaultValues()
61 private boolean loadsImagesAutomatically = true;
62 private boolean javaScriptEnabled = true;
63 private boolean pluginsEnabled = true;
64 private String pluginsPath; // default value set in loadFromDb().
65 private boolean javaScriptCanOpenWindowsAutomatically = false;
66 private boolean showSecurityWarnings = true;
67 private boolean rememberPasswords = true;
68 private boolean saveFormData = true;
69 private boolean openInBackground = false;
70 private String defaultTextEncodingName;
71 private String homeUrl = "";
72 private boolean loginInitialized = false;
73 private boolean autoFitPage = true;
74 private boolean landscapeOnly = false;
75 private boolean loadsPageInOverviewMode = true;
76 private boolean showDebugSettings = false;
78 private boolean appCacheEnabled = true;
79 private boolean databaseEnabled = true;
80 private boolean domStorageEnabled = true;
81 private boolean geolocationEnabled = true;
82 private boolean workersEnabled = true; // only affects V8. JSC does not have a similar setting
83 // HTML5 API configuration params
84 private long appCacheMaxSize = Long.MAX_VALUE;
85 private String appCachePath; // default value set in loadFromDb().
86 private String databasePath; // default value set in loadFromDb()
87 private WebStorageSizeManager webStorageSizeManager;
89 private String jsFlags = "";
91 private final static String TAG = "BrowserSettings";
93 // Development settings
94 public WebSettings.LayoutAlgorithm layoutAlgorithm =
95 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
96 private boolean useWideViewPort = true;
97 private int userAgent = 0;
98 private boolean tracing = false;
99 private boolean lightTouch = false;
100 private boolean navDump = false;
102 // By default the error console is shown once the user navigates to about:debug.
103 // The setting can be then toggled from the settings menu.
104 private boolean showConsole = true;
106 // Browser only settings
107 private boolean doFlick = false;
109 // Private preconfigured values
110 private static int minimumFontSize = 8;
111 private static int minimumLogicalFontSize = 8;
112 private static int defaultFontSize = 16;
113 private static int defaultFixedFontSize = 13;
114 private static WebSettings.TextSize textSize =
115 WebSettings.TextSize.NORMAL;
116 private static WebSettings.ZoomDensity zoomDensity =
117 WebSettings.ZoomDensity.MEDIUM;
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";
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";
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";
147 // Value to truncate strings when adding them to a TextView within
149 public final static int MAX_TEXTVIEW_LEN = 80;
151 private TabControl mTabControl;
153 // Single instance of the BrowserSettings for use in the Browser app.
154 private static BrowserSettings sSingleton;
156 // Private map of WebSettings to Observer objects used when deleting an
158 private HashMap<WebSettings,Observer> mWebSettingsToObservers =
159 new HashMap<WebSettings,Observer>();
162 * An observer wrapper for updating a WebSettings object with the new
163 * settings after a call to BrowserSettings.update().
165 static class Observer implements java.util.Observer {
166 // Private WebSettings object that will be updated.
167 private WebSettings mSettings;
169 Observer(WebSettings w) {
173 public void update(Observable o, Object arg) {
174 BrowserSettings b = (BrowserSettings)o;
175 WebSettings s = mSettings;
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);
186 s.setUseWideViewPort(b.useWideViewPort);
187 s.setLoadsImagesAutomatically(b.loadsImagesAutomatically);
188 s.setJavaScriptEnabled(b.javaScriptEnabled);
189 s.setPluginsEnabled(b.pluginsEnabled);
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);
205 // WebView inside Browser doesn't want initial focus to be set.
206 s.setNeedInitialFocus(false);
207 // Browser supports multiple windows
208 s.setSupportMultipleWindows(true);
209 // Turn off file access
210 s.setAllowFileAccess(false);
213 s.setAppCacheEnabled(b.appCacheEnabled);
214 s.setDatabaseEnabled(b.databaseEnabled);
215 s.setDomStorageEnabled(b.domStorageEnabled);
216 s.setWorkersEnabled(b.workersEnabled); // This only affects V8.
217 s.setGeolocationEnabled(b.geolocationEnabled);
219 // HTML5 configuration parameters.
220 s.setAppCacheMaxSize(b.appCacheMaxSize);
221 s.setAppCachePath(b.appCachePath);
222 s.setDatabasePath(b.databasePath);
224 // Enable/Disable the error console.
225 b.mTabControl.getBrowserActivity().setShouldShowErrorConsole(
226 b.showDebugSettings && b.showConsole);
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.
239 public void loadFromDb(Context ctx) {
240 SharedPreferences p =
241 PreferenceManager.getDefaultSharedPreferences(ctx);
243 // Set the default value for the plugins path to the application's
245 pluginsPath = ctx.getDir("plugins", 0).getPath();
246 // Set the default value for the Application Caches path.
247 appCachePath = ctx.getDir("appcache", 0).getPath();
248 // Determine the maximum size of the application cache.
249 webStorageSizeManager = new WebStorageSizeManager(
251 new WebStorageSizeManager.StatFsDiskInfo(appCachePath),
252 new WebStorageSizeManager.WebKitAppCacheInfo(appCachePath));
253 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
254 // Set the default value for the Database path.
255 databasePath = ctx.getDir("databases", 0).getPath();
257 homeUrl = getFactoryResetHomeUrl(ctx);
259 // Load the defaults from the xml
260 // This call is TOO SLOW, need to manually keep the defaults
262 //PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences);
263 syncSharedPreferences(p);
266 /* package */ void syncSharedPreferences(SharedPreferences p) {
269 p.getString(PREF_HOMEPAGE, homeUrl);
271 loadsImagesAutomatically = p.getBoolean("load_images",
272 loadsImagesAutomatically);
273 javaScriptEnabled = p.getBoolean("enable_javascript",
275 pluginsEnabled = p.getBoolean("enable_plugins",
277 pluginsPath = p.getString("plugins_path", pluginsPath);
278 javaScriptCanOpenWindowsAutomatically = !p.getBoolean(
279 "block_popup_windows",
280 !javaScriptCanOpenWindowsAutomatically);
281 showSecurityWarnings = p.getBoolean("show_security_warnings",
282 showSecurityWarnings);
283 rememberPasswords = p.getBoolean("remember_passwords",
285 saveFormData = p.getBoolean("save_formdata",
287 boolean accept_cookies = p.getBoolean("accept_cookies",
288 CookieManager.getInstance().acceptCookie());
289 CookieManager.getInstance().setAcceptCookie(accept_cookies);
290 openInBackground = p.getBoolean("open_in_background", openInBackground);
291 loginInitialized = p.getBoolean("login_initialized", loginInitialized);
292 textSize = WebSettings.TextSize.valueOf(
293 p.getString(PREF_TEXT_SIZE, textSize.name()));
294 zoomDensity = WebSettings.ZoomDensity.valueOf(
295 p.getString(PREF_DEFAULT_ZOOM, zoomDensity.name()));
296 autoFitPage = p.getBoolean("autofit_pages", autoFitPage);
297 loadsPageInOverviewMode = p.getBoolean("load_page",
298 loadsPageInOverviewMode);
299 boolean landscapeOnlyTemp =
300 p.getBoolean("landscape_only", landscapeOnly);
301 if (landscapeOnlyTemp != landscapeOnly) {
302 landscapeOnly = landscapeOnlyTemp;
303 mTabControl.getBrowserActivity().setRequestedOrientation(
304 landscapeOnly ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
305 : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
307 useWideViewPort = true; // use wide view port for either setting
309 layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
311 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
313 defaultTextEncodingName =
314 p.getString(PREF_DEFAULT_TEXT_ENCODING,
315 defaultTextEncodingName);
318 p.getBoolean(PREF_DEBUG_SETTINGS, showDebugSettings);
319 // Debug menu items have precidence if the menu is visible
320 if (showDebugSettings) {
321 boolean small_screen = p.getBoolean("small_screen",
323 WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
325 layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
327 boolean normal_layout = p.getBoolean("normal_layout",
328 layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
330 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
333 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
336 useWideViewPort = p.getBoolean("wide_viewport", useWideViewPort);
337 tracing = p.getBoolean("enable_tracing", tracing);
338 lightTouch = p.getBoolean("enable_light_touch", lightTouch);
339 navDump = p.getBoolean("enable_nav_dump", navDump);
340 doFlick = p.getBoolean("enable_flick", doFlick);
341 userAgent = Integer.parseInt(p.getString("user_agent", "0"));
343 // JS flags is loaded from DB even if showDebugSettings is false,
344 // so that it can be set once and be effective all the time.
345 jsFlags = p.getString("js_engine_flags", "");
347 // Read the setting for showing/hiding the JS Console always so that should the
348 // user enable debug settings, we already know if we should show the console.
349 // The user will never see the console unless they navigate to about:debug,
350 // regardless of the setting we read here. This setting is only used after debug
352 showConsole = p.getBoolean("javascript_console", showConsole);
353 mTabControl.getBrowserActivity().setShouldShowErrorConsole(
354 showDebugSettings && showConsole);
357 appCacheEnabled = p.getBoolean("enable_appcache", appCacheEnabled);
358 databaseEnabled = p.getBoolean("enable_database", databaseEnabled);
359 domStorageEnabled = p.getBoolean("enable_domstorage", domStorageEnabled);
360 geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled);
361 workersEnabled = p.getBoolean("enable_workers", workersEnabled);
366 public String getPluginsPath() {
370 public String getHomePage() {
374 public String getJsFlags() {
378 public WebStorageSizeManager getWebStorageSizeManager() {
379 return webStorageSizeManager;
382 public void setHomePage(Context context, String url) {
383 Editor ed = PreferenceManager.
384 getDefaultSharedPreferences(context).edit();
385 ed.putString(PREF_HOMEPAGE, url);
390 public boolean isLoginInitialized() {
391 return loginInitialized;
394 public void setLoginInitialized(Context context) {
395 loginInitialized = true;
396 Editor ed = PreferenceManager.
397 getDefaultSharedPreferences(context).edit();
398 ed.putBoolean("login_initialized", loginInitialized);
402 public WebSettings.TextSize getTextSize() {
406 public WebSettings.ZoomDensity getDefaultZoom() {
410 public boolean openInBackground() {
411 return openInBackground;
414 public boolean showSecurityWarnings() {
415 return showSecurityWarnings;
418 public boolean isTracing() {
422 public boolean isLightTouch() {
426 public boolean isNavDump() {
430 public boolean doFlick() {
434 public boolean showDebugSettings() {
435 return showDebugSettings;
438 public void toggleDebugSettings() {
439 showDebugSettings = !showDebugSettings;
440 navDump = showDebugSettings;
445 * Add a WebSettings object to the list of observers that will be updated
446 * when update() is called.
448 * @param s A WebSettings object that is strictly tied to the life of a
451 public Observer addObserver(WebSettings s) {
452 Observer old = mWebSettingsToObservers.get(s);
454 super.deleteObserver(old);
456 Observer o = new Observer(s);
457 mWebSettingsToObservers.put(s, o);
458 super.addObserver(o);
463 * Delete the given WebSettings observer from the list of observers.
464 * @param s The WebSettings object to be deleted.
466 public void deleteObserver(WebSettings s) {
467 Observer o = mWebSettingsToObservers.get(s);
469 mWebSettingsToObservers.remove(s);
470 super.deleteObserver(o);
475 * Package level method for obtaining a single app instance of the
478 /*package*/ static BrowserSettings getInstance() {
479 if (sSingleton == null ) {
480 sSingleton = new BrowserSettings();
486 * Package level method for associating the BrowserSettings with TabControl
488 /* package */void setTabControl(TabControl tabControl) {
489 mTabControl = tabControl;
493 * Update all the observers of the object.
495 /*package*/ void update() {
500 /*package*/ void clearCache(Context context) {
501 WebIconDatabase.getInstance().removeAllIcons();
502 if (mTabControl != null) {
503 WebView current = mTabControl.getCurrentWebView();
504 if (current != null) {
505 current.clearCache(true);
510 /*package*/ void clearCookies(Context context) {
511 CookieManager.getInstance().removeAllCookie();
514 /* package */void clearHistory(Context context) {
515 ContentResolver resolver = context.getContentResolver();
516 Browser.clearHistory(resolver);
517 Browser.clearSearches(resolver);
520 /* package */ void clearFormData(Context context) {
521 WebViewDatabase.getInstance(context).clearFormData();
522 if (mTabControl != null) {
523 mTabControl.getCurrentTopWebView().clearFormData();
527 /*package*/ void clearPasswords(Context context) {
528 WebViewDatabase db = WebViewDatabase.getInstance(context);
529 db.clearUsernamePassword();
530 db.clearHttpAuthUsernamePassword();
533 private void maybeDisableWebsiteSettings(Context context) {
534 Set webStorageOrigins = WebStorage.getInstance().getOrigins();
535 Set geolocationOrigins =
536 GeolocationPermissions.getInstance().getOrigins();
537 if (((webStorageOrigins == null) || webStorageOrigins.isEmpty()) &&
538 ((geolocationOrigins == null) || geolocationOrigins.isEmpty())) {
539 PreferenceActivity activity = (PreferenceActivity) context;
540 PreferenceScreen screen = (PreferenceScreen)
541 activity.findPreference(BrowserSettings.PREF_WEBSITE_SETTINGS);
542 screen.setEnabled(false);
546 /*package*/ void clearDatabases(Context context) {
547 WebStorage.getInstance().deleteAllData();
548 maybeDisableWebsiteSettings(context);
551 /*package*/ void clearLocationAccess(Context context) {
552 GeolocationPermissions.getInstance().clearAll();
553 maybeDisableWebsiteSettings(context);
556 /*package*/ void resetDefaultPreferences(Context ctx) {
557 SharedPreferences p =
558 PreferenceManager.getDefaultSharedPreferences(ctx);
559 p.edit().clear().commit();
560 PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences,
563 setHomePage(ctx, getFactoryResetHomeUrl(ctx));
564 // reset appcache max size
565 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
568 private String getFactoryResetHomeUrl(Context context) {
569 String url = context.getResources().getString(R.string.homepage_base);
570 if (url.indexOf("{CID}") != -1) {
571 url = url.replace("{CID}", Partner.getString(context
572 .getContentResolver(), Partner.CLIENT_ID, "android-google"));
577 // Private constructor that does nothing.
578 private BrowserSettings() {