BrowserSettings.java revision dc62cb9c7a75ab767e03baa5464a14d34a6312e2
1
2/*
3 * Copyright (C) 2007 The Android Open Source Project
4 *
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
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
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.
16 */
17
18package com.android.browser;
19
20import com.android.browser.search.SearchEngine;
21import com.android.browser.search.SearchEngines;
22
23import android.app.ActivityManager;
24import android.content.ComponentName;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.pm.ActivityInfo;
28import android.content.SharedPreferences;
29import android.content.SharedPreferences.Editor;
30import android.database.ContentObserver;
31import android.database.Cursor;
32import android.net.Uri;
33import android.os.AsyncTask;
34import android.os.Handler;
35import android.os.Message;
36import android.preference.PreferenceActivity;
37import android.preference.PreferenceManager;
38import android.preference.PreferenceScreen;
39import android.provider.Browser;
40import android.provider.Settings;
41import android.util.Log;
42import android.webkit.CookieManager;
43import android.webkit.GeolocationPermissions;
44import android.webkit.ValueCallback;
45import android.webkit.WebView;
46import android.webkit.WebViewDatabase;
47import android.webkit.WebIconDatabase;
48import android.webkit.WebSettings;
49import android.webkit.WebSettings.AutoFillProfile;
50import android.webkit.WebStorage;
51import android.widget.Toast;
52
53import java.util.HashMap;
54import java.util.Map;
55import java.util.Set;
56import java.util.Observable;
57
58/*
59 * Package level class for storing various WebView and Browser settings. To use
60 * this class:
61 * BrowserSettings s = BrowserSettings.getInstance();
62 * s.addObserver(webView.getSettings());
63 * s.loadFromDb(context); // Only needed on app startup
64 * s.javaScriptEnabled = true;
65 * ... // set any other settings
66 * s.update(); // this will update all the observers
67 *
68 * To remove an observer:
69 * s.deleteObserver(webView.getSettings());
70 */
71public class BrowserSettings extends Observable {
72
73    // Private variables for settings
74    // NOTE: these defaults need to be kept in sync with the XML
75    // until the performance of PreferenceManager.setDefaultValues()
76    // is improved.
77    // Note: boolean variables are set inside reset function.
78    private boolean loadsImagesAutomatically;
79    private boolean javaScriptEnabled;
80    private WebSettings.PluginState pluginState;
81    private boolean javaScriptCanOpenWindowsAutomatically;
82    private boolean showSecurityWarnings;
83    private boolean rememberPasswords;
84    private boolean saveFormData;
85    private boolean autoFillEnabled;
86    private boolean openInBackground;
87    private String defaultTextEncodingName;
88    private String homeUrl = "";
89    private SearchEngine searchEngine;
90    private boolean autoFitPage;
91    private boolean loadsPageInOverviewMode;
92    private boolean showDebugSettings;
93    // HTML5 API flags
94    private boolean appCacheEnabled;
95    private boolean databaseEnabled;
96    private boolean domStorageEnabled;
97    private boolean geolocationEnabled;
98    private boolean workersEnabled;  // only affects V8. JSC does not have a similar setting
99    // HTML5 API configuration params
100    private long appCacheMaxSize = Long.MAX_VALUE;
101    private String appCachePath;  // default value set in loadFromDb().
102    private String databasePath; // default value set in loadFromDb()
103    private String geolocationDatabasePath; // default value set in loadFromDb()
104    private WebStorageSizeManager webStorageSizeManager;
105
106    private String jsFlags = "";
107
108    private final static String TAG = "BrowserSettings";
109
110    // Development settings
111    public WebSettings.LayoutAlgorithm layoutAlgorithm =
112        WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
113    private boolean useWideViewPort = true;
114    private int userAgent = 0;
115    private boolean tracing = false;
116    private boolean lightTouch = false;
117    private boolean navDump = false;
118    private boolean hardwareAccelerated = true;
119
120    // By default the error console is shown once the user navigates to about:debug.
121    // The setting can be then toggled from the settings menu.
122    private boolean showConsole = true;
123
124    // Private preconfigured values
125    private static int minimumFontSize = 1;
126    private static int minimumLogicalFontSize = 1;
127    private static int defaultFontSize = 16;
128    private static int defaultFixedFontSize = 13;
129    private static WebSettings.TextSize textSize =
130        WebSettings.TextSize.NORMAL;
131    private static WebSettings.ZoomDensity zoomDensity =
132        WebSettings.ZoomDensity.MEDIUM;
133    private static int pageCacheCapacity;
134
135
136    private AutoFillProfile autoFillProfile;
137    // Default to zero. In the case no profile is set up, the initial
138    // value will come from the AutoFillSettingsFragment when the user
139    // creates a profile. Otherwise, we'll read the ID of the last used
140    // profile from the prefs db.
141    private int autoFillActiveProfileId;
142    private static final int NO_AUTOFILL_PROFILE_SET = 0;
143
144    // Preference keys that are used outside this class
145    public final static String PREF_CLEAR_CACHE = "privacy_clear_cache";
146    public final static String PREF_CLEAR_COOKIES = "privacy_clear_cookies";
147    public final static String PREF_CLEAR_HISTORY = "privacy_clear_history";
148    public final static String PREF_HOMEPAGE = "homepage";
149    public final static String PREF_SEARCH_ENGINE = "search_engine";
150    public final static String PREF_CLEAR_FORM_DATA =
151            "privacy_clear_form_data";
152    public final static String PREF_CLEAR_PASSWORDS =
153            "privacy_clear_passwords";
154    public final static String PREF_EXTRAS_RESET_DEFAULTS =
155            "reset_default_preferences";
156    public final static String PREF_DEBUG_SETTINGS = "debug_menu";
157    public final static String PREF_WEBSITE_SETTINGS = "website_settings";
158    public final static String PREF_TEXT_SIZE = "text_size";
159    public final static String PREF_DEFAULT_ZOOM = "default_zoom";
160    public final static String PREF_DEFAULT_TEXT_ENCODING =
161            "default_text_encoding";
162    public final static String PREF_CLEAR_GEOLOCATION_ACCESS =
163            "privacy_clear_geolocation_access";
164    public final static String PREF_AUTOFILL_ENABLED = "autofill_enabled";
165    public final static String PREF_AUTOFILL_PROFILE = "autofill_profile";
166    public final static String PREF_AUTOFILL_ACTIVE_PROFILE_ID = "autofill_active_profile_id";
167
168    private static final String DESKTOP_USERAGENT = "Mozilla/5.0 (Macintosh; " +
169            "U; Intel Mac OS X 10_6_3; en-us) AppleWebKit/533.16 (KHTML, " +
170            "like Gecko) Version/5.0 Safari/533.16";
171
172    private static final String IPHONE_USERAGENT = "Mozilla/5.0 (iPhone; U; " +
173            "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 " +
174            "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7";
175
176    private static final String IPAD_USERAGENT = "Mozilla/5.0 (iPad; U; " +
177            "CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 " +
178            "(KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10";
179
180    private static final String FROYO_USERAGENT = "Mozilla/5.0 (Linux; U; " +
181            "Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 " +
182            "(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
183
184    // Value to truncate strings when adding them to a TextView within
185    // a ListView
186    public final static int MAX_TEXTVIEW_LEN = 80;
187
188    public static final String RLZ_PROVIDER = "com.google.android.partnersetup.rlzappprovider";
189
190    public static final Uri RLZ_PROVIDER_URI = Uri.parse("content://" + RLZ_PROVIDER + "/");
191
192    private Controller mController;
193
194    // Single instance of the BrowserSettings for use in the Browser app.
195    private static BrowserSettings sSingleton;
196
197    // Private map of WebSettings to Observer objects used when deleting an
198    // observer.
199    private HashMap<WebSettings,Observer> mWebSettingsToObservers =
200        new HashMap<WebSettings,Observer>();
201
202    /*
203     * An observer wrapper for updating a WebSettings object with the new
204     * settings after a call to BrowserSettings.update().
205     */
206    static class Observer implements java.util.Observer {
207        // Private WebSettings object that will be updated.
208        private WebSettings mSettings;
209
210        Observer(WebSettings w) {
211            mSettings = w;
212        }
213
214        public void update(Observable o, Object arg) {
215            BrowserSettings b = (BrowserSettings)o;
216            WebSettings s = mSettings;
217
218            s.setLayoutAlgorithm(b.layoutAlgorithm);
219            if (b.userAgent == 0) {
220                // use the default ua string
221                s.setUserAgentString(null);
222            } else if (b.userAgent == 1) {
223                s.setUserAgentString(DESKTOP_USERAGENT);
224            } else if (b.userAgent == 2) {
225                s.setUserAgentString(IPHONE_USERAGENT);
226            } else if (b.userAgent == 3) {
227                s.setUserAgentString(IPAD_USERAGENT);
228            } else if (b.userAgent == 4) {
229                s.setUserAgentString(FROYO_USERAGENT);
230            }
231            s.setUseWideViewPort(b.useWideViewPort);
232            s.setLoadsImagesAutomatically(b.loadsImagesAutomatically);
233            s.setJavaScriptEnabled(b.javaScriptEnabled);
234            s.setPluginState(b.pluginState);
235            s.setJavaScriptCanOpenWindowsAutomatically(
236                    b.javaScriptCanOpenWindowsAutomatically);
237            s.setDefaultTextEncodingName(b.defaultTextEncodingName);
238            s.setMinimumFontSize(b.minimumFontSize);
239            s.setMinimumLogicalFontSize(b.minimumLogicalFontSize);
240            s.setDefaultFontSize(b.defaultFontSize);
241            s.setDefaultFixedFontSize(b.defaultFixedFontSize);
242            s.setNavDump(b.navDump);
243            s.setTextSize(b.textSize);
244            s.setDefaultZoom(b.zoomDensity);
245            s.setLightTouchEnabled(b.lightTouch);
246            s.setSaveFormData(b.saveFormData);
247            s.setAutoFillEnabled(b.autoFillEnabled);
248            s.setSavePassword(b.rememberPasswords);
249            s.setLoadWithOverviewMode(b.loadsPageInOverviewMode);
250            s.setPageCacheCapacity(pageCacheCapacity);
251
252            // WebView inside Browser doesn't want initial focus to be set.
253            s.setNeedInitialFocus(false);
254            // Browser supports multiple windows
255            s.setSupportMultipleWindows(true);
256            // enable smooth transition for better performance during panning or
257            // zooming
258            s.setEnableSmoothTransition(true);
259
260            // HTML5 API flags
261            s.setAppCacheEnabled(b.appCacheEnabled);
262            s.setDatabaseEnabled(b.databaseEnabled);
263            s.setDomStorageEnabled(b.domStorageEnabled);
264            s.setWorkersEnabled(b.workersEnabled);  // This only affects V8.
265            s.setGeolocationEnabled(b.geolocationEnabled);
266
267            // HTML5 configuration parameters.
268            s.setAppCacheMaxSize(b.appCacheMaxSize);
269            s.setAppCachePath(b.appCachePath);
270            s.setDatabasePath(b.databasePath);
271            s.setGeolocationDatabasePath(b.geolocationDatabasePath);
272
273            // Active AutoFill profile data.
274            s.setAutoFillProfile(b.autoFillProfile);
275
276            b.updateTabControlSettings();
277        }
278    }
279
280    /**
281     * Load settings from the browser app's database.
282     * NOTE: Strings used for the preferences must match those specified
283     * in the various preference XML files.
284     * @param ctx A Context object used to query the browser's settings
285     *            database. If the database exists, the saved settings will be
286     *            stored in this BrowserSettings object. This will update all
287     *            observers of this object.
288     */
289    public void loadFromDb(final Context ctx) {
290        SharedPreferences p =
291                PreferenceManager.getDefaultSharedPreferences(ctx);
292        // Set the default value for the Application Caches path.
293        appCachePath = ctx.getDir("appcache", 0).getPath();
294        // Determine the maximum size of the application cache.
295        webStorageSizeManager = new WebStorageSizeManager(
296                ctx,
297                new WebStorageSizeManager.StatFsDiskInfo(appCachePath),
298                new WebStorageSizeManager.WebKitAppCacheInfo(appCachePath));
299        appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
300        // Set the default value for the Database path.
301        databasePath = ctx.getDir("databases", 0).getPath();
302        // Set the default value for the Geolocation database path.
303        geolocationDatabasePath = ctx.getDir("geolocation", 0).getPath();
304
305        if (p.getString(PREF_HOMEPAGE, "") == "") {
306            // No home page preferences is set, set it to default.
307            setHomePage(ctx, getFactoryResetHomeUrl(ctx));
308        }
309
310        // the cost of one cached page is ~3M (measured using nytimes.com). For
311        // low end devices, we only cache one page. For high end devices, we try
312        // to cache more pages, currently choose 5.
313        ActivityManager am = (ActivityManager) ctx
314                .getSystemService(Context.ACTIVITY_SERVICE);
315        if (am.getMemoryClass() > 16) {
316            pageCacheCapacity = 5;
317        } else {
318            pageCacheCapacity = 1;
319        }
320
321        // Read the last active AutoFill profile id.
322        autoFillActiveProfileId = p.getInt(
323                PREF_AUTOFILL_ACTIVE_PROFILE_ID, autoFillActiveProfileId);
324
325        // Load the autofill profile data from the database. We use a database separate
326        // to the browser preference DB to make it easier to support multiple profiles
327        // and switching between them.
328        AutoFillProfileDatabase autoFillDb = AutoFillProfileDatabase.getInstance(ctx);
329        Cursor c = autoFillDb.getProfile(autoFillActiveProfileId);
330
331        if (c.getCount() > 0) {
332            c.moveToFirst();
333
334            String fullName = c.getString(c.getColumnIndex(
335                    AutoFillProfileDatabase.Profiles.FULL_NAME));
336            String email = c.getString(c.getColumnIndex(
337                    AutoFillProfileDatabase.Profiles.EMAIL_ADDRESS));
338            String company = c.getString(c.getColumnIndex(
339                    AutoFillProfileDatabase.Profiles.COMPANY_NAME));
340            String addressLine1 = c.getString(c.getColumnIndex(
341                    AutoFillProfileDatabase.Profiles.ADDRESS_LINE_1));
342            String addressLine2 = c.getString(c.getColumnIndex(
343                    AutoFillProfileDatabase.Profiles.ADDRESS_LINE_2));
344            String city = c.getString(c.getColumnIndex(
345                    AutoFillProfileDatabase.Profiles.CITY));
346            String state = c.getString(c.getColumnIndex(
347                    AutoFillProfileDatabase.Profiles.STATE));
348            String zip = c.getString(c.getColumnIndex(
349                    AutoFillProfileDatabase.Profiles.ZIP_CODE));
350            String country = c.getString(c.getColumnIndex(
351                    AutoFillProfileDatabase.Profiles.COUNTRY));
352            String phone = c.getString(c.getColumnIndex(
353                    AutoFillProfileDatabase.Profiles.PHONE_NUMBER));
354            autoFillProfile = new AutoFillProfile(autoFillActiveProfileId,
355                    fullName, email, company, addressLine1, addressLine2, city,
356                    state, zip, country, phone);
357        }
358        c.close();
359        autoFillDb.close();
360
361        // PreferenceManager.setDefaultValues is TOO SLOW, need to manually keep
362        // the defaults in sync
363        syncSharedPreferences(ctx, p);
364    }
365
366    /* package */ void syncSharedPreferences(Context ctx, SharedPreferences p) {
367
368        homeUrl =
369            p.getString(PREF_HOMEPAGE, homeUrl);
370        String searchEngineName = p.getString(PREF_SEARCH_ENGINE,
371                SearchEngine.GOOGLE);
372        if (searchEngine == null || !searchEngine.getName().equals(searchEngineName)) {
373            if (searchEngine != null) {
374                if (searchEngine.supportsVoiceSearch()) {
375                    // One or more tabs could have been in voice search mode.
376                    // Clear it, since the new SearchEngine may not support
377                    // it, or may handle it differently.
378                    for (int i = 0; i < mController.getTabControl().getTabCount(); i++) {
379                        mController.getTabControl().getTab(i).revertVoiceSearchMode();
380                    }
381                }
382                searchEngine.close();
383            }
384            searchEngine = SearchEngines.get(ctx, searchEngineName);
385        }
386        Log.i(TAG, "Selected search engine: " + searchEngine);
387
388        loadsImagesAutomatically = p.getBoolean("load_images",
389                loadsImagesAutomatically);
390        javaScriptEnabled = p.getBoolean("enable_javascript",
391                javaScriptEnabled);
392        pluginState = WebSettings.PluginState.valueOf(
393                p.getString("plugin_state", pluginState.name()));
394        javaScriptCanOpenWindowsAutomatically = !p.getBoolean(
395            "block_popup_windows",
396            !javaScriptCanOpenWindowsAutomatically);
397        showSecurityWarnings = p.getBoolean("show_security_warnings",
398                showSecurityWarnings);
399        rememberPasswords = p.getBoolean("remember_passwords",
400                rememberPasswords);
401        saveFormData = p.getBoolean("save_formdata",
402                saveFormData);
403        autoFillEnabled = p.getBoolean("autofill_enabled", autoFillEnabled);
404        boolean accept_cookies = p.getBoolean("accept_cookies",
405                CookieManager.getInstance().acceptCookie());
406        CookieManager.getInstance().setAcceptCookie(accept_cookies);
407        openInBackground = p.getBoolean("open_in_background", openInBackground);
408        textSize = WebSettings.TextSize.valueOf(
409                p.getString(PREF_TEXT_SIZE, textSize.name()));
410        zoomDensity = WebSettings.ZoomDensity.valueOf(
411                p.getString(PREF_DEFAULT_ZOOM, zoomDensity.name()));
412        autoFitPage = p.getBoolean("autofit_pages", autoFitPage);
413        loadsPageInOverviewMode = p.getBoolean("load_page",
414                loadsPageInOverviewMode);
415        useWideViewPort = true; // use wide view port for either setting
416        if (autoFitPage) {
417            layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
418        } else {
419            layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
420        }
421        defaultTextEncodingName =
422                p.getString(PREF_DEFAULT_TEXT_ENCODING,
423                        defaultTextEncodingName);
424
425        showDebugSettings =
426                p.getBoolean(PREF_DEBUG_SETTINGS, showDebugSettings);
427        // Debug menu items have precidence if the menu is visible
428        if (showDebugSettings) {
429            boolean small_screen = p.getBoolean("small_screen",
430                    layoutAlgorithm ==
431                    WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
432            if (small_screen) {
433                layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;
434            } else {
435                boolean normal_layout = p.getBoolean("normal_layout",
436                        layoutAlgorithm == WebSettings.LayoutAlgorithm.NORMAL);
437                if (normal_layout) {
438                    layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL;
439                } else {
440                    layoutAlgorithm =
441                            WebSettings.LayoutAlgorithm.NARROW_COLUMNS;
442                }
443            }
444            useWideViewPort = p.getBoolean("wide_viewport", useWideViewPort);
445            tracing = p.getBoolean("enable_tracing", tracing);
446            lightTouch = p.getBoolean("enable_light_touch", lightTouch);
447            navDump = p.getBoolean("enable_nav_dump", navDump);
448            userAgent = Integer.parseInt(p.getString("user_agent", "0"));
449        }
450
451        // This setting can only be modified when the debug settings have been
452        // enabled but it is read and used by the browser at startup so we must
453        // initialize it regardless of the status of the debug settings.
454        hardwareAccelerated = p.getBoolean("enable_hardware_accel", hardwareAccelerated);
455
456        // JS flags is loaded from DB even if showDebugSettings is false,
457        // so that it can be set once and be effective all the time.
458        jsFlags = p.getString("js_engine_flags", "");
459
460        // Read the setting for showing/hiding the JS Console always so that should the
461        // user enable debug settings, we already know if we should show the console.
462        // The user will never see the console unless they navigate to about:debug,
463        // regardless of the setting we read here. This setting is only used after debug
464        // is enabled.
465        showConsole = p.getBoolean("javascript_console", showConsole);
466
467        // HTML5 API flags
468        appCacheEnabled = p.getBoolean("enable_appcache", appCacheEnabled);
469        databaseEnabled = p.getBoolean("enable_database", databaseEnabled);
470        domStorageEnabled = p.getBoolean("enable_domstorage", domStorageEnabled);
471        geolocationEnabled = p.getBoolean("enable_geolocation", geolocationEnabled);
472        workersEnabled = p.getBoolean("enable_workers", workersEnabled);
473
474        update();
475    }
476
477    public String getHomePage() {
478        return homeUrl;
479    }
480
481    public SearchEngine getSearchEngine() {
482        return searchEngine;
483    }
484
485    public String getJsFlags() {
486        return jsFlags;
487    }
488
489    public WebStorageSizeManager getWebStorageSizeManager() {
490        return webStorageSizeManager;
491    }
492
493    public void setHomePage(Context context, String url) {
494        Editor ed = PreferenceManager.
495                getDefaultSharedPreferences(context).edit();
496        ed.putString(PREF_HOMEPAGE, url);
497        ed.apply();
498        homeUrl = url;
499    }
500
501    public WebSettings.TextSize getTextSize() {
502        return textSize;
503    }
504
505    public WebSettings.ZoomDensity getDefaultZoom() {
506        return zoomDensity;
507    }
508
509    public boolean openInBackground() {
510        return openInBackground;
511    }
512
513    public boolean showSecurityWarnings() {
514        return showSecurityWarnings;
515    }
516
517    public boolean isTracing() {
518        return tracing;
519    }
520
521    public boolean isLightTouch() {
522        return lightTouch;
523    }
524
525    public boolean isNavDump() {
526        return navDump;
527    }
528
529    public boolean isHardwareAccelerated() {
530        return hardwareAccelerated;
531    }
532
533    public boolean showDebugSettings() {
534        return showDebugSettings;
535    }
536
537    public void toggleDebugSettings() {
538        showDebugSettings = !showDebugSettings;
539        navDump = showDebugSettings;
540        update();
541    }
542
543    public void setAutoFillProfile(Context ctx, AutoFillProfile profile, Message msg) {
544        if (profile != null) {
545            setActiveAutoFillProfileId(ctx, profile.getUniqueId());
546            // Update the AutoFill DB with the new profile.
547            new SaveProfileToDbTask(ctx, msg).execute(profile);
548        } else {
549            // Delete the current profile.
550            if (autoFillProfile != null) {
551                new DeleteProfileFromDbTask(ctx, msg).execute(autoFillProfile.getUniqueId());
552                setActiveAutoFillProfileId(ctx, NO_AUTOFILL_PROFILE_SET);
553            }
554        }
555        autoFillProfile = profile;
556    }
557
558    public AutoFillProfile getAutoFillProfile() {
559        return autoFillProfile;
560    }
561
562    private void setActiveAutoFillProfileId(Context context, int activeProfileId) {
563        autoFillActiveProfileId = activeProfileId;
564        Editor ed = PreferenceManager.
565            getDefaultSharedPreferences(context).edit();
566        ed.putInt(PREF_AUTOFILL_ACTIVE_PROFILE_ID, activeProfileId);
567        ed.apply();
568    }
569
570    /* package */ void disableAutoFill(Context ctx) {
571        autoFillEnabled = false;
572        Editor ed = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
573        ed.putBoolean(PREF_AUTOFILL_ENABLED, false);
574        ed.apply();
575    }
576
577    /**
578     * Add a WebSettings object to the list of observers that will be updated
579     * when update() is called.
580     *
581     * @param s A WebSettings object that is strictly tied to the life of a
582     *            WebView.
583     */
584    public Observer addObserver(WebSettings s) {
585        Observer old = mWebSettingsToObservers.get(s);
586        if (old != null) {
587            super.deleteObserver(old);
588        }
589        Observer o = new Observer(s);
590        mWebSettingsToObservers.put(s, o);
591        super.addObserver(o);
592        return o;
593    }
594
595    /**
596     * Delete the given WebSettings observer from the list of observers.
597     * @param s The WebSettings object to be deleted.
598     */
599    public void deleteObserver(WebSettings s) {
600        Observer o = mWebSettingsToObservers.get(s);
601        if (o != null) {
602            mWebSettingsToObservers.remove(s);
603            super.deleteObserver(o);
604        }
605    }
606
607    /*
608     * Package level method for obtaining a single app instance of the
609     * BrowserSettings.
610     */
611    /*package*/ static BrowserSettings getInstance() {
612        if (sSingleton == null ) {
613            sSingleton = new BrowserSettings();
614        }
615        return sSingleton;
616    }
617
618    /*
619     * Package level method for associating the BrowserSettings with TabControl
620     */
621    /* package */void setController(Controller ctrl) {
622        mController = ctrl;
623        updateTabControlSettings();
624    }
625
626    /*
627     * Update all the observers of the object.
628     */
629    /*package*/ void update() {
630        setChanged();
631        notifyObservers();
632    }
633
634    /*package*/ void clearCache(Context context) {
635        WebIconDatabase.getInstance().removeAllIcons();
636        if (mController != null) {
637            WebView current = mController.getCurrentWebView();
638            if (current != null) {
639                current.clearCache(true);
640            }
641        }
642    }
643
644    /*package*/ void clearCookies(Context context) {
645        CookieManager.getInstance().removeAllCookie();
646    }
647
648    /* package */void clearHistory(Context context) {
649        ContentResolver resolver = context.getContentResolver();
650        Browser.clearHistory(resolver);
651        Browser.clearSearches(resolver);
652    }
653
654    /* package */ void clearFormData(Context context) {
655        WebViewDatabase.getInstance(context).clearFormData();
656        if (mController!= null) {
657            WebView currentTopView = mController.getCurrentTopWebView();
658            if (currentTopView != null) {
659                currentTopView.clearFormData();
660            }
661        }
662    }
663
664    /*package*/ void clearPasswords(Context context) {
665        WebViewDatabase db = WebViewDatabase.getInstance(context);
666        db.clearUsernamePassword();
667        db.clearHttpAuthUsernamePassword();
668    }
669
670    private void updateTabControlSettings() {
671        // Enable/disable the error console.
672        mController.setShouldShowErrorConsole(
673            showDebugSettings && showConsole);
674    }
675
676    /*package*/ void clearDatabases(Context context) {
677        WebStorage.getInstance().deleteAllData();
678    }
679
680    /*package*/ void clearLocationAccess(Context context) {
681        GeolocationPermissions.getInstance().clearAll();
682    }
683
684    /*package*/ void resetDefaultPreferences(Context ctx) {
685        reset();
686        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(ctx);
687        p.edit().clear().apply();
688        PreferenceManager.setDefaultValues(ctx, R.xml.page_content_preferences, true);
689        PreferenceManager.setDefaultValues(ctx, R.xml.personal_preferences, true);
690        PreferenceManager.setDefaultValues(ctx, R.xml.privacy_preferences, true);
691        PreferenceManager.setDefaultValues(ctx, R.xml.security_preferences, true);
692        PreferenceManager.setDefaultValues(ctx, R.xml.advanced_preferences, true);
693        // reset homeUrl
694        setHomePage(ctx, getFactoryResetHomeUrl(ctx));
695        // reset appcache max size
696        appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
697        setActiveAutoFillProfileId(ctx, NO_AUTOFILL_PROFILE_SET);
698    }
699
700    /*package*/ static String getFactoryResetHomeUrl(Context context) {
701        String url = context.getResources().getString(R.string.homepage_base);
702        if (url.indexOf("{CID}") != -1) {
703            url = url.replace("{CID}",
704                    BrowserProvider.getClientId(context.getContentResolver()));
705        }
706        return url;
707    }
708
709    // Private constructor that does nothing.
710    private BrowserSettings() {
711        reset();
712    }
713
714    private void reset() {
715        // Private variables for settings
716        // NOTE: these defaults need to be kept in sync with the XML
717        // until the performance of PreferenceManager.setDefaultValues()
718        // is improved.
719        loadsImagesAutomatically = true;
720        javaScriptEnabled = true;
721        pluginState = WebSettings.PluginState.ON;
722        javaScriptCanOpenWindowsAutomatically = false;
723        showSecurityWarnings = true;
724        rememberPasswords = true;
725        saveFormData = true;
726        autoFillEnabled = true;
727        openInBackground = false;
728        autoFitPage = true;
729        loadsPageInOverviewMode = true;
730        showDebugSettings = false;
731        // HTML5 API flags
732        appCacheEnabled = true;
733        databaseEnabled = true;
734        domStorageEnabled = true;
735        geolocationEnabled = true;
736        workersEnabled = true;  // only affects V8. JSC does not have a similar setting
737    }
738
739    private abstract class AutoFillProfileDbTask<T> extends AsyncTask<T, Void, Void> {
740        Context mContext;
741        AutoFillProfileDatabase mAutoFillProfileDb;
742        Message mCompleteMessage;
743
744        public AutoFillProfileDbTask(Context ctx, Message msg) {
745            mContext = ctx;
746            mCompleteMessage = msg;
747        }
748
749        protected void onPostExecute(Void result) {
750            if (mCompleteMessage != null) {
751                mCompleteMessage.sendToTarget();
752            }
753            mAutoFillProfileDb.close();
754        }
755
756        abstract protected Void doInBackground(T... values);
757    }
758
759
760    private class SaveProfileToDbTask extends AutoFillProfileDbTask<AutoFillProfile> {
761        public SaveProfileToDbTask(Context ctx, Message msg) {
762            super(ctx, msg);
763        }
764
765        protected Void doInBackground(AutoFillProfile... values) {
766            mAutoFillProfileDb = AutoFillProfileDatabase.getInstance(mContext);
767            assert autoFillActiveProfileId != NO_AUTOFILL_PROFILE_SET;
768            AutoFillProfile newProfile = values[0];
769            mAutoFillProfileDb.addOrUpdateProfile(autoFillActiveProfileId, newProfile);
770            return null;
771        }
772    }
773
774    private class DeleteProfileFromDbTask extends AutoFillProfileDbTask<Integer> {
775        public DeleteProfileFromDbTask(Context ctx, Message msg) {
776            super(ctx, msg);
777        }
778
779        protected Void doInBackground(Integer... values) {
780            mAutoFillProfileDb = AutoFillProfileDatabase.getInstance(mContext);
781            int id = values[0];
782            assert  id > 0;
783            mAutoFillProfileDb.dropProfile(id);
784            return null;
785        }
786    }
787}
788