OSDN Git Service

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