BrowserSettings.java revision f344d03c0b01d30575ba1ddd1ed340705c6f5a97
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
17package com.android.browser;
18
19import com.google.android.providers.GoogleSettings.Partner;
20
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.pm.ActivityInfo;
24import android.content.SharedPreferences;
25import android.content.SharedPreferences.Editor;
26import android.preference.PreferenceActivity;
27import android.preference.PreferenceScreen;
28import android.webkit.CookieManager;
29import android.webkit.GeolocationPermissions;
30import android.webkit.WebView;
31import android.webkit.WebViewDatabase;
32import android.webkit.WebIconDatabase;
33import android.webkit.WebSettings;
34import android.webkit.WebStorage;
35import android.preference.PreferenceManager;
36import android.provider.Browser;
37
38import java.util.Set;
39import java.util.HashMap;
40import 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 */
55class 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 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;
87
88    private final static String TAG = "BrowserSettings";
89
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;
98
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;
102
103    // Browser only settings
104    private boolean doFlick = false;
105
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;
115
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";
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
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);
210
211            s.setDatabasePath(b.databasePath);
212            s.setDatabaseEnabled(b.databaseEnabled);
213            s.setDomStorageEnabled(b.domStorageEnabled);
214            s.setWebStorageDefaultQuota(b.webStorageDefaultQuota);
215
216            // Turn on Application Caches.
217            s.setAppCachePath(b.appCachePath);
218            s.setAppCacheEnabled(b.appCacheEnabled);
219            s.setAppCacheMaxSize(b.appCacheMaxSize);
220
221            // Enable/Disable the error console.
222            b.mTabControl.getBrowserActivity().setShouldShowErrorConsole(
223                    b.showDebugSettings && b.showConsole);
224
225            // Configure the Geolocation permissions manager to deny all
226            // permission requests if Geolocation is disabled in the browser.
227            // TODO(steveblock): Implement
228        }
229    }
230
231    /**
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.
239     */
240    public void loadFromDb(Context ctx) {
241        SharedPreferences p =
242                PreferenceManager.getDefaultSharedPreferences(ctx);
243
244        // Set the default value for the plugins path to the application's
245        // local directory.
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(
251                ctx,
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();
257
258        homeUrl = getFactoryResetHomeUrl(ctx);
259
260        // Load the defaults from the xml
261        // This call is TOO SLOW, need to manually keep the defaults
262        // in sync
263        //PreferenceManager.setDefaultValues(ctx, R.xml.browser_preferences);
264        syncSharedPreferences(p);
265    }
266
267    /* package */ void syncSharedPreferences(SharedPreferences p) {
268
269        homeUrl =
270            p.getString(PREF_HOMEPAGE, homeUrl);
271
272        loadsImagesAutomatically = p.getBoolean("load_images",
273                loadsImagesAutomatically);
274        javaScriptEnabled = p.getBoolean("enable_javascript",
275                javaScriptEnabled);
276        pluginsEnabled = p.getBoolean("enable_plugins",
277                pluginsEnabled);
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",
284                appCacheEnabled);
285        domStorageEnabled = p.getBoolean("enable_domstorage",
286                domStorageEnabled);
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",
294                rememberPasswords);
295        saveFormData = p.getBoolean("save_formdata",
296                saveFormData);
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);
314        }
315        useWideViewPort = true; // use wide view port for either setting
316        if (autoFitPage) {
317            layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
318        } else {
319            layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
320        }
321        defaultTextEncodingName =
322                p.getString(PREF_DEFAULT_TEXT_ENCODING,
323                        defaultTextEncodingName);
324
325        showDebugSettings =
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",
330                    layoutAlgorithm ==
331                    WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
332            if (small_screen) {
333                layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
334            } else {
335                boolean normal_layout = p.getBoolean("normal_layout",
336                        layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
337                if (normal_layout) {
338                    layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
339                } else {
340                    layoutAlgorithm =
341                            WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
342                }
343            }
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"));
350        }
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", "");
354
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
359        // is enabled.
360        showConsole = p.getBoolean("javascript_console", showConsole);
361        mTabControl.getBrowserActivity().setShouldShowErrorConsole(
362                showDebugSettings && showConsole);
363
364        geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled);
365
366        update();
367    }
368
369    public String getPluginsPath() {
370        return pluginsPath;
371    }
372
373    public String getHomePage() {
374        return homeUrl;
375    }
376
377    public String getJsFlags() {
378        return jsFlags;
379    }
380
381    public WebStorageSizeManager getWebStorageSizeManager() {
382        return webStorageSizeManager;
383    }
384
385    public void setHomePage(Context context, String url) {
386        Editor ed = PreferenceManager.
387                getDefaultSharedPreferences(context).edit();
388        ed.putString(PREF_HOMEPAGE, url);
389        ed.commit();
390        homeUrl = url;
391    }
392
393    public boolean isLoginInitialized() {
394        return loginInitialized;
395    }
396
397    public void setLoginInitialized(Context context) {
398        loginInitialized = true;
399        Editor ed = PreferenceManager.
400                getDefaultSharedPreferences(context).edit();
401        ed.putBoolean("login_initialized", loginInitialized);
402        ed.commit();
403    }
404
405    public WebSettings.TextSize getTextSize() {
406        return textSize;
407    }
408
409    public WebSettings.ZoomDensity getDefaultZoom() {
410        return zoomDensity;
411    }
412
413    public boolean openInBackground() {
414        return openInBackground;
415    }
416
417    public boolean showSecurityWarnings() {
418        return showSecurityWarnings;
419    }
420
421    public boolean isTracing() {
422        return tracing;
423    }
424
425    public boolean isLightTouch() {
426        return lightTouch;
427    }
428
429    public boolean isNavDump() {
430        return navDump;
431    }
432
433    public boolean doFlick() {
434        return doFlick;
435    }
436
437    public boolean showDebugSettings() {
438        return showDebugSettings;
439    }
440
441    public void toggleDebugSettings() {
442        showDebugSettings = !showDebugSettings;
443        navDump = showDebugSettings;
444        update();
445    }
446
447    /**
448     * Add a WebSettings object to the list of observers that will be updated
449     * when update() is called.
450     *
451     * @param s A WebSettings object that is strictly tied to the life of a
452     *            WebView.
453     */
454    public Observer addObserver(WebSettings s) {
455        Observer old = mWebSettingsToObservers.get(s);
456        if (old != null) {
457            super.deleteObserver(old);
458        }
459        Observer o = new Observer(s);
460        mWebSettingsToObservers.put(s, o);
461        super.addObserver(o);
462        return o;
463    }
464
465    /**
466     * Delete the given WebSettings observer from the list of observers.
467     * @param s The WebSettings object to be deleted.
468     */
469    public void deleteObserver(WebSettings s) {
470        Observer o = mWebSettingsToObservers.get(s);
471        if (o != null) {
472            mWebSettingsToObservers.remove(s);
473            super.deleteObserver(o);
474        }
475    }
476
477    /*
478     * Package level method for obtaining a single app instance of the
479     * BrowserSettings.
480     */
481    /*package*/ static BrowserSettings getInstance() {
482        if (sSingleton == null ) {
483            sSingleton = new BrowserSettings();
484        }
485        return sSingleton;
486    }
487
488    /*
489     * Package level method for associating the BrowserSettings with TabControl
490     */
491    /* package */void setTabControl(TabControl tabControl) {
492        mTabControl = tabControl;
493    }
494
495    /*
496     * Update all the observers of the object.
497     */
498    /*package*/ void update() {
499        setChanged();
500        notifyObservers();
501    }
502
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);
509            }
510        }
511    }
512
513    /*package*/ void clearCookies(Context context) {
514        CookieManager.getInstance().removeAllCookie();
515    }
516
517    /* package */void clearHistory(Context context) {
518        ContentResolver resolver = context.getContentResolver();
519        Browser.clearHistory(resolver);
520        Browser.clearSearches(resolver);
521    }
522
523    /* package */ void clearFormData(Context context) {
524        WebViewDatabase.getInstance(context).clearFormData();
525        if (mTabControl != null) {
526            mTabControl.getCurrentTopWebView().clearFormData();
527        }
528    }
529
530    /*package*/ void clearPasswords(Context context) {
531        WebViewDatabase db = WebViewDatabase.getInstance(context);
532        db.clearUsernamePassword();
533        db.clearHttpAuthUsernamePassword();
534    }
535
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);
546        }
547    }
548
549    /*package*/ void clearDatabases(Context context) {
550        WebStorage.getInstance().deleteAllData();
551        maybeDisableWebsiteSettings(context);
552    }
553
554    /*package*/ void clearLocationAccess(Context context) {
555        GeolocationPermissions.getInstance().clearAll();
556        maybeDisableWebsiteSettings(context);
557    }
558
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,
564                true);
565        // reset homeUrl
566        setHomePage(ctx, getFactoryResetHomeUrl(ctx));
567        // reset appcache max size
568        appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
569    }
570
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"));
576        }
577        return url;
578    }
579
580    // Private constructor that does nothing.
581    private BrowserSettings() {
582    }
583}
584