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 showDebugSettings = false;
76 private String databasePath; // default value set in loadFromDb()
77 private boolean databaseEnabled = true;
78 private long webStorageDefaultQuota = 5 * 1024 * 1024;
79 // The Browser always enables Application Caches.
80 private boolean appCacheEnabled = true;
81 private String appCachePath; // default value set in loadFromDb().
82 private long appCacheMaxSize = Long.MAX_VALUE;
83 private WebStorageSizeManager webStorageSizeManager;
84 private boolean domStorageEnabled = true;
85 private String jsFlags = "";
86 private boolean geolocationEnabled = true;
88 private final static String TAG = "BrowserSettings";
90 // Development settings
91 public WebSettings.LayoutAlgorithm layoutAlgorithm =
92 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
93 private boolean useWideViewPort = true;
94 private int userAgent = 0;
95 private boolean tracing = false;
96 private boolean lightTouch = false;
97 private boolean navDump = false;
99 // By default the error console is shown once the user navigates to about:debug.
100 // The setting can be then toggled from the settings menu.
101 private boolean showConsole = true;
103 // Browser only settings
104 private boolean doFlick = false;
106 // Private preconfigured values
107 private static int minimumFontSize = 8;
108 private static int minimumLogicalFontSize = 8;
109 private static int defaultFontSize = 16;
110 private static int defaultFixedFontSize = 13;
111 private static WebSettings.TextSize textSize =
112 WebSettings.TextSize.NORMAL;
113 private static WebSettings.ZoomDensity zoomDensity =
114 WebSettings.ZoomDensity.MEDIUM;
116 // Preference keys that are used outside this class
117 public final static String PREF_CLEAR_CACHE = "privacy_clear_cache";
118 public final static String PREF_CLEAR_COOKIES = "privacy_clear_cookies";
119 public final static String PREF_CLEAR_HISTORY = "privacy_clear_history";
120 public final static String PREF_HOMEPAGE = "homepage";
121 public final static String PREF_CLEAR_FORM_DATA =
122 "privacy_clear_form_data";
123 public final static String PREF_CLEAR_PASSWORDS =
124 "privacy_clear_passwords";
125 public final static String PREF_DEFAULT_QUOTA =
126 "webstorage_default_quota";
127 public final static String PREF_EXTRAS_RESET_DEFAULTS =
128 "reset_default_preferences";
129 public final static String PREF_DEBUG_SETTINGS = "debug_menu";
130 public final static String PREF_GEARS_SETTINGS = "gears_settings";
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_LOCATION_ACCESS =
137 "privacy_clear_location_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);
204 // WebView inside Browser doesn't want initial focus to be set.
205 s.setNeedInitialFocus(false);
206 // Browser supports multiple windows
207 s.setSupportMultipleWindows(true);
208 // Turn off file access
209 s.setAllowFileAccess(false);
211 s.setDatabasePath(b.databasePath);
212 s.setDatabaseEnabled(b.databaseEnabled);
213 s.setDomStorageEnabled(b.domStorageEnabled);
214 s.setWebStorageDefaultQuota(b.webStorageDefaultQuota);
216 // Turn on Application Caches.
217 s.setAppCachePath(b.appCachePath);
218 s.setAppCacheEnabled(b.appCacheEnabled);
219 s.setAppCacheMaxSize(b.appCacheMaxSize);
221 // Enable/Disable the error console.
222 b.mTabControl.getBrowserActivity().setShouldShowErrorConsole(
223 b.showDebugSettings && b.showConsole);
225 // Configure the Geolocation permissions manager to deny all
226 // permission requests if Geolocation is disabled in the browser.
227 // TODO(steveblock): Implement
232 * Load settings from the browser app's database.
233 * NOTE: Strings used for the preferences must match those specified
234 * in the browser_preferences.xml
235 * @param ctx A Context object used to query the browser's settings
236 * database. If the database exists, the saved settings will be
237 * stored in this BrowserSettings object. This will update all
238 * observers of this object.
240 public void loadFromDb(Context ctx) {
241 SharedPreferences p =
242 PreferenceManager.getDefaultSharedPreferences(ctx);
244 // Set the default value for the plugins path to the application's
246 pluginsPath = ctx.getDir("plugins", 0).getPath();
247 // Set the default value for the Application Caches path.
248 appCachePath = ctx.getDir("appcache", 0).getPath();
249 // Determine the maximum size of the application cache.
250 webStorageSizeManager = new WebStorageSizeManager(
252 new WebStorageSizeManager.StatFsDiskInfo(appCachePath),
253 new WebStorageSizeManager.WebKitAppCacheInfo(appCachePath));
254 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
255 // Set the default value for the Database path.
256 databasePath = ctx.getDir("databases", 0).getPath();
258 homeUrl = getFactoryResetHomeUrl(ctx);
260 // Load the defaults from the xml
261 // This call is TOO SLOW, need to manually keep the defaults
263 //PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences);
264 syncSharedPreferences(p);
267 /* package */ void syncSharedPreferences(SharedPreferences p) {
270 p.getString(PREF_HOMEPAGE, homeUrl);
272 loadsImagesAutomatically = p.getBoolean("load_images",
273 loadsImagesAutomatically);
274 javaScriptEnabled = p.getBoolean("enable_javascript",
276 pluginsEnabled = p.getBoolean("enable_plugins",
278 pluginsPath = p.getString("plugins_path", pluginsPath);
279 databasePath = p.getString("database_path", databasePath);
280 databaseEnabled = p.getBoolean("enable_database", databaseEnabled);
281 webStorageDefaultQuota = Long.parseLong(p.getString(PREF_DEFAULT_QUOTA,
282 String.valueOf(webStorageDefaultQuota)));
283 appCacheEnabled = p.getBoolean("enable_appcache",
285 domStorageEnabled = p.getBoolean("enable_domstorage",
287 appCachePath = p.getString("appcache_path", appCachePath);
288 javaScriptCanOpenWindowsAutomatically = !p.getBoolean(
289 "block_popup_windows",
290 !javaScriptCanOpenWindowsAutomatically);
291 showSecurityWarnings = p.getBoolean("show_security_warnings",
292 showSecurityWarnings);
293 rememberPasswords = p.getBoolean("remember_passwords",
295 saveFormData = p.getBoolean("save_formdata",
297 boolean accept_cookies = p.getBoolean("accept_cookies",
298 CookieManager.getInstance().acceptCookie());
299 CookieManager.getInstance().setAcceptCookie(accept_cookies);
300 openInBackground = p.getBoolean("open_in_background", openInBackground);
301 loginInitialized = p.getBoolean("login_initialized", loginInitialized);
302 textSize = WebSettings.TextSize.valueOf(
303 p.getString(PREF_TEXT_SIZE, textSize.name()));
304 zoomDensity = WebSettings.ZoomDensity.valueOf(
305 p.getString(PREF_DEFAULT_ZOOM, zoomDensity.name()));
306 autoFitPage = p.getBoolean("autofit_pages", autoFitPage);
307 boolean landscapeOnlyTemp =
308 p.getBoolean("landscape_only", landscapeOnly);
309 if (landscapeOnlyTemp != landscapeOnly) {
310 landscapeOnly = landscapeOnlyTemp;
311 mTabControl.getBrowserActivity().setRequestedOrientation(
312 landscapeOnly ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
313 : ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
315 useWideViewPort = true; // use wide view port for either setting
317 layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
319 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
321 defaultTextEncodingName =
322 p.getString(PREF_DEFAULT_TEXT_ENCODING,
323 defaultTextEncodingName);
326 p.getBoolean(PREF_DEBUG_SETTINGS, showDebugSettings);
327 // Debug menu items have precidence if the menu is visible
328 if (showDebugSettings) {
329 boolean small_screen = p.getBoolean("small_screen",
331 WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
333 layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
335 boolean normal_layout = p.getBoolean("normal_layout",
336 layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
338 layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
341 WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
344 useWideViewPort = p.getBoolean("wide_viewport", useWideViewPort);
345 tracing = p.getBoolean("enable_tracing", tracing);
346 lightTouch = p.getBoolean("enable_light_touch", lightTouch);
347 navDump = p.getBoolean("enable_nav_dump", navDump);
348 doFlick = p.getBoolean("enable_flick", doFlick);
349 userAgent = Integer.parseInt(p.getString("user_agent", "0"));
351 // JS flags is loaded from DB even if showDebugSettings is false,
352 // so that it can be set once and be effective all the time.
353 jsFlags = p.getString("js_engine_flags", "");
355 // Read the setting for showing/hiding the JS Console always so that should the
356 // user enable debug settings, we already know if we should show the console.
357 // The user will never see the console unless they navigate to about:debug,
358 // regardless of the setting we read here. This setting is only used after debug
360 showConsole = p.getBoolean("javascript_console", showConsole);
361 mTabControl.getBrowserActivity().setShouldShowErrorConsole(
362 showDebugSettings && showConsole);
364 geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled);
369 public String getPluginsPath() {
373 public String getHomePage() {
377 public String getJsFlags() {
381 public WebStorageSizeManager getWebStorageSizeManager() {
382 return webStorageSizeManager;
385 public void setHomePage(Context context, String url) {
386 Editor ed = PreferenceManager.
387 getDefaultSharedPreferences(context).edit();
388 ed.putString(PREF_HOMEPAGE, url);
393 public boolean isLoginInitialized() {
394 return loginInitialized;
397 public void setLoginInitialized(Context context) {
398 loginInitialized = true;
399 Editor ed = PreferenceManager.
400 getDefaultSharedPreferences(context).edit();
401 ed.putBoolean("login_initialized", loginInitialized);
405 public WebSettings.TextSize getTextSize() {
409 public WebSettings.ZoomDensity getDefaultZoom() {
413 public boolean openInBackground() {
414 return openInBackground;
417 public boolean showSecurityWarnings() {
418 return showSecurityWarnings;
421 public boolean isTracing() {
425 public boolean isLightTouch() {
429 public boolean isNavDump() {
433 public boolean doFlick() {
437 public boolean showDebugSettings() {
438 return showDebugSettings;
441 public void toggleDebugSettings() {
442 showDebugSettings = !showDebugSettings;
443 navDump = showDebugSettings;
448 * Add a WebSettings object to the list of observers that will be updated
449 * when update() is called.
451 * @param s A WebSettings object that is strictly tied to the life of a
454 public Observer addObserver(WebSettings s) {
455 Observer old = mWebSettingsToObservers.get(s);
457 super.deleteObserver(old);
459 Observer o = new Observer(s);
460 mWebSettingsToObservers.put(s, o);
461 super.addObserver(o);
466 * Delete the given WebSettings observer from the list of observers.
467 * @param s The WebSettings object to be deleted.
469 public void deleteObserver(WebSettings s) {
470 Observer o = mWebSettingsToObservers.get(s);
472 mWebSettingsToObservers.remove(s);
473 super.deleteObserver(o);
478 * Package level method for obtaining a single app instance of the
481 /*package*/ static BrowserSettings getInstance() {
482 if (sSingleton == null ) {
483 sSingleton = new BrowserSettings();
489 * Package level method for associating the BrowserSettings with TabControl
491 /* package */void setTabControl(TabControl tabControl) {
492 mTabControl = tabControl;
496 * Update all the observers of the object.
498 /*package*/ void update() {
503 /*package*/ void clearCache(Context context) {
504 WebIconDatabase.getInstance().removeAllIcons();
505 if (mTabControl != null) {
506 WebView current = mTabControl.getCurrentWebView();
507 if (current != null) {
508 current.clearCache(true);
513 /*package*/ void clearCookies(Context context) {
514 CookieManager.getInstance().removeAllCookie();
517 /* package */void clearHistory(Context context) {
518 ContentResolver resolver = context.getContentResolver();
519 Browser.clearHistory(resolver);
520 Browser.clearSearches(resolver);
523 /* package */ void clearFormData(Context context) {
524 WebViewDatabase.getInstance(context).clearFormData();
525 if (mTabControl != null) {
526 mTabControl.getCurrentTopWebView().clearFormData();
530 /*package*/ void clearPasswords(Context context) {
531 WebViewDatabase db = WebViewDatabase.getInstance(context);
532 db.clearUsernamePassword();
533 db.clearHttpAuthUsernamePassword();
536 private void maybeDisableWebsiteSettings(Context context) {
537 Set webStorageOrigins = WebStorage.getInstance().getOrigins();
538 Set geolocationOrigins =
539 GeolocationPermissions.getInstance().getOrigins();
540 if (((webStorageOrigins == null) || webStorageOrigins.isEmpty()) &&
541 ((geolocationOrigins == null) || geolocationOrigins.isEmpty())) {
542 PreferenceActivity activity = (PreferenceActivity) context;
543 PreferenceScreen screen = (PreferenceScreen)
544 activity.findPreference(BrowserSettings.PREF_WEBSITE_SETTINGS);
545 screen.setEnabled(false);
549 /*package*/ void clearDatabases(Context context) {
550 WebStorage.getInstance().deleteAllData();
551 maybeDisableWebsiteSettings(context);
554 /*package*/ void clearLocationAccess(Context context) {
555 GeolocationPermissions.getInstance().clearAll();
556 maybeDisableWebsiteSettings(context);
559 /*package*/ void resetDefaultPreferences(Context ctx) {
560 SharedPreferences p =
561 PreferenceManager.getDefaultSharedPreferences(ctx);
562 p.edit().clear().commit();
563 PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences,
566 setHomePage(ctx, getFactoryResetHomeUrl(ctx));
567 // reset appcache max size
568 appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
571 private String getFactoryResetHomeUrl(Context context) {
572 String url = context.getResources().getString(R.string.homepage_base);
573 if (url.indexOf("{CID}") != -1) {
574 url = url.replace("{CID}", Partner.getString(context
575 .getContentResolver(), Partner.CLIENT_ID, "android-google"));
580 // Private constructor that does nothing.
581 private BrowserSettings() {