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.
5 #include "chrome/browser/ui/webui/chromeos/login/network_screen_handler.h"
10 #include "base/bind_helpers.h"
11 #include "base/command_line.h"
12 #include "base/logging.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/prefs/pref_registry_simple.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/values.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
22 #include "chrome/browser/chromeos/base/locale_util.h"
23 #include "chrome/browser/chromeos/idle_detector.h"
24 #include "chrome/browser/chromeos/input_method/input_method_util.h"
25 #include "chrome/browser/chromeos/login/input_events_blocker.h"
26 #include "chrome/browser/chromeos/login/login_display_host.h"
27 #include "chrome/browser/chromeos/login/login_display_host_impl.h"
28 #include "chrome/browser/chromeos/login/screens/core_oobe_actor.h"
29 #include "chrome/browser/chromeos/system/input_device_settings.h"
30 #include "chrome/browser/chromeos/system/timezone_util.h"
31 #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
32 #include "chrome/browser/ui/webui/options/chromeos/cros_language_options_handler.h"
33 #include "chrome/common/pref_names.h"
34 #include "chromeos/chromeos_switches.h"
35 #include "chromeos/ime/extension_ime_util.h"
36 #include "chromeos/ime/input_method_manager.h"
37 #include "grit/chromium_strings.h"
38 #include "grit/generated_resources.h"
39 #include "ui/base/l10n/l10n_util.h"
40 #include "ui/gfx/rect.h"
41 #include "ui/views/layout/fill_layout.h"
42 #include "ui/views/widget/widget.h"
46 const char kJsScreenPath[] = "login.NetworkScreen";
48 // JS API callbacks names.
49 const char kJsApiNetworkOnExit[] = "networkOnExit";
50 const char kJsApiNetworkOnLanguageChanged[] = "networkOnLanguageChanged";
51 const char kJsApiNetworkOnInputMethodChanged[] = "networkOnInputMethodChanged";
52 const char kJsApiNetworkOnTimezoneChanged[] = "networkOnTimezoneChanged";
54 const char kUSLayout[] = "xkb:us::eng";
56 const int kDerelectDetectionTimeoutSeconds = 8 * 60 * 60; // 8 hours.
57 const int kDerelectIdleTimeoutSeconds = 5 * 60; // 5 minutes.
58 const int kOobeTimerUpdateIntervalSeconds = 5 * 60; // 5 minutes.
60 // Returns true if element was inserted.
61 bool InsertString(const std::string& str, std::set<std::string>& to) {
62 const std::pair<std::set<std::string>::iterator, bool> result =
67 void AddOptgroupOtherLayouts(base::ListValue* input_methods_list) {
68 base::DictionaryValue* optgroup = new base::DictionaryValue;
71 l10n_util::GetStringUTF16(IDS_OOBE_OTHER_KEYBOARD_LAYOUTS));
72 input_methods_list->Append(optgroup);
75 // For "UI Language" drop-down menu at OOBE screen we need to decide which
76 // entry to mark "selected". If user has just selected "requested_locale",
77 // but "loaded_locale" was actually loaded, we mark original user choice
78 // "selected" only if loaded_locale is a backup for "requested_locale".
79 std::string CalculateSelectedLanguage(const std::string& requested_locale,
80 const std::string& loaded_locale) {
82 std::string resolved_locale;
83 if (!l10n_util::CheckAndResolveLocale(requested_locale, &resolved_locale))
86 if (resolved_locale == loaded_locale)
87 return requested_locale;
96 // NetworkScreenHandler, public: -----------------------------------------------
98 NetworkScreenHandler::NetworkScreenHandler(CoreOobeActor* core_oobe_actor)
99 : BaseScreenHandler(kJsScreenPath),
101 core_oobe_actor_(core_oobe_actor),
102 is_continue_enabled_(false),
103 show_on_init_(false),
104 should_reinitialize_language_keyboard_list_(false),
105 weak_ptr_factory_(this) {
106 DCHECK(core_oobe_actor_);
109 input_method::InputMethodManager* manager =
110 input_method::InputMethodManager::Get();
111 manager->GetComponentExtensionIMEManager()->AddObserver(this);
114 NetworkScreenHandler::~NetworkScreenHandler() {
116 screen_->OnActorDestroyed(this);
118 input_method::InputMethodManager::Get()
119 ->GetComponentExtensionIMEManager()
120 ->RemoveObserver(this);
123 // NetworkScreenHandler, NetworkScreenActor implementation: --------------------
125 void NetworkScreenHandler::SetDelegate(NetworkScreenActor::Delegate* screen) {
129 void NetworkScreenHandler::PrepareToShow() {
132 void NetworkScreenHandler::Show() {
133 if (!page_is_ready()) {
134 show_on_init_ = true;
138 // Here we should handle default locales, for which we do not have UI
139 // resources. This would load fallback, but properly show "selected" locale
141 if (selected_language_code_.empty()) {
142 const StartupCustomizationDocument* startup_manifest =
143 StartupCustomizationDocument::GetInstance();
144 HandleOnLanguageChanged(startup_manifest->initial_locale_default());
147 ShowScreen(OobeUI::kScreenOobeNetwork, NULL);
149 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableDemoMode))
153 StartIdleDetection();
158 void NetworkScreenHandler::Hide() {
161 void NetworkScreenHandler::ShowError(const base::string16& message) {
162 CallJS("showError", message);
165 void NetworkScreenHandler::ClearErrors() {
167 core_oobe_actor_->ClearErrors();
170 void NetworkScreenHandler::ShowConnectingStatus(
172 const base::string16& network_id) {
175 void NetworkScreenHandler::EnableContinue(bool enabled) {
176 is_continue_enabled_ = enabled;
178 CallJS("enableContinueButton", enabled);
181 // NetworkScreenHandler, BaseScreenHandler implementation: --------------------
183 void NetworkScreenHandler::DeclareLocalizedValues(
184 LocalizedValuesBuilder* builder) {
185 if (system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation())
186 builder->Add("networkScreenGreeting", IDS_REMORA_CONFIRM_MESSAGE);
188 builder->Add("networkScreenGreeting", IDS_WELCOME_SCREEN_GREETING);
190 builder->Add("networkScreenTitle", IDS_WELCOME_SCREEN_TITLE);
191 builder->Add("networkScreenAccessibleTitle",
192 IDS_NETWORK_SCREEN_ACCESSIBLE_TITLE);
193 builder->Add("selectLanguage", IDS_LANGUAGE_SELECTION_SELECT);
194 builder->Add("selectKeyboard", IDS_KEYBOARD_SELECTION_SELECT);
195 builder->Add("selectNetwork", IDS_NETWORK_SELECTION_SELECT);
196 builder->Add("selectTimezone", IDS_OPTIONS_SETTINGS_TIMEZONE_DESCRIPTION);
197 builder->Add("proxySettings", IDS_OPTIONS_PROXIES_CONFIGURE_BUTTON);
198 builder->Add("continueButton", IDS_NETWORK_SELECTION_CONTINUE_BUTTON);
201 void NetworkScreenHandler::GetAdditionalParameters(
202 base::DictionaryValue* dict) {
203 dict->Set("languageList", GetLanguageList());
204 dict->Set("inputMethodsList", GetInputMethods());
205 dict->Set("timezoneList", GetTimezoneList());
208 void NetworkScreenHandler::Initialize() {
209 EnableContinue(is_continue_enabled_);
211 show_on_init_ = false;
215 if (should_reinitialize_language_keyboard_list_) {
216 should_reinitialize_language_keyboard_list_ = false;
217 ReloadLocalizedContent();
220 timezone_subscription_ = CrosSettings::Get()->AddSettingsObserver(
222 base::Bind(&NetworkScreenHandler::OnSystemTimezoneChanged,
223 base::Unretained(this)));
224 OnSystemTimezoneChanged();
227 // NetworkScreenHandler, WebUIMessageHandler implementation: -------------------
229 void NetworkScreenHandler::RegisterMessages() {
230 AddCallback(kJsApiNetworkOnExit, &NetworkScreenHandler::HandleOnExit);
231 AddCallback(kJsApiNetworkOnLanguageChanged,
232 &NetworkScreenHandler::HandleOnLanguageChanged);
233 AddCallback(kJsApiNetworkOnInputMethodChanged,
234 &NetworkScreenHandler::HandleOnInputMethodChanged);
235 AddCallback(kJsApiNetworkOnTimezoneChanged,
236 &NetworkScreenHandler::HandleOnTimezoneChanged);
241 void NetworkScreenHandler::RegisterPrefs(PrefRegistrySimple* registry) {
242 registry->RegisterInt64Pref(prefs::kTimeOnOobe, 0);
245 // NetworkScreenHandler, private: ----------------------------------------------
247 void NetworkScreenHandler::HandleOnExit() {
248 idle_detector_.reset();
251 screen_->OnContinuePressed();
254 struct NetworkScreenHandlerOnLanguageChangedCallbackData {
255 explicit NetworkScreenHandlerOnLanguageChangedCallbackData(
256 base::WeakPtr<NetworkScreenHandler>& handler)
257 : handler_(handler) {}
259 base::WeakPtr<NetworkScreenHandler> handler_;
261 // Block UI while resource bundle is being reloaded.
262 chromeos::InputEventsBlocker input_events_blocker;
266 void NetworkScreenHandler::OnLanguageChangedCallback(
267 scoped_ptr<NetworkScreenHandlerOnLanguageChangedCallbackData> context,
268 const std::string& requested_locale,
269 const std::string& loaded_locale,
270 const bool success) {
271 if (!context or !context->handler_)
274 NetworkScreenHandler* const self = context->handler_.get();
277 if (requested_locale == loaded_locale) {
278 self->selected_language_code_ = requested_locale;
280 self->selected_language_code_ =
281 CalculateSelectedLanguage(requested_locale, loaded_locale);
284 self->selected_language_code_ = loaded_locale;
287 self->ReloadLocalizedContent();
289 AccessibilityManager::Get()->OnLocaleChanged();
292 void NetworkScreenHandler::HandleOnLanguageChanged(const std::string& locale) {
293 const std::string app_locale = g_browser_process->GetApplicationLocale();
294 if (app_locale == locale)
297 base::WeakPtr<NetworkScreenHandler> weak_self =
298 weak_ptr_factory_.GetWeakPtr();
299 scoped_ptr<NetworkScreenHandlerOnLanguageChangedCallbackData> callback_data(
300 new NetworkScreenHandlerOnLanguageChangedCallbackData(weak_self));
301 scoped_ptr<locale_util::SwitchLanguageCallback> callback(
302 new locale_util::SwitchLanguageCallback(
303 base::Bind(&NetworkScreenHandler::OnLanguageChangedCallback,
304 base::Passed(callback_data.Pass()))));
305 locale_util::SwitchLanguage(locale,
306 true /* enableLocaleKeyboardLayouts */,
307 true /* login_layouts_only */,
311 void NetworkScreenHandler::HandleOnInputMethodChanged(const std::string& id) {
312 input_method::InputMethodManager::Get()->ChangeInputMethod(id);
315 void NetworkScreenHandler::HandleOnTimezoneChanged(
316 const std::string& timezone_id) {
317 std::string current_timezone_id;
318 CrosSettings::Get()->GetString(kSystemTimezone, ¤t_timezone_id);
319 if (current_timezone_id == timezone_id)
322 CrosSettings::Get()->SetString(kSystemTimezone, timezone_id);
325 void NetworkScreenHandler::OnSystemTimezoneChanged() {
326 std::string current_timezone_id;
327 CrosSettings::Get()->GetString(kSystemTimezone, ¤t_timezone_id);
328 CallJS("setTimezone", current_timezone_id);
331 void NetworkScreenHandler::StartIdleDetection() {
332 if (!idle_detector_.get()) {
333 idle_detector_.reset(
334 new IdleDetector(base::Closure(),
335 base::Bind(&NetworkScreenHandler::OnIdle,
336 weak_ptr_factory_.GetWeakPtr())));
338 idle_detector_->Start(derelict_idle_timeout_);
341 void NetworkScreenHandler::StartOobeTimer() {
342 oobe_timer_.Start(FROM_HERE,
343 oobe_timer_update_interval_,
345 &NetworkScreenHandler::OnOobeTimerUpdate);
348 void NetworkScreenHandler::OnIdle() {
349 LoginDisplayHost* host = LoginDisplayHostImpl::default_host();
350 host->StartDemoAppLaunch();
353 void NetworkScreenHandler::OnOobeTimerUpdate() {
354 time_on_oobe_ += oobe_timer_update_interval_;
356 PrefService* prefs = g_browser_process->local_state();
357 prefs->SetInt64(prefs::kTimeOnOobe, time_on_oobe_.InSeconds());
361 StartIdleDetection();
365 void NetworkScreenHandler::SetupTimeouts() {
366 CommandLine* cmdline = CommandLine::ForCurrentProcess();
369 PrefService* prefs = g_browser_process->local_state();
371 base::TimeDelta::FromSeconds(prefs->GetInt64(prefs::kTimeOnOobe));
373 int derelict_detection_timeout;
374 if (!cmdline->HasSwitch(switches::kDerelictDetectionTimeout) ||
376 cmdline->GetSwitchValueASCII(switches::kDerelictDetectionTimeout),
377 &derelict_detection_timeout)) {
378 derelict_detection_timeout = kDerelectDetectionTimeoutSeconds;
380 derelict_detection_timeout_ =
381 base::TimeDelta::FromSeconds(derelict_detection_timeout);
383 int derelict_idle_timeout;
384 if (!cmdline->HasSwitch(switches::kDerelictIdleTimeout) ||
386 cmdline->GetSwitchValueASCII(switches::kDerelictIdleTimeout),
387 &derelict_idle_timeout)) {
388 derelict_idle_timeout = kDerelectIdleTimeoutSeconds;
390 derelict_idle_timeout_ = base::TimeDelta::FromSeconds(derelict_idle_timeout);
393 int oobe_timer_update_interval;
394 if (!cmdline->HasSwitch(switches::kOobeTimerInterval) ||
396 cmdline->GetSwitchValueASCII(switches::kOobeTimerInterval),
397 &oobe_timer_update_interval)) {
398 oobe_timer_update_interval = kOobeTimerUpdateIntervalSeconds;
400 oobe_timer_update_interval_ =
401 base::TimeDelta::FromSeconds(oobe_timer_update_interval);
403 // In case we'd be derelict before our timer is set to trigger, reduce
404 // the interval so we check again when we're scheduled to go derelict.
405 oobe_timer_update_interval_ =
406 std::max(std::min(oobe_timer_update_interval_,
407 derelict_detection_timeout_ - time_on_oobe_),
408 base::TimeDelta::FromSeconds(0));
411 bool NetworkScreenHandler::IsDerelict() {
412 return time_on_oobe_ >= derelict_detection_timeout_;
415 base::ListValue* NetworkScreenHandler::GetLanguageList() {
416 const std::string app_locale = g_browser_process->GetApplicationLocale();
417 input_method::InputMethodManager* manager =
418 input_method::InputMethodManager::Get();
419 ComponentExtensionIMEManager* comp_manager =
420 manager->GetComponentExtensionIMEManager();
421 input_method::InputMethodDescriptors descriptors;
422 if (extension_ime_util::UseWrappedExtensionKeyboardLayouts()) {
423 if (comp_manager->IsInitialized())
424 descriptors = comp_manager->GetXkbIMEAsInputMethodDescriptor();
426 descriptors = *(manager->GetSupportedInputMethods());
428 base::ListValue* languages_list =
429 options::CrosLanguageOptionsHandler::GetUILanguageList(descriptors);
430 for (size_t i = 0; i < languages_list->GetSize(); ++i) {
431 base::DictionaryValue* language_info = NULL;
432 if (!languages_list->GetDictionary(i, &language_info))
436 language_info->GetString("code", &value);
437 std::string display_name;
438 language_info->GetString("displayName", &display_name);
439 std::string native_name;
440 language_info->GetString("nativeDisplayName", &native_name);
442 // If it's option group divider, add field name.
443 if (value == options::kVendorOtherLanguagesListDivider) {
444 language_info->SetString(
446 l10n_util::GetStringUTF16(IDS_OOBE_OTHER_LANGUAGES));
448 if (display_name != native_name) {
449 display_name = base::StringPrintf("%s - %s",
450 display_name.c_str(),
451 native_name.c_str());
454 language_info->SetString("value", value);
455 language_info->SetString("title", display_name);
456 if (selected_language_code_.empty()) {
457 if (value == app_locale)
458 language_info->SetBoolean("selected", true);
460 if (value == selected_language_code_)
461 language_info->SetBoolean("selected", true);
464 return languages_list;
467 base::DictionaryValue* CreateInputMethodsEntry(
468 const input_method::InputMethodDescriptor& method,
469 const std::string current_input_method_id) {
470 input_method::InputMethodUtil* util =
471 input_method::InputMethodManager::Get()->GetInputMethodUtil();
472 const std::string& ime_id = method.id();
473 scoped_ptr<base::DictionaryValue> input_method(new base::DictionaryValue);
474 input_method->SetString("value", ime_id);
475 input_method->SetString("title", util->GetInputMethodLongName(method));
476 input_method->SetBoolean("selected", ime_id == current_input_method_id);
477 return input_method.release();
480 void NetworkScreenHandler::OnImeComponentExtensionInitialized() {
481 // Refreshes the language and keyboard list once the component extension
482 // IMEs are initialized.
484 ReloadLocalizedContent();
486 should_reinitialize_language_keyboard_list_ = true;
489 void NetworkScreenHandler::ReloadLocalizedContent() {
490 base::DictionaryValue localized_strings;
491 static_cast<OobeUI*>(web_ui()->GetController())
492 ->GetLocalizedStrings(&localized_strings);
493 core_oobe_actor_->ReloadContent(localized_strings);
495 // Buttons are recreated, updated "Continue" button state.
496 EnableContinue(is_continue_enabled_);
500 base::ListValue* NetworkScreenHandler::GetInputMethods() {
501 base::ListValue* input_methods_list = new base::ListValue;
502 input_method::InputMethodManager* manager =
503 input_method::InputMethodManager::Get();
504 input_method::InputMethodUtil* util = manager->GetInputMethodUtil();
505 if (extension_ime_util::UseWrappedExtensionKeyboardLayouts()) {
506 ComponentExtensionIMEManager* comp_manager =
507 manager->GetComponentExtensionIMEManager();
508 if (!comp_manager->IsInitialized()) {
509 input_method::InputMethodDescriptor fallback =
510 util->GetFallbackInputMethodDescriptor();
511 input_methods_list->Append(
512 CreateInputMethodsEntry(fallback, fallback.id()));
513 return input_methods_list;
517 const std::vector<std::string>& hardware_login_input_methods =
518 util->GetHardwareLoginInputMethodIds();
519 manager->EnableLoginLayouts(g_browser_process->GetApplicationLocale(),
520 hardware_login_input_methods);
522 scoped_ptr<input_method::InputMethodDescriptors> input_methods(
523 manager->GetActiveInputMethods());
524 const std::string& current_input_method_id =
525 manager->GetCurrentInputMethod().id();
526 std::set<std::string> input_methods_added;
528 for (std::vector<std::string>::const_iterator i =
529 hardware_login_input_methods.begin();
530 i != hardware_login_input_methods.end();
532 const input_method::InputMethodDescriptor* ime =
533 util->GetInputMethodDescriptorFromId(*i);
535 // Do not crash in case of misconfiguration.
537 input_methods_added.insert(*i);
538 input_methods_list->Append(
539 CreateInputMethodsEntry(*ime, current_input_method_id));
543 bool optgroup_added = false;
544 for (size_t i = 0; i < input_methods->size(); ++i) {
545 // Makes sure the id is in legacy xkb id format.
546 const std::string& ime_id = (*input_methods)[i].id();
547 if (!InsertString(ime_id, input_methods_added))
549 if (!optgroup_added) {
550 optgroup_added = true;
551 AddOptgroupOtherLayouts(input_methods_list);
553 input_methods_list->Append(
554 CreateInputMethodsEntry((*input_methods)[i], current_input_method_id));
556 // "xkb:us::eng" should always be in the list of available layouts.
557 const std::string& us_keyboard_id =
558 extension_ime_util::GetInputMethodIDByKeyboardLayout(kUSLayout);
559 if (input_methods_added.find(us_keyboard_id) == input_methods_added.end()) {
560 const input_method::InputMethodDescriptor* us_eng_descriptor =
561 util->GetInputMethodDescriptorFromId(us_keyboard_id);
562 DCHECK(us_eng_descriptor != NULL);
563 if (!optgroup_added) {
564 optgroup_added = true;
565 AddOptgroupOtherLayouts(input_methods_list);
567 input_methods_list->Append(
568 CreateInputMethodsEntry(*us_eng_descriptor, current_input_method_id));
570 return input_methods_list;
574 base::ListValue* NetworkScreenHandler::GetTimezoneList() {
575 std::string current_timezone_id;
576 CrosSettings::Get()->GetString(kSystemTimezone, ¤t_timezone_id);
578 scoped_ptr<base::ListValue> timezone_list(new base::ListValue);
579 scoped_ptr<base::ListValue> timezones = system::GetTimezoneList().Pass();
580 for (size_t i = 0; i < timezones->GetSize(); ++i) {
581 const base::ListValue* timezone = NULL;
582 CHECK(timezones->GetList(i, &timezone));
584 std::string timezone_id;
585 CHECK(timezone->GetString(0, &timezone_id));
587 std::string timezone_name;
588 CHECK(timezone->GetString(1, &timezone_name));
590 scoped_ptr<base::DictionaryValue> timezone_option(
591 new base::DictionaryValue);
592 timezone_option->SetString("value", timezone_id);
593 timezone_option->SetString("title", timezone_name);
594 timezone_option->SetBoolean("selected", timezone_id == current_timezone_id);
595 timezone_list->Append(timezone_option.release());
598 return timezone_list.release();
601 } // namespace chromeos