OSDN Git Service

Removes unnecessary syncing of databse and app cache paths with browser settings...
[android-x86/packages-apps-Browser.git] / src / com / android / browser / BrowserSettings.java
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.android.browser;
18
19 import com.google.android.providers.GoogleSettings.Partner;
20
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;
37
38 import java.util.Set;
39 import java.util.HashMap;
40 import java.util.Observable;
41
42 /*
43  * Package level class for storing various WebView and Browser settings. To use
44  * this class:
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
51  *
52  * To remove an observer:
53  * s.deleteObserver(webView.getSettings());
54  */
55 class BrowserSettings extends Observable {
56
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()
60     // is improved.
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;
77     // HTML5 API flags
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;
88
89     private String jsFlags = "";
90
91     private final static String TAG = "BrowserSettings";
92
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;
101
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;
105
106     // Browser only settings
107     private boolean doFlick = false;
108
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;
118
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";
138
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";
142
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";
146
147     // Value to truncate strings when adding them to a TextView within
148     // a ListView
149     public final static int MAX_TEXTVIEW_LEN = 80;
150
151     private TabControl mTabControl;
152
153     // Single instance of the BrowserSettings for use in the Browser app.
154     private static BrowserSettings sSingleton;
155
156     // Private map of WebSettings to Observer objects used when deleting an
157     // observer.
158     private HashMap<WebSettings,Observer> mWebSettingsToObservers =
159         new HashMap<WebSettings,Observer>();
160
161     /*
162      * An observer wrapper for updating a WebSettings object with the new
163      * settings after a call to BrowserSettings.update().
164      */
165     static class Observer implements java.util.Observer {
166         // Private WebSettings object that will be updated.
167         private WebSettings mSettings;
168
169         Observer(WebSettings w) {
170             mSettings = w;
171         }
172
173         public void update(Observable o, Object arg) {
174             BrowserSettings b = (BrowserSettings)o;
175             WebSettings s = mSettings;
176
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);
185             }
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);
204
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);
211
212             // HTML5 API flags
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);
218
219             // HTML5 configuration parameters.
220             s.setAppCacheMaxSize(b.appCacheMaxSize);
221             s.setAppCachePath(b.appCachePath);
222             s.setDatabasePath(b.databasePath);
223
224             // Enable/Disable the error console.
225             b.mTabControl.getBrowserActivity().setShouldShowErrorConsole(
226                     b.showDebugSettings && b.showConsole);
227         }
228     }
229
230     /**
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.
238      */
239     public void loadFromDb(Context ctx) {
240         SharedPreferences p =
241                 PreferenceManager.getDefaultSharedPreferences(ctx);
242
243         // Set the default value for the plugins path to the application's
244         // local directory.
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(
250                 ctx,
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();
256
257         homeUrl = getFactoryResetHomeUrl(ctx);
258
259         // Load the defaults from the xml
260         // This call is TOO SLOW, need to manually keep the defaults
261         // in sync
262         //PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences);
263         syncSharedPreferences(p);
264     }
265
266     /* package */ void syncSharedPreferences(SharedPreferences p) {
267
268         homeUrl =
269             p.getString(PREF_HOMEPAGE, homeUrl);
270
271         loadsImagesAutomatically = p.getBoolean("load_images",
272                 loadsImagesAutomatically);
273         javaScriptEnabled = p.getBoolean("enable_javascript",
274                 javaScriptEnabled);
275         pluginsEnabled = p.getBoolean("enable_plugins",
276                 pluginsEnabled);
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",
284                 rememberPasswords);
285         saveFormData = p.getBoolean("save_formdata",
286                 saveFormData);
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);
306         }
307         useWideViewPort = true; // use wide view port for either setting
308         if (autoFitPage) {
309             layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
310         } else {
311             layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
312         }
313         defaultTextEncodingName =
314                 p.getString(PREF_DEFAULT_TEXT_ENCODING,
315                         defaultTextEncodingName);
316
317         showDebugSettings =
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",
322                     layoutAlgorithm ==
323                     WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
324             if (small_screen) {
325                 layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
326             } else {
327                 boolean normal_layout = p.getBoolean("normal_layout",
328                         layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
329                 if (normal_layout) {
330                     layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
331                 } else {
332                     layoutAlgorithm =
333                             WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
334                 }
335             }
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"));
342         }
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", "");
346
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
351         // is enabled.
352         showConsole = p.getBoolean("javascript_console", showConsole);
353         mTabControl.getBrowserActivity().setShouldShowErrorConsole(
354                 showDebugSettings && showConsole);
355
356         // HTML5 API flags
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);
362
363         update();
364     }
365
366     public String getPluginsPath() {
367         return pluginsPath;
368     }
369
370     public String getHomePage() {
371         return homeUrl;
372     }
373
374     public String getJsFlags() {
375         return jsFlags;
376     }
377
378     public WebStorageSizeManager getWebStorageSizeManager() {
379         return webStorageSizeManager;
380     }
381
382     public void setHomePage(Context context, String url) {
383         Editor ed = PreferenceManager.
384                 getDefaultSharedPreferences(context).edit();
385         ed.putString(PREF_HOMEPAGE, url);
386         ed.commit();
387         homeUrl = url;
388     }
389
390     public boolean isLoginInitialized() {
391         return loginInitialized;
392     }
393
394     public void setLoginInitialized(Context context) {
395         loginInitialized = true;
396         Editor ed = PreferenceManager.
397                 getDefaultSharedPreferences(context).edit();
398         ed.putBoolean("login_initialized", loginInitialized);
399         ed.commit();
400     }
401
402     public WebSettings.TextSize getTextSize() {
403         return textSize;
404     }
405
406     public WebSettings.ZoomDensity getDefaultZoom() {
407         return zoomDensity;
408     }
409
410     public boolean openInBackground() {
411         return openInBackground;
412     }
413
414     public boolean showSecurityWarnings() {
415         return showSecurityWarnings;
416     }
417
418     public boolean isTracing() {
419         return tracing;
420     }
421
422     public boolean isLightTouch() {
423         return lightTouch;
424     }
425
426     public boolean isNavDump() {
427         return navDump;
428     }
429
430     public boolean doFlick() {
431         return doFlick;
432     }
433
434     public boolean showDebugSettings() {
435         return showDebugSettings;
436     }
437
438     public void toggleDebugSettings() {
439         showDebugSettings = !showDebugSettings;
440         navDump = showDebugSettings;
441         update();
442     }
443
444     /**
445      * Add a WebSettings object to the list of observers that will be updated
446      * when update() is called.
447      *
448      * @param s A WebSettings object that is strictly tied to the life of a
449      *            WebView.
450      */
451     public Observer addObserver(WebSettings s) {
452         Observer old = mWebSettingsToObservers.get(s);
453         if (old != null) {
454             super.deleteObserver(old);
455         }
456         Observer o = new Observer(s);
457         mWebSettingsToObservers.put(s, o);
458         super.addObserver(o);
459         return o;
460     }
461
462     /**
463      * Delete the given WebSettings observer from the list of observers.
464      * @param s The WebSettings object to be deleted.
465      */
466     public void deleteObserver(WebSettings s) {
467         Observer o = mWebSettingsToObservers.get(s);
468         if (o != null) {
469             mWebSettingsToObservers.remove(s);
470             super.deleteObserver(o);
471         }
472     }
473
474     /*
475      * Package level method for obtaining a single app instance of the
476      * BrowserSettings.
477      */
478     /*package*/ static BrowserSettings getInstance() {
479         if (sSingleton == null ) {
480             sSingleton = new BrowserSettings();
481         }
482         return sSingleton;
483     }
484
485     /*
486      * Package level method for associating the BrowserSettings with TabControl
487      */
488     /* package */void setTabControl(TabControl tabControl) {
489         mTabControl = tabControl;
490     }
491
492     /*
493      * Update all the observers of the object.
494      */
495     /*package*/ void update() {
496         setChanged();
497         notifyObservers();
498     }
499
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);
506             }
507         }
508     }
509
510     /*package*/ void clearCookies(Context context) {
511         CookieManager.getInstance().removeAllCookie();
512     }
513
514     /* package */void clearHistory(Context context) {
515         ContentResolver resolver = context.getContentResolver();
516         Browser.clearHistory(resolver);
517         Browser.clearSearches(resolver);
518     }
519
520     /* package */ void clearFormData(Context context) {
521         WebViewDatabase.getInstance(context).clearFormData();
522         if (mTabControl != null) {
523             mTabControl.getCurrentTopWebView().clearFormData();
524         }
525     }
526
527     /*package*/ void clearPasswords(Context context) {
528         WebViewDatabase db = WebViewDatabase.getInstance(context);
529         db.clearUsernamePassword();
530         db.clearHttpAuthUsernamePassword();
531     }
532
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);
543         }
544     }
545
546     /*package*/ void clearDatabases(Context context) {
547         WebStorage.getInstance().deleteAllData();
548         maybeDisableWebsiteSettings(context);
549     }
550
551     /*package*/ void clearLocationAccess(Context context) {
552         GeolocationPermissions.getInstance().clearAll();
553         maybeDisableWebsiteSettings(context);
554     }
555
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,
561                 true);
562         // reset homeUrl
563         setHomePage(ctx, getFactoryResetHomeUrl(ctx));
564         // reset appcache max size
565         appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
566     }
567
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"));
573         }
574         return url;
575     }
576
577     // Private constructor that does nothing.
578     private BrowserSettings() {
579     }
580 }