Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / webui / options / browser_options_handler.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/ui/webui/options/browser_options_handler.h"
6
7 #include <string>
8 #include <vector>
9
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/command_line.h"
13 #include "base/environment.h"
14 #include "base/memory/singleton.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/metrics/histogram.h"
17 #include "base/path_service.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/prefs/scoped_user_pref_update.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/value_conversions.h"
24 #include "base/values.h"
25 #include "chrome/browser/auto_launch_trial.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/chrome_page_zoom.h"
29 #include "chrome/browser/custom_home_pages_table_model.h"
30 #include "chrome/browser/download/download_prefs.h"
31 #include "chrome/browser/gpu/gpu_mode_manager.h"
32 #include "chrome/browser/lifetime/application_lifetime.h"
33 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
34 #include "chrome/browser/metrics/metrics_reporting_state.h"
35 #include "chrome/browser/net/prediction_options.h"
36 #include "chrome/browser/prefs/session_startup_pref.h"
37 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
38 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
39 #include "chrome/browser/profiles/profile.h"
40 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
41 #include "chrome/browser/profiles/profile_info_cache.h"
42 #include "chrome/browser/profiles/profile_manager.h"
43 #include "chrome/browser/profiles/profile_metrics.h"
44 #include "chrome/browser/profiles/profile_shortcut_manager.h"
45 #include "chrome/browser/profiles/profile_window.h"
46 #include "chrome/browser/profiles/profiles_state.h"
47 #include "chrome/browser/search/hotword_service.h"
48 #include "chrome/browser/search/hotword_service_factory.h"
49 #include "chrome/browser/search/search.h"
50 #include "chrome/browser/search_engines/template_url_service_factory.h"
51 #include "chrome/browser/signin/easy_unlock_service.h"
52 #include "chrome/browser/signin/signin_manager_factory.h"
53 #include "chrome/browser/sync/profile_sync_service.h"
54 #include "chrome/browser/sync/profile_sync_service_factory.h"
55 #include "chrome/browser/sync/sync_ui_util.h"
56 #include "chrome/browser/themes/theme_service.h"
57 #include "chrome/browser/themes/theme_service_factory.h"
58 #include "chrome/browser/ui/browser_finder.h"
59 #include "chrome/browser/ui/chrome_select_file_policy.h"
60 #include "chrome/browser/ui/host_desktop.h"
61 #include "chrome/browser/ui/webui/favicon_source.h"
62 #include "chrome/browser/ui/webui/options/options_handlers_helper.h"
63 #include "chrome/common/chrome_constants.h"
64 #include "chrome/common/chrome_paths.h"
65 #include "chrome/common/chrome_switches.h"
66 #include "chrome/common/extensions/extension_constants.h"
67 #include "chrome/common/pref_names.h"
68 #include "chrome/common/url_constants.h"
69 #include "chrome/grit/chromium_strings.h"
70 #include "chrome/grit/generated_resources.h"
71 #include "chrome/grit/locale_settings.h"
72 #include "chromeos/chromeos_switches.h"
73 #include "components/search_engines/template_url.h"
74 #include "components/search_engines/template_url_service.h"
75 #include "components/signin/core/browser/signin_manager.h"
76 #include "components/signin/core/common/profile_management_switches.h"
77 #include "components/user_manager/user_type.h"
78 #include "content/public/browser/browser_thread.h"
79 #include "content/public/browser/download_manager.h"
80 #include "content/public/browser/navigation_controller.h"
81 #include "content/public/browser/notification_details.h"
82 #include "content/public/browser/notification_service.h"
83 #include "content/public/browser/notification_source.h"
84 #include "content/public/browser/notification_types.h"
85 #include "content/public/browser/url_data_source.h"
86 #include "content/public/browser/user_metrics.h"
87 #include "content/public/browser/web_contents.h"
88 #include "content/public/common/page_zoom.h"
89 #include "extensions/browser/extension_registry.h"
90 #include "google_apis/gaia/gaia_auth_util.h"
91 #include "google_apis/gaia/google_service_auth_error.h"
92 #include "third_party/skia/include/core/SkBitmap.h"
93 #include "ui/base/l10n/l10n_util.h"
94 #include "ui/base/webui/web_ui_util.h"
95
96 #if !defined(OS_CHROMEOS)
97 #include "chrome/browser/ui/webui/options/advanced_options_utils.h"
98 #endif
99
100 #if defined(OS_CHROMEOS)
101 #include "ash/ash_switches.h"
102 #include "ash/desktop_background/user_wallpaper_delegate.h"
103 #include "ash/magnifier/magnifier_constants.h"
104 #include "ash/shell.h"
105 #include "chrome/browser/browser_process_platform_part.h"
106 #include "chrome/browser/chromeos/accessibility/accessibility_util.h"
107 #include "chrome/browser/chromeos/chromeos_utils.h"
108 #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
109 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
110 #include "chrome/browser/chromeos/profiles/profile_helper.h"
111 #include "chrome/browser/chromeos/reset/metrics.h"
112 #include "chrome/browser/chromeos/settings/cros_settings.h"
113 #include "chrome/browser/chromeos/system/timezone_util.h"
114 #include "chrome/browser/policy/profile_policy_connector.h"
115 #include "chrome/browser/policy/profile_policy_connector_factory.h"
116 #include "chrome/browser/ui/browser_window.h"
117 #include "chromeos/dbus/dbus_thread_manager.h"
118 #include "chromeos/dbus/power_manager_client.h"
119 #include "components/policy/core/common/policy_map.h"
120 #include "components/policy/core/common/policy_namespace.h"
121 #include "components/policy/core/common/policy_service.h"
122 #include "components/user_manager/user.h"
123 #include "components/user_manager/user_manager.h"
124 #include "policy/policy_constants.h"
125 #include "ui/gfx/image/image_skia.h"
126 #endif  // defined(OS_CHROMEOS)
127
128 #if defined(OS_WIN)
129 #include "chrome/browser/extensions/settings_api_helpers.h"
130 #include "chrome/installer/util/auto_launch_util.h"
131 #include "content/public/browser/browser_url_handler.h"
132 #endif  // defined(OS_WIN)
133
134 #if defined(ENABLE_SERVICE_DISCOVERY)
135 #include "chrome/browser/local_discovery/privet_notifications.h"
136 #endif
137
138 using base::UserMetricsAction;
139 using content::BrowserContext;
140 using content::BrowserThread;
141 using content::DownloadManager;
142 using content::OpenURLParams;
143 using content::Referrer;
144 using extensions::Extension;
145 using extensions::ExtensionRegistry;
146
147 namespace {
148
149 #if defined(OS_WIN)
150 void AppendExtensionData(const std::string& key,
151                          const Extension* extension,
152                          base::DictionaryValue* dict) {
153   scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue);
154   details->SetString("id", extension ? extension->id() : std::string());
155   details->SetString("name", extension ? extension->name() : std::string());
156   dict->Set(key, details.release());
157 }
158 #endif  // defined(OS_WIN)
159
160 }  // namespace
161
162 namespace options {
163
164 BrowserOptionsHandler::BrowserOptionsHandler()
165     : page_initialized_(false),
166       template_url_service_(NULL),
167       cloud_print_mdns_ui_enabled_(false),
168       signin_observer_(this),
169       weak_ptr_factory_(this) {
170   default_browser_worker_ = new ShellIntegration::DefaultBrowserWorker(this);
171
172 #if defined(ENABLE_SERVICE_DISCOVERY)
173   cloud_print_mdns_ui_enabled_ = true;
174 #endif  // defined(ENABLE_SERVICE_DISCOVERY)
175 }
176
177 BrowserOptionsHandler::~BrowserOptionsHandler() {
178   ProfileSyncService* sync_service(ProfileSyncServiceFactory::
179       GetInstance()->GetForProfile(Profile::FromWebUI(web_ui())));
180   if (sync_service)
181     sync_service->RemoveObserver(this);
182
183   if (default_browser_worker_.get())
184     default_browser_worker_->ObserverDestroyed();
185   if (template_url_service_)
186     template_url_service_->RemoveObserver(this);
187   // There may be pending file dialogs, we need to tell them that we've gone
188   // away so they don't try and call back to us.
189   if (select_folder_dialog_.get())
190     select_folder_dialog_->ListenerDestroyed();
191 }
192
193 void BrowserOptionsHandler::GetLocalizedValues(base::DictionaryValue* values) {
194   DCHECK(values);
195
196 #if defined(OS_CHROMEOS)
197   const int device_type_resource_id = chromeos::GetChromeDeviceTypeResourceId();
198 #else
199   // TODO(isherman): Set an appropriate device name for non-ChromeOS devices.
200   const int device_type_resource_id = IDS_EASY_UNLOCK_GENERIC_DEVICE_TYPE;
201 #endif  // defined(OS_CHROMEOS)
202
203   static OptionsStringResource resources[] = {
204     { "advancedSectionTitleCloudPrint", IDS_GOOGLE_CLOUD_PRINT },
205     { "currentUserOnly", IDS_OPTIONS_CURRENT_USER_ONLY },
206     { "advancedSectionTitleCertificates",
207       IDS_OPTIONS_ADVANCED_SECTION_TITLE_CERTIFICATES },
208     { "advancedSectionTitleContent",
209       IDS_OPTIONS_ADVANCED_SECTION_TITLE_CONTENT },
210     { "advancedSectionTitleLanguages",
211       IDS_OPTIONS_ADVANCED_SECTION_TITLE_LANGUAGES },
212     { "advancedSectionTitleNetwork",
213       IDS_OPTIONS_ADVANCED_SECTION_TITLE_NETWORK },
214     { "advancedSectionTitlePrivacy",
215       IDS_OPTIONS_ADVANCED_SECTION_TITLE_PRIVACY },
216     { "autofillEnabled", IDS_OPTIONS_AUTOFILL_ENABLE },
217     { "autologinEnabled", IDS_OPTIONS_PASSWORDS_AUTOLOGIN },
218     { "autoOpenFileTypesInfo", IDS_OPTIONS_OPEN_FILE_TYPES_AUTOMATICALLY },
219     { "autoOpenFileTypesResetToDefault",
220       IDS_OPTIONS_AUTOOPENFILETYPES_RESETTODEFAULT },
221     { "changeHomePage", IDS_OPTIONS_CHANGE_HOME_PAGE },
222     { "certificatesManageButton", IDS_OPTIONS_CERTIFICATES_MANAGE_BUTTON },
223     { "customizeSync", IDS_OPTIONS_CUSTOMIZE_SYNC_BUTTON_LABEL },
224     { "defaultFontSizeLabel", IDS_OPTIONS_DEFAULT_FONT_SIZE_LABEL },
225     { "defaultSearchManageEngines", IDS_OPTIONS_DEFAULTSEARCH_MANAGE_ENGINES },
226     { "defaultZoomFactorLabel", IDS_OPTIONS_DEFAULT_ZOOM_LEVEL_LABEL },
227 #if defined(OS_CHROMEOS)
228     { "disableGData", IDS_OPTIONS_DISABLE_GDATA },
229 #endif
230     { "disableWebServices", IDS_OPTIONS_DISABLE_WEB_SERVICES },
231 #if defined(OS_CHROMEOS)
232     { "displayOptions",
233       IDS_OPTIONS_SETTINGS_DISPLAY_OPTIONS_BUTTON_LABEL },
234 #endif
235     { "doNotTrack", IDS_OPTIONS_ENABLE_DO_NOT_TRACK },
236     { "doNotTrackConfirmMessage", IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_TEXT },
237     { "doNotTrackConfirmEnable",
238        IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_ENABLE },
239     { "doNotTrackConfirmDisable",
240        IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_DISABLE },
241     { "downloadLocationAskForSaveLocation",
242       IDS_OPTIONS_DOWNLOADLOCATION_ASKFORSAVELOCATION },
243     { "downloadLocationBrowseTitle",
244       IDS_OPTIONS_DOWNLOADLOCATION_BROWSE_TITLE },
245     { "downloadLocationChangeButton",
246       IDS_OPTIONS_DOWNLOADLOCATION_CHANGE_BUTTON },
247     { "downloadLocationGroupName", IDS_OPTIONS_DOWNLOADLOCATION_GROUP_NAME },
248     { "enableLogging", IDS_OPTIONS_ENABLE_LOGGING },
249     { "metricsReportingResetRestart", IDS_OPTIONS_ENABLE_LOGGING_RESTART },
250     { "easyUnlockDescription", IDS_OPTIONS_EASY_UNLOCK_DESCRIPTION,
251       device_type_resource_id },
252     { "easyUnlockSectionTitle", IDS_OPTIONS_EASY_UNLOCK_SECTION_TITLE },
253     { "easyUnlockSetupButton", IDS_OPTIONS_EASY_UNLOCK_SETUP_BUTTON },
254     { "easyUnlockSetupIntro", IDS_OPTIONS_EASY_UNLOCK_SETUP_INTRO,
255       device_type_resource_id },
256     { "extensionControlled", IDS_OPTIONS_TAB_EXTENSION_CONTROLLED },
257     { "extensionDisable", IDS_OPTIONS_TAB_EXTENSION_CONTROLLED_DISABLE },
258     { "fontSettingsCustomizeFontsButton",
259       IDS_OPTIONS_FONTSETTINGS_CUSTOMIZE_FONTS_BUTTON },
260     { "fontSizeLabelCustom", IDS_OPTIONS_FONT_SIZE_LABEL_CUSTOM },
261     { "fontSizeLabelLarge", IDS_OPTIONS_FONT_SIZE_LABEL_LARGE },
262     { "fontSizeLabelMedium", IDS_OPTIONS_FONT_SIZE_LABEL_MEDIUM },
263     { "fontSizeLabelSmall", IDS_OPTIONS_FONT_SIZE_LABEL_SMALL },
264     { "fontSizeLabelVeryLarge", IDS_OPTIONS_FONT_SIZE_LABEL_VERY_LARGE },
265     { "fontSizeLabelVerySmall", IDS_OPTIONS_FONT_SIZE_LABEL_VERY_SMALL },
266     { "hideAdvancedSettings", IDS_SETTINGS_HIDE_ADVANCED_SETTINGS },
267     { "homePageNtp", IDS_OPTIONS_HOMEPAGE_NTP },
268     { "homePageShowHomeButton", IDS_OPTIONS_TOOLBAR_SHOW_HOME_BUTTON },
269     { "homePageUseNewTab", IDS_OPTIONS_HOMEPAGE_USE_NEWTAB },
270     { "homePageUseURL", IDS_OPTIONS_HOMEPAGE_USE_URL },
271     { "hotwordAlwaysOnSearchEnable", IDS_HOTWORD_ALWAYS_ON_SEARCH_PREF_CHKBOX },
272     { "hotwordAudioHistoryEnable", IDS_HOTWORD_AUDIO_HISTORY_PREF_CHKBOX },
273     { "hotwordSearchEnable", IDS_HOTWORD_SEARCH_PREF_CHKBOX },
274     { "hotwordConfirmEnable", IDS_HOTWORD_CONFIRM_BUBBLE_ENABLE },
275     { "hotwordConfirmDisable", IDS_HOTWORD_CONFIRM_BUBBLE_DISABLE },
276     { "hotwordConfirmMessage", IDS_HOTWORD_SEARCH_PREF_DESCRIPTION },
277     { "hotwordAudioLoggingEnable", IDS_HOTWORD_AUDIO_LOGGING_ENABLE },
278     { "importData", IDS_OPTIONS_IMPORT_DATA_BUTTON },
279     { "improveBrowsingExperience", IDS_OPTIONS_IMPROVE_BROWSING_EXPERIENCE },
280     { "languageAndSpellCheckSettingsButton",
281       IDS_OPTIONS_SETTINGS_LANGUAGE_AND_INPUT_SETTINGS },
282     { "linkDoctorPref", IDS_OPTIONS_LINKDOCTOR_PREF },
283     { "manageAutofillSettings", IDS_OPTIONS_MANAGE_AUTOFILL_SETTINGS_LINK },
284     { "manageLanguages", IDS_OPTIONS_TRANSLATE_MANAGE_LANGUAGES },
285     { "managePasswords", IDS_OPTIONS_PASSWORDS_MANAGE_PASSWORDS_LINK },
286     { "networkPredictionEnabledDescription",
287       IDS_NETWORK_PREDICTION_ENABLED_DESCRIPTION },
288     { "passwordsAndAutofillGroupName",
289       IDS_OPTIONS_PASSWORDS_AND_FORMS_GROUP_NAME },
290     { "passwordManagerEnabled", IDS_OPTIONS_PASSWORD_MANAGER_ENABLE },
291     { "privacyClearDataButton", IDS_OPTIONS_PRIVACY_CLEAR_DATA_BUTTON },
292     { "privacyContentSettingsButton",
293       IDS_OPTIONS_PRIVACY_CONTENT_SETTINGS_BUTTON },
294     { "profileAddPersonEnable", IDS_PROFILE_ADD_PERSON_ENABLE },
295     { "profileBrowserGuestEnable", IDS_PROFILE_BROWSER_GUEST_ENABLE },
296     { "profilesCreate", IDS_PROFILES_CREATE_BUTTON_LABEL },
297     { "profilesDelete", IDS_PROFILES_DELETE_BUTTON_LABEL },
298     { "profilesDeleteSingle", IDS_PROFILES_DELETE_SINGLE_BUTTON_LABEL },
299     { "profilesListItemCurrent", IDS_PROFILES_LIST_ITEM_CURRENT },
300     { "profilesManage", IDS_PROFILES_MANAGE_BUTTON_LABEL },
301     { "profilesSupervisedDashboardTip",
302       IDS_PROFILES_SUPERVISED_USER_DASHBOARD_TIP },
303 #if defined(ENABLE_SETTINGS_APP)
304     { "profilesAppListSwitch", IDS_SETTINGS_APP_PROFILES_SWITCH_BUTTON_LABEL },
305 #endif
306     { "proxiesLabelExtension", IDS_OPTIONS_EXTENSION_PROXIES_LABEL },
307     { "proxiesLabelSystem", IDS_OPTIONS_SYSTEM_PROXIES_LABEL,
308       IDS_PRODUCT_NAME },
309     { "resetProfileSettings", IDS_RESET_PROFILE_SETTINGS_BUTTON },
310     { "resetProfileSettingsDescription",
311       IDS_RESET_PROFILE_SETTINGS_DESCRIPTION },
312     { "resetProfileSettingsSectionTitle",
313       IDS_RESET_PROFILE_SETTINGS_SECTION_TITLE },
314     { "safeBrowsingEnableProtection",
315       IDS_OPTIONS_SAFEBROWSING_ENABLEPROTECTION },
316     { "safeBrowsingEnableExtendedReporting",
317       IDS_OPTIONS_SAFEBROWSING_ENABLE_EXTENDED_REPORTING },
318     { "sectionTitleAppearance", IDS_APPEARANCE_GROUP_NAME },
319     { "sectionTitleDefaultBrowser", IDS_OPTIONS_DEFAULTBROWSER_GROUP_NAME },
320     { "sectionTitleUsers", IDS_PROFILES_OPTIONS_GROUP_NAME },
321     { "sectionTitleProxy", IDS_OPTIONS_PROXY_GROUP_NAME },
322     { "sectionTitleSearch", IDS_OPTIONS_DEFAULTSEARCH_GROUP_NAME },
323     { "sectionTitleStartup", IDS_OPTIONS_STARTUP_GROUP_NAME },
324     { "sectionTitleSync", IDS_SYNC_OPTIONS_GROUP_NAME },
325     { "sectionTitleVoice", IDS_OPTIONS_VOICE_GROUP_NAME },
326     { "settingsTitle", IDS_SETTINGS_TITLE },
327     { "showAdvancedSettings", IDS_SETTINGS_SHOW_ADVANCED_SETTINGS },
328     { "spellingConfirmMessage", IDS_CONTENT_CONTEXT_SPELLING_BUBBLE_TEXT },
329     { "spellingConfirmEnable", IDS_CONTENT_CONTEXT_SPELLING_BUBBLE_ENABLE },
330     { "spellingConfirmDisable", IDS_CONTENT_CONTEXT_SPELLING_BUBBLE_DISABLE },
331     { "spellingPref", IDS_OPTIONS_SPELLING_PREF },
332     { "startupRestoreLastSession", IDS_OPTIONS_STARTUP_RESTORE_LAST_SESSION },
333     { "startupSetPages", IDS_OPTIONS_STARTUP_SET_PAGES },
334     { "startupShowNewTab", IDS_OPTIONS_STARTUP_SHOW_NEWTAB },
335     { "startupShowPages", IDS_OPTIONS_STARTUP_SHOW_PAGES },
336     { "suggestPref", IDS_OPTIONS_SUGGEST_PREF },
337     { "supervisedUserLabel", IDS_PROFILES_LIST_SUPERVISED_USER_LABEL },
338     { "syncButtonTextInProgress", IDS_SYNC_NTP_SETUP_IN_PROGRESS },
339     { "syncButtonTextStop", IDS_SYNC_STOP_SYNCING_BUTTON_LABEL },
340     { "themesGallery", IDS_THEMES_GALLERY_BUTTON },
341     { "themesGalleryURL", IDS_THEMES_GALLERY_URL },
342     { "tabsToLinksPref", IDS_OPTIONS_TABS_TO_LINKS_PREF },
343     { "toolbarShowBookmarksBar", IDS_OPTIONS_TOOLBAR_SHOW_BOOKMARKS_BAR },
344     { "toolbarShowHomeButton", IDS_OPTIONS_TOOLBAR_SHOW_HOME_BUTTON },
345     { "translateEnableTranslate",
346       IDS_OPTIONS_TRANSLATE_ENABLE_TRANSLATE },
347 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
348     { "showWindowDecorations", IDS_SHOW_WINDOW_DECORATIONS },
349     { "themesNativeButton", IDS_THEMES_GTK_BUTTON },
350     { "themesSetClassic", IDS_THEMES_SET_CLASSIC },
351 #else
352     { "themes", IDS_THEMES_GROUP_NAME },
353 #endif
354     { "themesReset", IDS_THEMES_RESET_BUTTON },
355     { "accessibilityTitle",
356       IDS_OPTIONS_SETTINGS_SECTION_TITLE_ACCESSIBILITY },
357     { "accessibilityFeaturesLink",
358       IDS_OPTIONS_ACCESSIBILITY_FEATURES_LINK },
359 #if defined(OS_CHROMEOS)
360     { "accessibilityExplanation",
361       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_EXPLANATION },
362     { "accessibilitySettings",
363       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SETTINGS },
364     { "accessibilityHighContrast",
365       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_HIGH_CONTRAST_DESCRIPTION },
366     { "accessibilityScreenMagnifier",
367       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_DESCRIPTION },
368     { "accessibilityTapDragging",
369       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_TOUCHPAD_TAP_DRAGGING_DESCRIPTION },
370     { "accessibilityScreenMagnifierOff",
371       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_OFF },
372     { "accessibilityScreenMagnifierFull",
373       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_FULL },
374     { "accessibilityScreenMagnifierPartial",
375       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_PARTIAL },
376     { "accessibilityLargeCursor",
377       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_LARGE_CURSOR_DESCRIPTION },
378     { "accessibilityStickyKeys",
379       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_STICKY_KEYS_DESCRIPTION },
380     { "accessibilitySpokenFeedback",
381       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SPOKEN_FEEDBACK_DESCRIPTION },
382     { "accessibilityVirtualKeyboard",
383       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_VIRTUAL_KEYBOARD_DESCRIPTION },
384     { "accessibilityAlwaysShowMenu",
385       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SHOULD_ALWAYS_SHOW_MENU },
386     { "accessibilityAutoclick",
387       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DESCRIPTION },
388     { "accessibilityAutoclickDropdown",
389       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DROPDOWN_DESCRIPTION },
390     { "autoclickDelayExtremelyShort",
391       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_EXTREMELY_SHORT },
392     { "autoclickDelayVeryShort",
393       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_VERY_SHORT },
394     { "autoclickDelayShort",
395       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_SHORT },
396     { "autoclickDelayLong",
397       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_LONG },
398     { "autoclickDelayVeryLong",
399       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_AUTOCLICK_DELAY_VERY_LONG },
400     { "consumerManagementDescription",
401       IDS_OPTIONS_CONSUMER_MANAGEMENT_DESCRIPTION },
402     { "consumerManagementEnrollButton",
403       IDS_OPTIONS_CONSUMER_MANAGEMENT_ENROLL_BUTTON },
404     { "consumerManagementEnrollingButton",
405       IDS_OPTIONS_CONSUMER_MANAGEMENT_ENROLLING_BUTTON },
406     { "consumerManagementUnenrollButton",
407       IDS_OPTIONS_CONSUMER_MANAGEMENT_UNENROLL_BUTTON },
408     { "consumerManagementUnenrollingButton",
409       IDS_OPTIONS_CONSUMER_MANAGEMENT_UNENROLLING_BUTTON },
410     { "deviceControlTitle", IDS_OPTIONS_DEVICE_CONTROL_SECTION_TITLE },
411     { "enableContentProtectionAttestation",
412       IDS_OPTIONS_ENABLE_CONTENT_PROTECTION_ATTESTATION },
413     { "factoryResetHeading", IDS_OPTIONS_FACTORY_RESET_HEADING },
414     { "factoryResetTitle", IDS_OPTIONS_FACTORY_RESET },
415     { "factoryResetRestart", IDS_OPTIONS_FACTORY_RESET_BUTTON },
416     { "factoryResetDataRestart", IDS_RELAUNCH_BUTTON },
417     { "factoryResetWarning", IDS_OPTIONS_FACTORY_RESET_WARNING },
418     { "factoryResetHelpUrl", IDS_FACTORY_RESET_HELP_URL },
419     { "changePicture", IDS_OPTIONS_CHANGE_PICTURE },
420     { "changePictureCaption", IDS_OPTIONS_CHANGE_PICTURE_CAPTION },
421     { "datetimeTitle", IDS_OPTIONS_SETTINGS_SECTION_TITLE_DATETIME },
422     { "deviceGroupDescription", IDS_OPTIONS_DEVICE_GROUP_DESCRIPTION },
423     { "deviceGroupPointer", IDS_OPTIONS_DEVICE_GROUP_POINTER_SECTION },
424     { "mouseSpeed", IDS_OPTIONS_SETTINGS_MOUSE_SPEED_DESCRIPTION },
425     { "touchpadSpeed", IDS_OPTIONS_SETTINGS_TOUCHPAD_SPEED_DESCRIPTION },
426     { "enableScreenlock", IDS_OPTIONS_ENABLE_SCREENLOCKER_CHECKBOX },
427     { "internetOptionsButtonTitle", IDS_OPTIONS_INTERNET_OPTIONS_BUTTON_TITLE },
428     { "keyboardSettingsButtonTitle",
429       IDS_OPTIONS_DEVICE_GROUP_KEYBOARD_SETTINGS_BUTTON_TITLE },
430     { "manageAccountsButtonTitle", IDS_OPTIONS_ACCOUNTS_BUTTON_TITLE },
431     { "noPointingDevices", IDS_OPTIONS_NO_POINTING_DEVICES },
432     { "sectionTitleDevice", IDS_OPTIONS_DEVICE_GROUP_NAME },
433     { "sectionTitleInternet", IDS_OPTIONS_INTERNET_OPTIONS_GROUP_LABEL },
434     { "syncOverview", IDS_SYNC_OVERVIEW },
435     { "syncButtonTextStart", IDS_SYNC_SETUP_BUTTON_LABEL },
436     { "thirdPartyImeConfirmEnable", IDS_OK },
437     { "thirdPartyImeConfirmDisable", IDS_CANCEL },
438     { "thirdPartyImeConfirmMessage",
439       IDS_OPTIONS_SETTINGS_LANGUAGES_THIRD_PARTY_WARNING_MESSAGE },
440     { "timezone", IDS_OPTIONS_SETTINGS_TIMEZONE_DESCRIPTION },
441     { "use24HourClock", IDS_OPTIONS_SETTINGS_USE_24HOUR_CLOCK_DESCRIPTION },
442     { "batteryButton", IDS_OPTIONS_SETTINGS_BATTERY_DESCRIPTION},
443     { "storageButton", IDS_OPTIONS_SETTINGS_STORAGE_DESCRIPTION},
444 #else
445     { "proxiesConfigureButton", IDS_OPTIONS_PROXIES_CONFIGURE_BUTTON },
446 #endif
447 #if defined(OS_CHROMEOS) && defined(USE_ASH)
448     { "setWallpaper", IDS_SET_WALLPAPER_BUTTON },
449 #endif
450     { "advancedSectionTitleSystem",
451       IDS_OPTIONS_ADVANCED_SECTION_TITLE_SYSTEM },
452 #if !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
453     { "backgroundModeCheckbox", IDS_OPTIONS_SYSTEM_ENABLE_BACKGROUND_MODE },
454 #endif
455 #if !defined(OS_CHROMEOS)
456     { "gpuModeCheckbox",
457       IDS_OPTIONS_SYSTEM_ENABLE_HARDWARE_ACCELERATION_MODE },
458     { "gpuModeResetRestart",
459       IDS_OPTIONS_SYSTEM_ENABLE_HARDWARE_ACCELERATION_MODE_RESTART },
460     // Strings with product-name substitutions.
461     { "syncOverview", IDS_SYNC_OVERVIEW, IDS_PRODUCT_NAME },
462     { "syncButtonTextStart", IDS_SYNC_SETUP_BUTTON_LABEL },
463 #endif
464     { "syncButtonTextSignIn", IDS_SYNC_START_SYNC_BUTTON_LABEL,
465       IDS_SHORT_PRODUCT_NAME },
466     { "profilesSingleUser", IDS_PROFILES_SINGLE_USER_MESSAGE,
467       IDS_PRODUCT_NAME },
468     { "defaultBrowserUnknown", IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN,
469       IDS_PRODUCT_NAME },
470     { "defaultBrowserUseAsDefault", IDS_OPTIONS_DEFAULTBROWSER_USEASDEFAULT },
471     { "autoLaunchText", IDS_AUTOLAUNCH_TEXT },
472 #if defined(OS_CHROMEOS)
473     { "factoryResetDescription", IDS_OPTIONS_FACTORY_RESET_DESCRIPTION,
474       IDS_SHORT_PRODUCT_NAME },
475 #endif
476     { "languageSectionLabel", IDS_OPTIONS_ADVANCED_LANGUAGE_LABEL,
477       IDS_SHORT_PRODUCT_NAME },
478 #if defined(ENABLE_SERVICE_DISCOVERY)
479     { "cloudPrintDevicesPageButton", IDS_LOCAL_DISCOVERY_DEVICES_PAGE_BUTTON },
480     { "cloudPrintEnableNotificationsLabel",
481       IDS_LOCAL_DISCOVERY_NOTIFICATIONS_ENABLE_CHECKBOX_LABEL },
482 #endif
483   };
484
485 #if defined(ENABLE_SETTINGS_APP)
486   static OptionsStringResource app_resources[] = {
487     { "syncOverview", IDS_SETTINGS_APP_SYNC_OVERVIEW },
488     { "syncButtonTextStart", IDS_SYNC_START_SYNC_BUTTON_LABEL,
489       IDS_SETTINGS_APP_LAUNCHER_PRODUCT_NAME },
490     { "profilesSingleUser", IDS_PROFILES_SINGLE_USER_MESSAGE,
491       IDS_SETTINGS_APP_LAUNCHER_PRODUCT_NAME },
492     { "languageSectionLabel", IDS_OPTIONS_ADVANCED_LANGUAGE_LABEL,
493       IDS_SETTINGS_APP_LAUNCHER_PRODUCT_NAME },
494     { "proxiesLabelSystem", IDS_OPTIONS_SYSTEM_PROXIES_LABEL,
495       IDS_SETTINGS_APP_LAUNCHER_PRODUCT_NAME },
496   };
497   base::DictionaryValue* app_values = NULL;
498   CHECK(values->GetDictionary(kSettingsAppKey, &app_values));
499   RegisterStrings(app_values, app_resources, arraysize(app_resources));
500 #endif
501
502   RegisterStrings(values, resources, arraysize(resources));
503   RegisterTitle(values, "doNotTrackConfirmOverlay",
504                 IDS_OPTIONS_ENABLE_DO_NOT_TRACK_BUBBLE_TITLE);
505   RegisterTitle(values, "spellingConfirmOverlay",
506                 IDS_CONTENT_CONTEXT_SPELLING_ASK_GOOGLE);
507 #if defined(ENABLE_FULL_PRINTING)
508   RegisterCloudPrintValues(values);
509 #endif
510
511   values->SetString("syncLearnMoreURL", chrome::kSyncLearnMoreURL);
512   base::string16 omnibox_url = base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL);
513   values->SetString(
514       "defaultSearchGroupLabel",
515       l10n_util::GetStringFUTF16(IDS_SEARCH_PREF_EXPLANATION, omnibox_url));
516   values->SetString("hotwordLearnMoreURL", chrome::kHotwordLearnMoreURL);
517   RegisterTitle(values, "hotwordConfirmOverlay",
518                 IDS_HOTWORD_CONFIRM_BUBBLE_TITLE);
519
520 #if defined(OS_CHROMEOS)
521   Profile* profile = Profile::FromWebUI(web_ui());
522   std::string username = profile->GetProfileName();
523   if (username.empty()) {
524     user_manager::User* user =
525         chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
526     if (user && (user->GetType() != user_manager::USER_TYPE_GUEST))
527       username = user->email();
528   }
529   if (!username.empty())
530     username = gaia::SanitizeEmail(gaia::CanonicalizeEmail(username));
531
532   values->SetString("username", username);
533 #endif
534
535   // Pass along sync status early so it will be available during page init.
536   values->Set("syncData", GetSyncStateDictionary().release());
537
538   values->SetString("privacyLearnMoreURL", chrome::kPrivacyLearnMoreURL);
539   values->SetString("doNotTrackLearnMoreURL", chrome::kDoNotTrackLearnMoreURL);
540
541 #if !defined(OS_CHROMEOS)
542   values->SetBoolean("metricsReportingEnabledAtStart",
543        ChromeMetricsServiceAccessor::IsMetricsReportingEnabled());
544 #endif
545
546 #if defined(OS_CHROMEOS)
547   // TODO(pastarmovj): replace this with a call to the CrosSettings list
548   // handling functionality to come.
549   values->Set("timezoneList", chromeos::system::GetTimezoneList().release());
550
551   values->SetString("accessibilityLearnMoreURL",
552                     chrome::kChromeAccessibilityHelpURL);
553
554   std::string settings_url = std::string("chrome-extension://") +
555       extension_misc::kChromeVoxExtensionId +
556       chrome::kChromeAccessibilitySettingsURL;
557
558   values->SetString("accessibilitySettingsURL",
559                     settings_url);
560
561   values->SetString("contentProtectionAttestationLearnMoreURL",
562                     chrome::kAttestationForContentProtectionLearnMoreURL);
563
564   // Creates magnifierList.
565   scoped_ptr<base::ListValue> magnifier_list(new base::ListValue);
566
567   scoped_ptr<base::ListValue> option_full(new base::ListValue);
568   option_full->AppendInteger(ash::MAGNIFIER_FULL);
569   option_full->AppendString(l10n_util::GetStringUTF16(
570       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_FULL));
571   magnifier_list->Append(option_full.release());
572
573   scoped_ptr<base::ListValue> option_partial(new base::ListValue);
574   option_partial->AppendInteger(ash::MAGNIFIER_PARTIAL);
575   option_partial->Append(new base::StringValue(l10n_util::GetStringUTF16(
576       IDS_OPTIONS_SETTINGS_ACCESSIBILITY_SCREEN_MAGNIFIER_PARTIAL)));
577   magnifier_list->Append(option_partial.release());
578
579   values->Set("magnifierList", magnifier_list.release());
580 #endif
581
582 #if defined(OS_MACOSX)
583   values->SetString("macPasswordsWarning",
584       l10n_util::GetStringUTF16(IDS_OPTIONS_PASSWORDS_MAC_WARNING));
585   values->SetBoolean("multiple_profiles",
586       g_browser_process->profile_manager()->GetNumberOfProfiles() > 1);
587 #endif
588
589   if (ShouldShowMultiProfilesUserList())
590     values->Set("profilesInfo", GetProfilesInfoList().release());
591
592   values->SetBoolean("profileIsGuest",
593                      Profile::FromWebUI(web_ui())->IsOffTheRecord());
594
595   values->SetBoolean("profileIsSupervised",
596                      Profile::FromWebUI(web_ui())->IsSupervised());
597
598 #if !defined(OS_CHROMEOS)
599   values->SetBoolean(
600       "gpuEnabledAtStart",
601       g_browser_process->gpu_mode_manager()->initial_gpu_mode_pref());
602 #endif
603
604 #if defined(ENABLE_SERVICE_DISCOVERY)
605   values->SetBoolean("cloudPrintHideNotificationsCheckbox",
606                      !local_discovery::PrivetNotificationService::IsEnabled());
607 #endif
608
609   values->SetBoolean("cloudPrintShowMDnsOptions",
610                      cloud_print_mdns_ui_enabled_);
611
612   values->SetString("cloudPrintLearnMoreURL", chrome::kCloudPrintLearnMoreURL);
613
614   values->SetString("languagesLearnMoreURL",
615                     chrome::kLanguageSettingsLearnMoreUrl);
616
617   values->SetBoolean(
618       "easyUnlockAllowed",
619       EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->IsAllowed());
620   values->SetString("easyUnlockLearnMoreURL", chrome::kEasyUnlockLearnMoreUrl);
621
622 #if defined(OS_CHROMEOS)
623   values->SetBoolean(
624       "consumerManagementEnabled",
625       CommandLine::ForCurrentProcess()->HasSwitch(
626           chromeos::switches::kEnableConsumerManagement));
627
628   RegisterTitle(values, "thirdPartyImeConfirmOverlay",
629                 IDS_OPTIONS_SETTINGS_LANGUAGES_THIRD_PARTY_WARNING_TITLE);
630 #endif
631
632   values->SetBoolean("showSetDefault", ShouldShowSetDefaultBrowser());
633
634   values->SetBoolean("allowAdvancedSettings", ShouldAllowAdvancedSettings());
635
636   values->SetBoolean("websiteSettingsManagerEnabled",
637                      CommandLine::ForCurrentProcess()->HasSwitch(
638                          switches::kEnableWebsiteSettingsManager));
639
640   values->SetBoolean("usingNewProfilesUI", switches::IsNewAvatarMenu());
641 }
642
643 #if defined(ENABLE_FULL_PRINTING)
644 void BrowserOptionsHandler::RegisterCloudPrintValues(
645     base::DictionaryValue* values) {
646   values->SetString("cloudPrintOptionLabel",
647                     l10n_util::GetStringFUTF16(
648                         IDS_CLOUD_PRINT_CHROMEOS_OPTION_LABEL,
649                         l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));
650 }
651 #endif  // defined(ENABLE_FULL_PRINTING)
652
653 void BrowserOptionsHandler::RegisterMessages() {
654   web_ui()->RegisterMessageCallback(
655       "becomeDefaultBrowser",
656       base::Bind(&BrowserOptionsHandler::BecomeDefaultBrowser,
657                  base::Unretained(this)));
658   web_ui()->RegisterMessageCallback(
659       "setDefaultSearchEngine",
660       base::Bind(&BrowserOptionsHandler::SetDefaultSearchEngine,
661                  base::Unretained(this)));
662   web_ui()->RegisterMessageCallback(
663       "deleteProfile",
664       base::Bind(&BrowserOptionsHandler::DeleteProfile,
665                  base::Unretained(this)));
666   web_ui()->RegisterMessageCallback(
667       "themesReset",
668       base::Bind(&BrowserOptionsHandler::ThemesReset,
669                  base::Unretained(this)));
670   web_ui()->RegisterMessageCallback(
671       "requestProfilesInfo",
672       base::Bind(&BrowserOptionsHandler::HandleRequestProfilesInfo,
673                  base::Unretained(this)));
674 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
675   web_ui()->RegisterMessageCallback(
676       "themesSetNative",
677       base::Bind(&BrowserOptionsHandler::ThemesSetNative,
678                  base::Unretained(this)));
679 #endif
680   web_ui()->RegisterMessageCallback(
681       "selectDownloadLocation",
682       base::Bind(&BrowserOptionsHandler::HandleSelectDownloadLocation,
683                  base::Unretained(this)));
684   web_ui()->RegisterMessageCallback(
685       "autoOpenFileTypesAction",
686       base::Bind(&BrowserOptionsHandler::HandleAutoOpenButton,
687                  base::Unretained(this)));
688   web_ui()->RegisterMessageCallback(
689       "defaultFontSizeAction",
690       base::Bind(&BrowserOptionsHandler::HandleDefaultFontSize,
691                  base::Unretained(this)));
692   web_ui()->RegisterMessageCallback(
693       "defaultZoomFactorAction",
694       base::Bind(&BrowserOptionsHandler::HandleDefaultZoomFactor,
695                  base::Unretained(this)));
696 #if defined(OS_WIN) || defined(OS_MACOSX)
697   web_ui()->RegisterMessageCallback(
698       "showManageSSLCertificates",
699       base::Bind(&BrowserOptionsHandler::ShowManageSSLCertificates,
700                  base::Unretained(this)));
701 #endif
702 #if defined(OS_CHROMEOS)
703   web_ui()->RegisterMessageCallback(
704       "openWallpaperManager",
705       base::Bind(&BrowserOptionsHandler::HandleOpenWallpaperManager,
706                  base::Unretained(this)));
707   web_ui()->RegisterMessageCallback(
708       "virtualKeyboardChange",
709       base::Bind(&BrowserOptionsHandler::VirtualKeyboardChangeCallback,
710                  base::Unretained(this)));
711   web_ui()->RegisterMessageCallback(
712        "onPowerwashDialogShow",
713        base::Bind(&BrowserOptionsHandler::OnPowerwashDialogShow,
714                   base::Unretained(this)));
715   web_ui()->RegisterMessageCallback(
716       "performFactoryResetRestart",
717       base::Bind(&BrowserOptionsHandler::PerformFactoryResetRestart,
718                  base::Unretained(this)));
719 #else
720   web_ui()->RegisterMessageCallback(
721       "restartBrowser",
722       base::Bind(&BrowserOptionsHandler::HandleRestartBrowser,
723                  base::Unretained(this)));
724   web_ui()->RegisterMessageCallback(
725       "showNetworkProxySettings",
726       base::Bind(&BrowserOptionsHandler::ShowNetworkProxySettings,
727                  base::Unretained(this)));
728 #endif  // defined(OS_CHROMEOS)
729
730 #if defined(ENABLE_SERVICE_DISCOVERY)
731   if (cloud_print_mdns_ui_enabled_) {
732     web_ui()->RegisterMessageCallback(
733         "showCloudPrintDevicesPage",
734         base::Bind(&BrowserOptionsHandler::ShowCloudPrintDevicesPage,
735                    base::Unretained(this)));
736   }
737 #endif
738   web_ui()->RegisterMessageCallback(
739       "requestHotwordAvailable",
740       base::Bind(&BrowserOptionsHandler::HandleRequestHotwordAvailable,
741                  base::Unretained(this)));
742
743   web_ui()->RegisterMessageCallback(
744       "launchHotwordAudioVerificationApp",
745       base::Bind(
746           &BrowserOptionsHandler::HandleLaunchHotwordAudioVerificationApp,
747           base::Unretained(this)));
748
749   web_ui()->RegisterMessageCallback(
750       "launchEasyUnlockSetup",
751       base::Bind(&BrowserOptionsHandler::HandleLaunchEasyUnlockSetup,
752                base::Unretained(this)));
753 #if defined(OS_WIN)
754   web_ui()->RegisterMessageCallback(
755       "refreshExtensionControlIndicators",
756       base::Bind(
757           &BrowserOptionsHandler::HandleRefreshExtensionControlIndicators,
758           base::Unretained(this)));
759 #endif  // defined(OS_WIN)
760   web_ui()->RegisterMessageCallback("metricsReportingCheckboxChanged",
761       base::Bind(&BrowserOptionsHandler::HandleMetricsReportingChange,
762                  base::Unretained(this)));
763 }
764
765 void BrowserOptionsHandler::Uninitialize() {
766   registrar_.RemoveAll();
767 #if defined(OS_WIN)
768   ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))->RemoveObserver(this);
769 #endif
770 #if defined(OS_CHROMEOS)
771   policy::ConsumerManagementService* consumer_management =
772       g_browser_process->platform_part()->browser_policy_connector_chromeos()->
773           GetConsumerManagementService();
774   if (consumer_management)
775     consumer_management->RemoveObserver(this);
776 #endif
777 }
778
779 void BrowserOptionsHandler::OnStateChanged() {
780   UpdateSyncState();
781 }
782
783 void BrowserOptionsHandler::GoogleSigninSucceeded(const std::string& account_id,
784                                                   const std::string& username,
785                                                   const std::string& password) {
786   OnStateChanged();
787 }
788
789 void BrowserOptionsHandler::GoogleSignedOut(const std::string& account_id,
790                                             const std::string& username) {
791   OnStateChanged();
792 }
793
794 void BrowserOptionsHandler::PageLoadStarted() {
795   page_initialized_ = false;
796 }
797
798 void BrowserOptionsHandler::InitializeHandler() {
799   Profile* profile = Profile::FromWebUI(web_ui());
800   PrefService* prefs = profile->GetPrefs();
801
802   ProfileSyncService* sync_service(
803       ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile));
804   // TODO(blundell): Use a ScopedObserver to observe the PSS so that cleanup on
805   // destruction is automatic.
806   if (sync_service)
807     sync_service->AddObserver(this);
808
809   SigninManagerBase* signin_manager(
810       SigninManagerFactory::GetInstance()->GetForProfile(profile));
811   if (signin_manager)
812     signin_observer_.Add(signin_manager);
813
814   // Create our favicon data source.
815   content::URLDataSource::Add(
816       profile, new FaviconSource(profile, FaviconSource::FAVICON));
817
818   default_browser_policy_.Init(
819       prefs::kDefaultBrowserSettingEnabled,
820       g_browser_process->local_state(),
821       base::Bind(&BrowserOptionsHandler::UpdateDefaultBrowserState,
822                  base::Unretained(this)));
823
824   registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED,
825                  content::NotificationService::AllSources());
826 #if defined(OS_CHROMEOS)
827   registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED,
828                  content::NotificationService::AllSources());
829 #endif
830   registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
831                  content::Source<ThemeService>(
832                      ThemeServiceFactory::GetForProfile(profile)));
833   registrar_.Add(this, chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED,
834                  content::Source<Profile>(profile));
835   AddTemplateUrlServiceObserver();
836
837 #if defined(OS_WIN)
838   ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))->AddObserver(this);
839
840   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
841   if (!command_line.HasSwitch(switches::kUserDataDir)) {
842     BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
843         base::Bind(&BrowserOptionsHandler::CheckAutoLaunch,
844                    weak_ptr_factory_.GetWeakPtr(),
845                    profile->GetPath()));
846   }
847 #endif
848
849   // No preferences below this point may be modified by guest profiles.
850   if (Profile::FromWebUI(web_ui())->IsGuestSession())
851     return;
852
853   auto_open_files_.Init(
854       prefs::kDownloadExtensionsToOpen, prefs,
855       base::Bind(&BrowserOptionsHandler::SetupAutoOpenFileTypes,
856                  base::Unretained(this)));
857   default_zoom_level_.Init(
858       prefs::kDefaultZoomLevel, prefs,
859       base::Bind(&BrowserOptionsHandler::SetupPageZoomSelector,
860                  base::Unretained(this)));
861   profile_pref_registrar_.Init(prefs);
862   profile_pref_registrar_.Add(
863       prefs::kNetworkPredictionOptions,
864       base::Bind(&BrowserOptionsHandler::SetupNetworkPredictionControl,
865                  base::Unretained(this)));
866   profile_pref_registrar_.Add(
867       prefs::kWebKitDefaultFontSize,
868       base::Bind(&BrowserOptionsHandler::SetupFontSizeSelector,
869                  base::Unretained(this)));
870   profile_pref_registrar_.Add(
871       prefs::kWebKitDefaultFixedFontSize,
872       base::Bind(&BrowserOptionsHandler::SetupFontSizeSelector,
873                  base::Unretained(this)));
874   profile_pref_registrar_.Add(
875       prefs::kSupervisedUsers,
876       base::Bind(&BrowserOptionsHandler::SetupManagingSupervisedUsers,
877                  base::Unretained(this)));
878   profile_pref_registrar_.Add(
879       prefs::kSigninAllowed,
880       base::Bind(&BrowserOptionsHandler::OnSigninAllowedPrefChange,
881                  base::Unretained(this)));
882   profile_pref_registrar_.Add(
883       prefs::kEasyUnlockPairing,
884       base::Bind(&BrowserOptionsHandler::SetupEasyUnlock,
885                  base::Unretained(this)));
886
887 #if defined(OS_WIN)
888   profile_pref_registrar_.Add(
889       prefs::kURLsToRestoreOnStartup,
890       base::Bind(&BrowserOptionsHandler::SetupExtensionControlledIndicators,
891                  base::Unretained(this)));
892   profile_pref_registrar_.Add(
893       prefs::kHomePage,
894       base::Bind(&BrowserOptionsHandler::SetupExtensionControlledIndicators,
895                  base::Unretained(this)));
896 #endif  // defined(OS_WIN)
897
898 #if defined(OS_CHROMEOS)
899   if (!policy_registrar_) {
900     policy_registrar_.reset(new policy::PolicyChangeRegistrar(
901         policy::ProfilePolicyConnectorFactory::GetForProfile(profile)->
902             policy_service(),
903         policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())));
904     policy_registrar_->Observe(
905         policy::key::kUserAvatarImage,
906         base::Bind(&BrowserOptionsHandler::OnUserImagePolicyChanged,
907                    base::Unretained(this)));
908     policy_registrar_->Observe(
909         policy::key::kWallpaperImage,
910         base::Bind(&BrowserOptionsHandler::OnWallpaperPolicyChanged,
911                    base::Unretained(this)));
912   }
913 #else  // !defined(OS_CHROMEOS)
914   profile_pref_registrar_.Add(
915       prefs::kProxy,
916       base::Bind(&BrowserOptionsHandler::SetupProxySettingsSection,
917                  base::Unretained(this)));
918 #endif  // !defined(OS_CHROMEOS)
919 }
920
921 void BrowserOptionsHandler::InitializePage() {
922   page_initialized_ = true;
923
924   OnTemplateURLServiceChanged();
925
926   ObserveThemeChanged();
927   OnStateChanged();
928   UpdateDefaultBrowserState();
929
930   SetupMetricsReportingSettingVisibility();
931   SetupMetricsReportingCheckbox();
932   SetupNetworkPredictionControl();
933   SetupFontSizeSelector();
934   SetupPageZoomSelector();
935   SetupAutoOpenFileTypes();
936   SetupProxySettingsSection();
937   SetupManageCertificatesSection();
938   SetupManagingSupervisedUsers();
939   SetupEasyUnlock();
940   SetupExtensionControlledIndicators();
941
942 #if defined(OS_CHROMEOS)
943   SetupAccessibilityFeatures();
944   policy::BrowserPolicyConnectorChromeOS* connector =
945       g_browser_process->platform_part()->browser_policy_connector_chromeos();
946   if (!connector->IsEnterpriseManaged() &&
947       !user_manager::UserManager::Get()->IsLoggedInAsGuest() &&
948       !user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser()) {
949     web_ui()->CallJavascriptFunction(
950         "BrowserOptions.enableFactoryResetSection");
951   }
952
953   Profile* profile = Profile::FromWebUI(web_ui());
954   OnAccountPictureManagedChanged(
955       policy::ProfilePolicyConnectorFactory::GetForProfile(profile)->
956           policy_service()->GetPolicies(
957               policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
958                                       std::string()))
959              .Get(policy::key::kUserAvatarImage));
960
961   OnWallpaperManagedChanged(
962       chromeos::WallpaperManager::Get()->IsPolicyControlled(
963           user_manager::UserManager::Get()->GetActiveUser()->email()));
964
965   policy::ConsumerManagementService* consumer_management =
966       g_browser_process->platform_part()->browser_policy_connector_chromeos()->
967           GetConsumerManagementService();
968   if (consumer_management) {
969     OnConsumerManagementStatusChanged();
970     consumer_management->AddObserver(this);
971   }
972 #endif
973 }
974
975 // static
976 void BrowserOptionsHandler::CheckAutoLaunch(
977     base::WeakPtr<BrowserOptionsHandler> weak_this,
978     const base::FilePath& profile_path) {
979 #if defined(OS_WIN)
980   DCHECK_CURRENTLY_ON(BrowserThread::FILE);
981
982   // Auto-launch is not supported for secondary profiles yet.
983   if (profile_path.BaseName().value() !=
984           base::ASCIIToUTF16(chrome::kInitialProfile)) {
985     return;
986   }
987
988   // Pass in weak pointer to this to avoid race if BrowserOptionsHandler is
989   // deleted.
990   BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
991       base::Bind(&BrowserOptionsHandler::CheckAutoLaunchCallback,
992                  weak_this,
993                  auto_launch_trial::IsInAutoLaunchGroup(),
994                  auto_launch_util::AutoStartRequested(
995                      profile_path.BaseName().value(),
996                      true,  // Window requested.
997                      base::FilePath())));
998 #endif
999 }
1000
1001 void BrowserOptionsHandler::CheckAutoLaunchCallback(
1002     bool is_in_auto_launch_group,
1003     bool will_launch_at_login) {
1004 #if defined(OS_WIN)
1005   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1006
1007   if (is_in_auto_launch_group) {
1008     web_ui()->RegisterMessageCallback("toggleAutoLaunch",
1009         base::Bind(&BrowserOptionsHandler::ToggleAutoLaunch,
1010         base::Unretained(this)));
1011
1012     base::FundamentalValue enabled(will_launch_at_login);
1013     web_ui()->CallJavascriptFunction("BrowserOptions.updateAutoLaunchState",
1014                                      enabled);
1015   }
1016 #endif
1017 }
1018
1019 bool BrowserOptionsHandler::ShouldShowSetDefaultBrowser() {
1020 #if defined(OS_CHROMEOS)
1021   // We're always the default browser on ChromeOS.
1022   return false;
1023 #else
1024   Profile* profile = Profile::FromWebUI(web_ui());
1025   return !profile->IsGuestSession();
1026 #endif
1027 }
1028
1029 bool BrowserOptionsHandler::ShouldShowMultiProfilesUserList() {
1030 #if defined(OS_CHROMEOS)
1031   // On Chrome OS we use different UI for multi-profiles.
1032   return false;
1033 #else
1034   if (helper::GetDesktopType(web_ui()) != chrome::HOST_DESKTOP_TYPE_NATIVE)
1035     return false;
1036   Profile* profile = Profile::FromWebUI(web_ui());
1037   if (profile->IsGuestSession())
1038     return false;
1039   return profiles::IsMultipleProfilesEnabled();
1040 #endif
1041 }
1042
1043 bool BrowserOptionsHandler::ShouldAllowAdvancedSettings() {
1044 #if defined(OS_CHROMEOS)
1045   // ChromeOS handles guest-mode restrictions in a different manner.
1046   return true;
1047 #else
1048   return !Profile::FromWebUI(web_ui())->IsGuestSession();
1049 #endif
1050 }
1051
1052 void BrowserOptionsHandler::UpdateDefaultBrowserState() {
1053   default_browser_worker_->StartCheckIsDefault();
1054 }
1055
1056 void BrowserOptionsHandler::BecomeDefaultBrowser(const base::ListValue* args) {
1057   // If the default browser setting is managed then we should not be able to
1058   // call this function.
1059   if (default_browser_policy_.IsManaged())
1060     return;
1061
1062   content::RecordAction(UserMetricsAction("Options_SetAsDefaultBrowser"));
1063   default_browser_worker_->StartSetAsDefault();
1064   // Callback takes care of updating UI.
1065
1066   // If the user attempted to make Chrome the default browser, then he/she
1067   // arguably wants to be notified when that changes.
1068   PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
1069   prefs->SetBoolean(prefs::kCheckDefaultBrowser, true);
1070 }
1071
1072 int BrowserOptionsHandler::StatusStringIdForState(
1073     ShellIntegration::DefaultWebClientState state) {
1074   if (state == ShellIntegration::IS_DEFAULT)
1075     return IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;
1076   if (state == ShellIntegration::NOT_DEFAULT)
1077     return IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;
1078   return IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;
1079 }
1080
1081 void BrowserOptionsHandler::SetDefaultWebClientUIState(
1082     ShellIntegration::DefaultWebClientUIState state) {
1083   int status_string_id;
1084
1085   if (state == ShellIntegration::STATE_IS_DEFAULT) {
1086     status_string_id = IDS_OPTIONS_DEFAULTBROWSER_DEFAULT;
1087   } else if (state == ShellIntegration::STATE_NOT_DEFAULT) {
1088     if (ShellIntegration::CanSetAsDefaultBrowser() ==
1089             ShellIntegration::SET_DEFAULT_NOT_ALLOWED) {
1090       status_string_id = IDS_OPTIONS_DEFAULTBROWSER_SXS;
1091     } else {
1092       status_string_id = IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT;
1093     }
1094   } else if (state == ShellIntegration::STATE_UNKNOWN) {
1095     status_string_id = IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN;
1096   } else {
1097     return;  // Still processing.
1098   }
1099
1100   SetDefaultBrowserUIString(status_string_id);
1101 }
1102
1103 bool BrowserOptionsHandler::IsInteractiveSetDefaultPermitted() {
1104   return true;  // This is UI so we can allow it.
1105 }
1106
1107 void BrowserOptionsHandler::SetDefaultBrowserUIString(int status_string_id) {
1108   base::StringValue status_string(
1109       l10n_util::GetStringFUTF16(status_string_id,
1110                                  l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)));
1111
1112   base::FundamentalValue is_default(
1113       status_string_id == IDS_OPTIONS_DEFAULTBROWSER_DEFAULT);
1114
1115   base::FundamentalValue can_be_default(
1116       !default_browser_policy_.IsManaged() &&
1117       (status_string_id == IDS_OPTIONS_DEFAULTBROWSER_DEFAULT ||
1118        status_string_id == IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT));
1119
1120   web_ui()->CallJavascriptFunction(
1121       "BrowserOptions.updateDefaultBrowserState",
1122       status_string, is_default, can_be_default);
1123 }
1124
1125 void BrowserOptionsHandler::OnTemplateURLServiceChanged() {
1126   if (!template_url_service_ || !template_url_service_->loaded())
1127     return;
1128
1129   const TemplateURL* default_url =
1130       template_url_service_->GetDefaultSearchProvider();
1131
1132   int default_index = -1;
1133   base::ListValue search_engines;
1134   TemplateURLService::TemplateURLVector model_urls(
1135       template_url_service_->GetTemplateURLs());
1136   for (size_t i = 0; i < model_urls.size(); ++i) {
1137     if (!model_urls[i]->ShowInDefaultList(
1138             template_url_service_->search_terms_data()))
1139       continue;
1140
1141     base::DictionaryValue* entry = new base::DictionaryValue();
1142     entry->SetString("name", model_urls[i]->short_name());
1143     entry->SetInteger("index", i);
1144     search_engines.Append(entry);
1145     if (model_urls[i] == default_url)
1146       default_index = i;
1147   }
1148
1149   web_ui()->CallJavascriptFunction(
1150       "BrowserOptions.updateSearchEngines",
1151       search_engines,
1152       base::FundamentalValue(default_index),
1153       base::FundamentalValue(
1154           template_url_service_->is_default_search_managed() ||
1155           template_url_service_->IsExtensionControlledDefaultSearch()));
1156
1157   SetupExtensionControlledIndicators();
1158 }
1159
1160 void BrowserOptionsHandler::SetDefaultSearchEngine(
1161     const base::ListValue* args) {
1162   int selected_index = -1;
1163   if (!ExtractIntegerValue(args, &selected_index)) {
1164     NOTREACHED();
1165     return;
1166   }
1167
1168   TemplateURLService::TemplateURLVector model_urls(
1169       template_url_service_->GetTemplateURLs());
1170   if (selected_index >= 0 &&
1171       selected_index < static_cast<int>(model_urls.size()))
1172     template_url_service_->SetUserSelectedDefaultSearchProvider(
1173         model_urls[selected_index]);
1174
1175   content::RecordAction(UserMetricsAction("Options_SearchEngineChanged"));
1176 }
1177
1178 void BrowserOptionsHandler::AddTemplateUrlServiceObserver() {
1179   template_url_service_ =
1180       TemplateURLServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()));
1181   if (template_url_service_) {
1182     template_url_service_->Load();
1183     template_url_service_->AddObserver(this);
1184   }
1185 }
1186
1187 void BrowserOptionsHandler::OnExtensionLoaded(
1188     content::BrowserContext* browser_context,
1189     const Extension* extension) {
1190   SetupExtensionControlledIndicators();
1191 }
1192
1193 void BrowserOptionsHandler::OnExtensionUnloaded(
1194     content::BrowserContext* browser_context,
1195     const Extension* extension,
1196     extensions::UnloadedExtensionInfo::Reason reason) {
1197   SetupExtensionControlledIndicators();
1198 }
1199
1200 void BrowserOptionsHandler::Observe(
1201     int type,
1202     const content::NotificationSource& source,
1203     const content::NotificationDetails& details) {
1204   // Notifications are used to update the UI dynamically when settings change in
1205   // the background. If the UI is currently being loaded, no dynamic updates are
1206   // possible (as the DOM and JS are not fully loaded) or necessary (as
1207   // InitializePage() will update the UI at the end of the load).
1208   if (!page_initialized_)
1209     return;
1210
1211   switch (type) {
1212     case chrome::NOTIFICATION_BROWSER_THEME_CHANGED:
1213       ObserveThemeChanged();
1214       break;
1215 #if defined(OS_CHROMEOS)
1216     case chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED:
1217       UpdateAccountPicture();
1218       break;
1219 #endif
1220     case chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED:
1221     SendProfilesInfo();
1222       break;
1223     case chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED:
1224       // Update our sync/signin status display.
1225       OnStateChanged();
1226       break;
1227     default:
1228       NOTREACHED();
1229   }
1230 }
1231
1232 void BrowserOptionsHandler::ToggleAutoLaunch(const base::ListValue* args) {
1233 #if defined(OS_WIN)
1234   if (!auto_launch_trial::IsInAutoLaunchGroup())
1235     return;
1236
1237   bool enable;
1238   CHECK_EQ(args->GetSize(), 1U);
1239   CHECK(args->GetBoolean(0, &enable));
1240
1241   Profile* profile = Profile::FromWebUI(web_ui());
1242   content::BrowserThread::PostTask(
1243       content::BrowserThread::FILE, FROM_HERE,
1244       enable ?
1245           base::Bind(&auto_launch_util::EnableForegroundStartAtLogin,
1246                      profile->GetPath().BaseName().value(), base::FilePath()) :
1247           base::Bind(&auto_launch_util::DisableForegroundStartAtLogin,
1248                       profile->GetPath().BaseName().value()));
1249 #endif  // OS_WIN
1250 }
1251
1252 scoped_ptr<base::ListValue> BrowserOptionsHandler::GetProfilesInfoList() {
1253   ProfileInfoCache& cache =
1254       g_browser_process->profile_manager()->GetProfileInfoCache();
1255   scoped_ptr<base::ListValue> profile_info_list(new base::ListValue);
1256   base::FilePath current_profile_path =
1257       web_ui()->GetWebContents()->GetBrowserContext()->GetPath();
1258
1259   for (size_t i = 0, e = cache.GetNumberOfProfiles(); i < e; ++i) {
1260     base::DictionaryValue* profile_value = new base::DictionaryValue();
1261     profile_value->SetString("name", cache.GetNameOfProfileAtIndex(i));
1262     base::FilePath profile_path = cache.GetPathOfProfileAtIndex(i);
1263     profile_value->Set("filePath", base::CreateFilePathValue(profile_path));
1264     profile_value->SetBoolean("isCurrentProfile",
1265                               profile_path == current_profile_path);
1266     profile_value->SetBoolean("isSupervised",
1267                               cache.ProfileIsSupervisedAtIndex(i));
1268
1269     bool is_gaia_picture =
1270         cache.IsUsingGAIAPictureOfProfileAtIndex(i) &&
1271         cache.GetGAIAPictureOfProfileAtIndex(i);
1272     if (is_gaia_picture) {
1273       gfx::Image icon = profiles::GetAvatarIconForWebUI(
1274           cache.GetAvatarIconOfProfileAtIndex(i), true);
1275       profile_value->SetString("iconURL",
1276           webui::GetBitmapDataUrl(icon.AsBitmap()));
1277     } else {
1278       size_t icon_index = cache.GetAvatarIconIndexOfProfileAtIndex(i);
1279       profile_value->SetString("iconURL",
1280                                profiles::GetDefaultAvatarIconUrl(icon_index));
1281     }
1282
1283     profile_info_list->Append(profile_value);
1284   }
1285
1286   return profile_info_list.Pass();
1287 }
1288
1289 void BrowserOptionsHandler::SendProfilesInfo() {
1290   if (!ShouldShowMultiProfilesUserList())
1291     return;
1292   web_ui()->CallJavascriptFunction("BrowserOptions.setProfilesInfo",
1293                                    *GetProfilesInfoList());
1294 }
1295
1296 void BrowserOptionsHandler::DeleteProfile(const base::ListValue* args) {
1297   DCHECK(args);
1298   const base::Value* file_path_value;
1299   if (!args->Get(0, &file_path_value))
1300     return;
1301
1302   base::FilePath file_path;
1303   if (!base::GetValueAsFilePath(*file_path_value, &file_path))
1304     return;
1305   helper::DeleteProfileAtPath(file_path, web_ui());
1306 }
1307
1308 void BrowserOptionsHandler::ObserveThemeChanged() {
1309   Profile* profile = Profile::FromWebUI(web_ui());
1310   ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile);
1311   bool is_system_theme = false;
1312
1313 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1314   bool profile_is_supervised = profile->IsSupervised();
1315   is_system_theme = theme_service->UsingSystemTheme();
1316   base::FundamentalValue native_theme_enabled(!is_system_theme &&
1317                                               !profile_is_supervised);
1318   web_ui()->CallJavascriptFunction("BrowserOptions.setNativeThemeButtonEnabled",
1319                                    native_theme_enabled);
1320 #endif
1321
1322   bool is_classic_theme = !is_system_theme &&
1323                           theme_service->UsingDefaultTheme();
1324   base::FundamentalValue enabled(!is_classic_theme);
1325   web_ui()->CallJavascriptFunction("BrowserOptions.setThemesResetButtonEnabled",
1326                                    enabled);
1327 }
1328
1329 void BrowserOptionsHandler::ThemesReset(const base::ListValue* args) {
1330   Profile* profile = Profile::FromWebUI(web_ui());
1331   content::RecordAction(UserMetricsAction("Options_ThemesReset"));
1332   ThemeServiceFactory::GetForProfile(profile)->UseDefaultTheme();
1333 }
1334
1335 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1336 void BrowserOptionsHandler::ThemesSetNative(const base::ListValue* args) {
1337   content::RecordAction(UserMetricsAction("Options_GtkThemeSet"));
1338   Profile* profile = Profile::FromWebUI(web_ui());
1339   ThemeServiceFactory::GetForProfile(profile)->UseSystemTheme();
1340 }
1341 #endif
1342
1343 #if defined(OS_CHROMEOS)
1344 void BrowserOptionsHandler::UpdateAccountPicture() {
1345   std::string email =
1346       user_manager::UserManager::Get()->GetLoggedInUser()->email();
1347   if (!email.empty()) {
1348     web_ui()->CallJavascriptFunction("BrowserOptions.updateAccountPicture");
1349     base::StringValue email_value(email);
1350     web_ui()->CallJavascriptFunction("BrowserOptions.updateAccountPicture",
1351                                      email_value);
1352   }
1353 }
1354
1355 void BrowserOptionsHandler::OnAccountPictureManagedChanged(bool managed) {
1356   web_ui()->CallJavascriptFunction("BrowserOptions.setAccountPictureManaged",
1357                                    base::FundamentalValue(managed));
1358 }
1359
1360 void BrowserOptionsHandler::OnWallpaperManagedChanged(bool managed) {
1361 #if defined(USE_ATHENA)
1362   // In Athena, we don't allow customizing wallpaper right now.
1363   // TODO(mukai|bshe): remove this.  http://crbug.com/408734
1364   managed = true;
1365 #endif
1366   web_ui()->CallJavascriptFunction("BrowserOptions.setWallpaperManaged",
1367                                    base::FundamentalValue(managed));
1368 }
1369 #endif
1370
1371 scoped_ptr<base::DictionaryValue>
1372 BrowserOptionsHandler::GetSyncStateDictionary() {
1373   // The items which are to be written into |sync_status| are also described in
1374   // chrome/browser/resources/options/browser_options.js in @typedef
1375   // for SyncStatus. Please update it whenever you add or remove any keys here.
1376   scoped_ptr<base::DictionaryValue> sync_status(new base::DictionaryValue);
1377   Profile* profile = Profile::FromWebUI(web_ui());
1378   if (profile->IsGuestSession()) {
1379     // Cannot display signin status when running in guest mode on chromeos
1380     // because there is no SigninManager.
1381     sync_status->SetBoolean("signinAllowed", false);
1382     return sync_status.Pass();
1383   }
1384
1385   sync_status->SetBoolean("supervisedUser", profile->IsSupervised());
1386
1387   bool signout_prohibited = false;
1388 #if !defined(OS_CHROMEOS)
1389   // Signout is not allowed if the user has policy (crbug.com/172204).
1390   signout_prohibited =
1391       SigninManagerFactory::GetForProfile(profile)->IsSignoutProhibited();
1392 #endif
1393
1394   ProfileSyncService* service =
1395       ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
1396   SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile);
1397   DCHECK(signin);
1398   sync_status->SetBoolean("signoutAllowed", !signout_prohibited);
1399   sync_status->SetBoolean("signinAllowed", signin->IsSigninAllowed());
1400   sync_status->SetBoolean("syncSystemEnabled", (service != NULL));
1401   sync_status->SetBoolean("setupCompleted",
1402                           service && service->HasSyncSetupCompleted());
1403   sync_status->SetBoolean("setupInProgress",
1404       service && !service->IsManaged() && service->FirstSetupInProgress());
1405
1406   base::string16 status_label;
1407   base::string16 link_label;
1408   bool status_has_error = sync_ui_util::GetStatusLabels(
1409       service, *signin, sync_ui_util::WITH_HTML, &status_label, &link_label) ==
1410           sync_ui_util::SYNC_ERROR;
1411   sync_status->SetString("statusText", status_label);
1412   sync_status->SetString("actionLinkText", link_label);
1413   sync_status->SetBoolean("hasError", status_has_error);
1414
1415   sync_status->SetBoolean("managed", service && service->IsManaged());
1416   sync_status->SetBoolean("signedIn", signin->IsAuthenticated());
1417   sync_status->SetBoolean("hasUnrecoverableError",
1418                           service && service->HasUnrecoverableError());
1419
1420   return sync_status.Pass();
1421 }
1422
1423 void BrowserOptionsHandler::HandleSelectDownloadLocation(
1424     const base::ListValue* args) {
1425   PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
1426   select_folder_dialog_ = ui::SelectFileDialog::Create(
1427       this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
1428   ui::SelectFileDialog::FileTypeInfo info;
1429   info.support_drive = true;
1430   select_folder_dialog_->SelectFile(
1431       ui::SelectFileDialog::SELECT_FOLDER,
1432       l10n_util::GetStringUTF16(IDS_OPTIONS_DOWNLOADLOCATION_BROWSE_TITLE),
1433       pref_service->GetFilePath(prefs::kDownloadDefaultDirectory),
1434       &info,
1435       0,
1436       base::FilePath::StringType(),
1437       web_ui()->GetWebContents()->GetTopLevelNativeWindow(),
1438       NULL);
1439 }
1440
1441 void BrowserOptionsHandler::FileSelected(const base::FilePath& path, int index,
1442                                          void* params) {
1443   content::RecordAction(UserMetricsAction("Options_SetDownloadDirectory"));
1444   PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
1445   pref_service->SetFilePath(prefs::kDownloadDefaultDirectory, path);
1446   pref_service->SetFilePath(prefs::kSaveFileDefaultDirectory, path);
1447 }
1448
1449 #if defined(OS_CHROMEOS)
1450 void BrowserOptionsHandler::TouchpadExists(bool exists) {
1451   base::FundamentalValue val(exists);
1452   web_ui()->CallJavascriptFunction("BrowserOptions.showTouchpadControls", val);
1453 }
1454
1455 void BrowserOptionsHandler::MouseExists(bool exists) {
1456   base::FundamentalValue val(exists);
1457   web_ui()->CallJavascriptFunction("BrowserOptions.showMouseControls", val);
1458 }
1459
1460 void BrowserOptionsHandler::OnUserImagePolicyChanged(
1461     const base::Value* previous_policy,
1462     const base::Value* current_policy) {
1463   const bool had_policy = previous_policy;
1464   const bool has_policy = current_policy;
1465   if (had_policy != has_policy)
1466     OnAccountPictureManagedChanged(has_policy);
1467 }
1468
1469 void BrowserOptionsHandler::OnWallpaperPolicyChanged(
1470     const base::Value* previous_policy,
1471     const base::Value* current_policy) {
1472   const bool had_policy = previous_policy;
1473   const bool has_policy = current_policy;
1474   if (had_policy != has_policy)
1475     OnWallpaperManagedChanged(has_policy);
1476 }
1477
1478 void BrowserOptionsHandler::OnPowerwashDialogShow(
1479      const base::ListValue* args) {
1480   UMA_HISTOGRAM_ENUMERATION(
1481       "Reset.ChromeOS.PowerwashDialogShown",
1482       chromeos::reset::DIALOG_FROM_OPTIONS,
1483       chromeos::reset::DIALOG_VIEW_TYPE_SIZE);
1484 }
1485
1486 void BrowserOptionsHandler::OnConsumerManagementStatusChanged() {
1487   const std::string& status = g_browser_process->platform_part()->
1488       browser_policy_connector_chromeos()->GetConsumerManagementService()->
1489           GetStatusString();
1490   web_ui()->CallJavascriptFunction(
1491       "BrowserOptions.setConsumerManagementStatus", base::StringValue(status));
1492 }
1493
1494 #endif  // defined(OS_CHROMEOS)
1495
1496 void BrowserOptionsHandler::UpdateSyncState() {
1497   web_ui()->CallJavascriptFunction("BrowserOptions.updateSyncState",
1498                                    *GetSyncStateDictionary());
1499 }
1500
1501 void BrowserOptionsHandler::OnSigninAllowedPrefChange() {
1502   UpdateSyncState();
1503 }
1504
1505 void BrowserOptionsHandler::HandleAutoOpenButton(const base::ListValue* args) {
1506   content::RecordAction(UserMetricsAction("Options_ResetAutoOpenFiles"));
1507   DownloadManager* manager = BrowserContext::GetDownloadManager(
1508       web_ui()->GetWebContents()->GetBrowserContext());
1509   if (manager)
1510     DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
1511 }
1512
1513 void BrowserOptionsHandler::HandleDefaultFontSize(const base::ListValue* args) {
1514   int font_size;
1515   if (ExtractIntegerValue(args, &font_size)) {
1516     if (font_size > 0) {
1517       PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
1518       pref_service->SetInteger(prefs::kWebKitDefaultFontSize, font_size);
1519       SetupFontSizeSelector();
1520     }
1521   }
1522 }
1523
1524 void BrowserOptionsHandler::HandleDefaultZoomFactor(
1525     const base::ListValue* args) {
1526   double zoom_factor;
1527   if (ExtractDoubleValue(args, &zoom_factor)) {
1528     default_zoom_level_.SetValue(content::ZoomFactorToZoomLevel(zoom_factor));
1529   }
1530 }
1531
1532 void BrowserOptionsHandler::HandleRestartBrowser(const base::ListValue* args) {
1533 #if defined(OS_WIN) && defined(USE_ASH)
1534   // If hardware acceleration is disabled then we need to force restart
1535   // browser in desktop mode.
1536   // TODO(shrikant): Remove this once we fix start mode logic for browser.
1537   // Currently there are issues with determining correct browser mode
1538   // at startup.
1539   if (chrome::GetActiveDesktop() == chrome::HOST_DESKTOP_TYPE_ASH) {
1540     PrefService* pref_service = g_browser_process->local_state();
1541     if (!pref_service->GetBoolean(prefs::kHardwareAccelerationModeEnabled)) {
1542       chrome::AttemptRestartToDesktopMode();
1543       return;
1544     }
1545   }
1546 #endif
1547
1548 #if defined(OS_WIN)
1549   // On Windows Breakpad will upload crash reports if the breakpad pipe name
1550   // environment variable is defined. So we undefine this environment variable
1551   // before restarting, as the restarted processes will inherit their
1552   // environment variables from ours, thus suppressing crash uploads.
1553   PrefService* pref_service = g_browser_process->local_state();
1554   if (!pref_service->GetBoolean(prefs::kMetricsReportingEnabled)) {
1555     HMODULE exe_module = GetModuleHandle(chrome::kBrowserProcessExecutableName);
1556     if (exe_module) {
1557       typedef void (__cdecl *ClearBreakpadPipeEnvVar)();
1558       ClearBreakpadPipeEnvVar clear = reinterpret_cast<ClearBreakpadPipeEnvVar>(
1559           GetProcAddress(exe_module, "ClearBreakpadPipeEnvironmentVariable"));
1560       if (clear)
1561         clear();
1562     }
1563   }
1564 #endif
1565
1566   chrome::AttemptRestart();
1567 }
1568
1569 void BrowserOptionsHandler::HandleRequestProfilesInfo(
1570     const base::ListValue* args) {
1571   SendProfilesInfo();
1572 }
1573
1574 #if !defined(OS_CHROMEOS)
1575 void BrowserOptionsHandler::ShowNetworkProxySettings(
1576     const base::ListValue* args) {
1577   content::RecordAction(UserMetricsAction("Options_ShowProxySettings"));
1578   AdvancedOptionsUtilities::ShowNetworkProxySettings(
1579       web_ui()->GetWebContents());
1580 }
1581 #endif
1582
1583 #if defined(OS_WIN) || defined(OS_MACOSX)
1584 void BrowserOptionsHandler::ShowManageSSLCertificates(
1585     const base::ListValue* args) {
1586   content::RecordAction(UserMetricsAction("Options_ManageSSLCertificates"));
1587   AdvancedOptionsUtilities::ShowManageSSLCertificates(
1588       web_ui()->GetWebContents());
1589 }
1590 #endif
1591
1592 #if defined(ENABLE_SERVICE_DISCOVERY)
1593
1594 void BrowserOptionsHandler::ShowCloudPrintDevicesPage(
1595     const base::ListValue* args) {
1596   content::RecordAction(UserMetricsAction("Options_CloudPrintDevicesPage"));
1597   // Navigate in current tab to devices page.
1598   OpenURLParams params(
1599       GURL(chrome::kChromeUIDevicesURL), Referrer(),
1600       CURRENT_TAB, ui::PAGE_TRANSITION_LINK, false);
1601   web_ui()->GetWebContents()->OpenURL(params);
1602 }
1603
1604 #endif
1605
1606 void BrowserOptionsHandler::HandleRequestHotwordAvailable(
1607     const base::ListValue* args) {
1608   Profile* profile = Profile::FromWebUI(web_ui());
1609   std::string group = base::FieldTrialList::FindFullName("VoiceTrigger");
1610   base::FundamentalValue enabled(
1611       profile->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled));
1612   if (group != "" && group != "Disabled" &&
1613       HotwordServiceFactory::IsHotwordAllowed(profile)) {
1614     // Update the current error value.
1615     HotwordServiceFactory::IsServiceAvailable(profile);
1616     int error = HotwordServiceFactory::GetCurrentError(profile);
1617     if (!error) {
1618       web_ui()->CallJavascriptFunction("BrowserOptions.showHotwordSection",
1619                                        enabled);
1620     } else {
1621       base::string16 hotword_help_url =
1622           base::ASCIIToUTF16(chrome::kHotwordLearnMoreURL);
1623       base::StringValue error_message(l10n_util::GetStringUTF16(error));
1624       if (error == IDS_HOTWORD_GENERIC_ERROR_MESSAGE) {
1625         error_message = base::StringValue(
1626             l10n_util::GetStringFUTF16(error, hotword_help_url));
1627       }
1628       web_ui()->CallJavascriptFunction("BrowserOptions.showHotwordSection",
1629                                        enabled, error_message);
1630     }
1631     if (CommandLine::ForCurrentProcess()->HasSwitch(
1632             switches::kEnableExperimentalHotwording)) {
1633       web_ui()->CallJavascriptFunction(
1634           "BrowserOptions.showHotwordAlwaysOnSection");
1635     }
1636   }
1637 }
1638
1639 void BrowserOptionsHandler::HandleLaunchHotwordAudioVerificationApp(
1640     const base::ListValue* args) {
1641   Profile* profile = Profile::FromWebUI(web_ui());
1642
1643   bool retrain = false;
1644   bool success = args->GetBoolean(0, &retrain);
1645   DCHECK(success);
1646   HotwordService::LaunchMode launch_mode =
1647       HotwordService::HOTWORD_AND_AUDIO_HISTORY;
1648
1649   if (retrain) {
1650     DCHECK(profile->GetPrefs()->GetBoolean(
1651         prefs::kHotwordAlwaysOnSearchEnabled));
1652     DCHECK(profile->GetPrefs()->GetBoolean(
1653         prefs::kHotwordAudioLoggingEnabled));
1654
1655     launch_mode = HotwordService::SPEECH_TRAINING;
1656   } else if (profile->GetPrefs()->GetBoolean(
1657       prefs::kHotwordAudioLoggingEnabled)) {
1658     DCHECK(!profile->GetPrefs()->GetBoolean(
1659         prefs::kHotwordAlwaysOnSearchEnabled));
1660
1661     // TODO(kcarattini): Make sure the Chrome Audio Logging pref is synced
1662     // to the account-level Audio History setting from footprints.
1663     launch_mode = HotwordService::HOTWORD_ONLY;
1664   } else {
1665     DCHECK(!profile->GetPrefs()->GetBoolean(
1666         prefs::kHotwordAlwaysOnSearchEnabled));
1667   }
1668
1669   HotwordService* hotword_service =
1670       HotwordServiceFactory::GetForProfile(profile);
1671   if (!hotword_service)
1672     return;
1673
1674   hotword_service->LaunchHotwordAudioVerificationApp(launch_mode);
1675 }
1676
1677 void BrowserOptionsHandler::HandleLaunchEasyUnlockSetup(
1678     const base::ListValue* args) {
1679   EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->LaunchSetup();
1680 }
1681
1682 void BrowserOptionsHandler::HandleRefreshExtensionControlIndicators(
1683     const base::ListValue* args) {
1684   SetupExtensionControlledIndicators();
1685 }
1686
1687 #if defined(OS_CHROMEOS)
1688 void BrowserOptionsHandler::HandleOpenWallpaperManager(
1689     const base::ListValue* args) {
1690   ash::Shell::GetInstance()->user_wallpaper_delegate()->OpenSetWallpaperPage();
1691 }
1692
1693 void BrowserOptionsHandler::VirtualKeyboardChangeCallback(
1694     const base::ListValue* args) {
1695   bool enabled = false;
1696   args->GetBoolean(0, &enabled);
1697
1698   chromeos::accessibility::EnableVirtualKeyboard(enabled);
1699 }
1700
1701 void BrowserOptionsHandler::PerformFactoryResetRestart(
1702     const base::ListValue* args) {
1703   policy::BrowserPolicyConnectorChromeOS* connector =
1704       g_browser_process->platform_part()->browser_policy_connector_chromeos();
1705   if (connector->IsEnterpriseManaged())
1706     return;
1707
1708   PrefService* prefs = g_browser_process->local_state();
1709   prefs->SetBoolean(prefs::kFactoryResetRequested, true);
1710   prefs->CommitPendingWrite();
1711
1712   // Perform sign out. Current chrome process will then terminate, new one will
1713   // be launched (as if it was a restart).
1714   chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
1715 }
1716
1717 void BrowserOptionsHandler::SetupAccessibilityFeatures() {
1718   PrefService* pref_service = g_browser_process->local_state();
1719   base::FundamentalValue virtual_keyboard_enabled(
1720       pref_service->GetBoolean(prefs::kAccessibilityVirtualKeyboardEnabled));
1721   web_ui()->CallJavascriptFunction(
1722       "BrowserOptions.setVirtualKeyboardCheckboxState",
1723       virtual_keyboard_enabled);
1724 }
1725 #endif
1726
1727 void BrowserOptionsHandler::SetupMetricsReportingSettingVisibility() {
1728 #if defined(GOOGLE_CHROME_BUILD)
1729   // Don't show the reporting setting if we are in the guest mode.
1730   if (Profile::FromWebUI(web_ui())->IsGuestSession()) {
1731     base::FundamentalValue visible(false);
1732     web_ui()->CallJavascriptFunction(
1733         "BrowserOptions.setMetricsReportingSettingVisibility", visible);
1734   }
1735 #endif
1736 }
1737
1738 void BrowserOptionsHandler::SetupNetworkPredictionControl() {
1739   PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
1740
1741   base::DictionaryValue dict;
1742   dict.SetInteger("value",
1743                   pref_service->GetInteger(prefs::kNetworkPredictionOptions));
1744   dict.SetBoolean("disabled",
1745                   !pref_service->IsUserModifiablePreference(
1746                       prefs::kNetworkPredictionOptions));
1747
1748   web_ui()->CallJavascriptFunction("BrowserOptions.setNetworkPredictionValue",
1749                                    dict);
1750 }
1751
1752 void BrowserOptionsHandler::SetupFontSizeSelector() {
1753   PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
1754   const PrefService::Preference* default_font_size =
1755       pref_service->FindPreference(prefs::kWebKitDefaultFontSize);
1756   const PrefService::Preference* default_fixed_font_size =
1757       pref_service->FindPreference(prefs::kWebKitDefaultFixedFontSize);
1758
1759   base::DictionaryValue dict;
1760   dict.SetInteger("value",
1761                   pref_service->GetInteger(prefs::kWebKitDefaultFontSize));
1762
1763   // The font size control displays the value of the default font size, but
1764   // setting it alters both the default font size and the default fixed font
1765   // size. So it must be disabled when either of those prefs is not user
1766   // modifiable.
1767   dict.SetBoolean("disabled",
1768       !default_font_size->IsUserModifiable() ||
1769       !default_fixed_font_size->IsUserModifiable());
1770
1771   // This is a poor man's version of CoreOptionsHandler::CreateValueForPref,
1772   // adapted to consider two prefs. It may be better to refactor
1773   // CreateValueForPref so it can be called from here.
1774   if (default_font_size->IsManaged() || default_fixed_font_size->IsManaged()) {
1775       dict.SetString("controlledBy", "policy");
1776   } else if (default_font_size->IsExtensionControlled() ||
1777              default_fixed_font_size->IsExtensionControlled()) {
1778       dict.SetString("controlledBy", "extension");
1779   }
1780
1781   web_ui()->CallJavascriptFunction("BrowserOptions.setFontSize", dict);
1782 }
1783
1784 void BrowserOptionsHandler::SetupPageZoomSelector() {
1785   PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
1786   double default_zoom_level = pref_service->GetDouble(prefs::kDefaultZoomLevel);
1787   double default_zoom_factor =
1788       content::ZoomLevelToZoomFactor(default_zoom_level);
1789
1790   // Generate a vector of zoom factors from an array of known presets along with
1791   // the default factor added if necessary.
1792   std::vector<double> zoom_factors =
1793       chrome_page_zoom::PresetZoomFactors(default_zoom_factor);
1794
1795   // Iterate through the zoom factors and and build the contents of the
1796   // selector that will be sent to the javascript handler.
1797   // Each item in the list has the following parameters:
1798   // 1. Title (string).
1799   // 2. Value (double).
1800   // 3. Is selected? (bool).
1801   base::ListValue zoom_factors_value;
1802   for (std::vector<double>::const_iterator i = zoom_factors.begin();
1803        i != zoom_factors.end(); ++i) {
1804     base::ListValue* option = new base::ListValue();
1805     double factor = *i;
1806     int percent = static_cast<int>(factor * 100 + 0.5);
1807     option->Append(new base::StringValue(
1808         l10n_util::GetStringFUTF16Int(IDS_ZOOM_PERCENT, percent)));
1809     option->Append(new base::FundamentalValue(factor));
1810     bool selected = content::ZoomValuesEqual(factor, default_zoom_factor);
1811     option->Append(new base::FundamentalValue(selected));
1812     zoom_factors_value.Append(option);
1813   }
1814
1815   web_ui()->CallJavascriptFunction(
1816       "BrowserOptions.setupPageZoomSelector", zoom_factors_value);
1817 }
1818
1819 void BrowserOptionsHandler::SetupAutoOpenFileTypes() {
1820   // Set the hidden state for the AutoOpenFileTypesResetToDefault button.
1821   // We show the button if the user has any auto-open file types registered.
1822   DownloadManager* manager = BrowserContext::GetDownloadManager(
1823       web_ui()->GetWebContents()->GetBrowserContext());
1824   bool display = manager &&
1825       DownloadPrefs::FromDownloadManager(manager)->IsAutoOpenUsed();
1826   base::FundamentalValue value(display);
1827   web_ui()->CallJavascriptFunction(
1828       "BrowserOptions.setAutoOpenFileTypesDisplayed", value);
1829 }
1830
1831 void BrowserOptionsHandler::SetupProxySettingsSection() {
1832 #if !defined(OS_CHROMEOS)
1833   // Disable the button if proxy settings are managed by a sysadmin, overridden
1834   // by an extension, or the browser is running in Windows Ash (on Windows the
1835   // proxy settings dialog will open on the Windows desktop and be invisible
1836   // to a user in Ash).
1837   bool is_win_ash = false;
1838 #if defined(OS_WIN)
1839   chrome::HostDesktopType desktop_type = helper::GetDesktopType(web_ui());
1840   is_win_ash = (desktop_type == chrome::HOST_DESKTOP_TYPE_ASH);
1841 #endif
1842   PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs();
1843   const PrefService::Preference* proxy_config =
1844       pref_service->FindPreference(prefs::kProxy);
1845   bool is_extension_controlled = (proxy_config &&
1846                                   proxy_config->IsExtensionControlled());
1847
1848   base::FundamentalValue disabled(is_win_ash || (proxy_config &&
1849                                   !proxy_config->IsUserModifiable()));
1850   base::FundamentalValue extension_controlled(is_extension_controlled);
1851   web_ui()->CallJavascriptFunction("BrowserOptions.setupProxySettingsButton",
1852                                    disabled, extension_controlled);
1853
1854 #if defined(OS_WIN)
1855   SetupExtensionControlledIndicators();
1856 #endif  // defined(OS_WIN)
1857
1858 #endif  // !defined(OS_CHROMEOS)
1859 }
1860
1861 void BrowserOptionsHandler::SetupManageCertificatesSection() {
1862 #if defined(OS_WIN)
1863   // Disable the button if the settings page is displayed in Windows Ash,
1864   // otherwise the proxy settings dialog will open on the Windows desktop and
1865   // be invisible to a user in Ash.
1866   if (helper::GetDesktopType(web_ui()) == chrome::HOST_DESKTOP_TYPE_ASH) {
1867     base::FundamentalValue enabled(false);
1868     web_ui()->CallJavascriptFunction("BrowserOptions.enableCertificateButton",
1869                                      enabled);
1870   }
1871 #endif  // defined(OS_WIN)
1872 }
1873
1874 void BrowserOptionsHandler::SetupManagingSupervisedUsers() {
1875   bool has_users = !Profile::FromWebUI(web_ui())->
1876       GetPrefs()->GetDictionary(prefs::kSupervisedUsers)->empty();
1877   base::FundamentalValue has_users_value(has_users);
1878   web_ui()->CallJavascriptFunction(
1879       "BrowserOptions.updateManagesSupervisedUsers",
1880       has_users_value);
1881 }
1882
1883 void BrowserOptionsHandler::SetupEasyUnlock() {
1884   // TODO(xiyuan): Update when pairing data is really availble.
1885   const base::ListValue* devices =
1886       EasyUnlockService::Get(Profile::FromWebUI(web_ui()))->GetRemoteDevices();
1887   bool has_pairing = devices && !devices->empty();
1888   base::FundamentalValue has_pairing_value(has_pairing);
1889   web_ui()->CallJavascriptFunction(
1890       "BrowserOptions.updateEasyUnlock",
1891       has_pairing_value);
1892 }
1893
1894 void BrowserOptionsHandler::SetupExtensionControlledIndicators() {
1895 #if defined(OS_WIN)
1896   base::DictionaryValue extension_controlled;
1897
1898   // Check if an extension is overriding the Search Engine.
1899   const extensions::Extension* extension =
1900       extensions::GetExtensionOverridingSearchEngine(
1901           Profile::FromWebUI(web_ui()));
1902   AppendExtensionData("searchEngine", extension, &extension_controlled);
1903
1904   // Check if an extension is overriding the Home page.
1905   extension = extensions::GetExtensionOverridingHomepage(
1906       Profile::FromWebUI(web_ui()));
1907   AppendExtensionData("homePage", extension, &extension_controlled);
1908
1909   // Check if an extension is overriding the Startup pages.
1910   extension = extensions::GetExtensionOverridingStartupPages(
1911       Profile::FromWebUI(web_ui()));
1912   AppendExtensionData("startUpPage", extension, &extension_controlled);
1913
1914   // Check if an extension is overriding the NTP page.
1915   GURL ntp_url(chrome::kChromeUINewTabURL);
1916   bool ignored_param;
1917   extension = NULL;
1918   content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
1919       &ntp_url,
1920       web_ui()->GetWebContents()->GetBrowserContext(),
1921       &ignored_param);
1922   if (ntp_url.SchemeIs("chrome-extension")) {
1923     using extensions::ExtensionRegistry;
1924     ExtensionRegistry* registry = ExtensionRegistry::Get(
1925         Profile::FromWebUI(web_ui()));
1926     extension = registry->GetExtensionById(ntp_url.host(),
1927                                            ExtensionRegistry::ENABLED);
1928   }
1929   AppendExtensionData("newTabPage", extension, &extension_controlled);
1930
1931   // Check if an extension is overwriting the proxy setting.
1932   extension = extensions::GetExtensionOverridingProxy(
1933       Profile::FromWebUI(web_ui()));
1934   AppendExtensionData("proxy", extension, &extension_controlled);
1935
1936   web_ui()->CallJavascriptFunction("BrowserOptions.toggleExtensionIndicators",
1937                                    extension_controlled);
1938 #endif  // defined(OS_WIN)
1939 }
1940
1941 void BrowserOptionsHandler::SetupMetricsReportingCheckbox() {
1942   // This function does not work for ChromeOS and non-official builds.
1943 #if !defined(OS_CHROMEOS) && defined(GOOGLE_CHROME_BUILD)
1944   bool checked = ChromeMetricsServiceAccessor::IsMetricsReportingEnabled();
1945   bool disabled = !IsMetricsReportingUserChangable();
1946
1947   SetMetricsReportingCheckbox(checked, disabled);
1948 #endif
1949 }
1950
1951 void BrowserOptionsHandler::HandleMetricsReportingChange(
1952     const base::ListValue* args) {
1953   bool enable;
1954   if (!args->GetBoolean(0, &enable))
1955     return;
1956
1957   InitiateMetricsReportingChange(
1958       enable,
1959       base::Bind(&BrowserOptionsHandler::MetricsReportingChangeCallback,
1960                  base::Unretained(this)));
1961 }
1962
1963 void BrowserOptionsHandler::MetricsReportingChangeCallback(bool enabled) {
1964   SetMetricsReportingCheckbox(enabled, !IsMetricsReportingUserChangable());
1965 }
1966
1967 void BrowserOptionsHandler::SetMetricsReportingCheckbox(bool checked,
1968                                                         bool disabled) {
1969   web_ui()->CallJavascriptFunction(
1970       "BrowserOptions.setMetricsReportingCheckboxState",
1971       base::FundamentalValue(checked),
1972       base::FundamentalValue(disabled));
1973 }
1974
1975 }  // namespace options